text stringlengths 8 4.13M |
|---|
use std::{path::PathBuf, str::FromStr};
use clap::Clap;
/// Options
#[derive(Clap, Debug)]
pub struct Opt {
/// The file to compile
pub file: PathBuf,
/// Output file. Omit for default file (compile) or stdout (other actions).
#[clap(short, long = "out")]
pub out_file: Option<PathBuf>,
/// The action to perform. Accepts: lex, parse, compile, run
#[clap(
short = 'd',
long = "do",
long = "action",
default_value = "compile",
env = "AZUKI_ACTION"
)]
pub action: Action,
/// The optimization passes to perform.
#[clap(long = "opt", env = "AZUKI_OPT")]
pub optimization: Option<Vec<String>>,
#[clap(long)]
pub entry_point: Option<String>,
#[clap(long)]
pub params: Vec<i64>,
#[clap(long = "log", default_value = "warn", env = "AZUKI_LOG")]
pub log_level: tracing_subscriber::filter::LevelFilter,
}
#[derive(Debug, PartialEq, Eq)]
pub enum Action {
Lex,
Parse,
Run,
Compile,
}
impl FromStr for Action {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(match s {
"lex" => Self::Lex,
"parse" => Self::Parse,
"run" => Self::Run,
"compile" => Self::Compile,
_ => return Err(format!("Expected lex, parse, run, got {}", s)),
})
}
}
|
extern crate rustc_serialize;
extern crate hyper;
use std::io::Read;
use rustc_serialize::json;
use rustc_serialize::{Encodable, Encoder};
use hyper::status::StatusCode;
pub const SERVER_ADDR: &'static str = "127.0.0.1:1980";
pub const BOT_ADDR: &'static str = "127.0.0.1:1981";
pub const HTML_ADDR: &'static str = "http://127.0.0.1:1980";
pub const HTML_DATA: &'static str = "data/index.html";
pub const HTML_HEADER: &'static str = "html/header.html";
pub const HTML_FOOTER: &'static str = "html/footer.html";
pub mod escape;
#[derive(Debug, RustcDecodable, RustcEncodable)]
pub struct Message {
pub user: String,
pub text: String,
}
impl Message {
pub fn new(user: String, text: String) -> Message {
Message {
text: text,
user: user,
}
}
}
pub struct UserClient {
username: String,
server_addr: String,
client: hyper::Client,
}
impl UserClient {
pub fn new(username: String, server_addr: String) -> UserClient {
UserClient {
username: username,
server_addr: server_addr,
client: hyper::Client::new(),
}
}
pub fn send_msg(&self, text: String) -> hyper::Result<(StatusCode)> {
let msg: Message = Message { user: self.username.clone(), text: text };
let body: String = json::encode(&msg).unwrap();
let mut response = try!(self.client.post(&self.server_addr).body(&body).send());
Ok(response.status)
}
pub fn get_content(&self) -> hyper::Result<(StatusCode, String)> {
let mut response = try!(self.client.get(&self.server_addr).send());
let mut buf = String::new();
response.read_to_string(&mut buf).unwrap();
Ok((response.status, buf))
}
}
|
use syn::Fields;
pub mod fields;
pub mod bit_index;
pub use fields::build_clauses;
use proc_macro2::TokenStream;
use crate::attributes::{ ParentDataType };
//Compiles the clauses into a struct
pub fn get_struct(fields : &Fields, name : &proc_macro2::Ident, parent_data_type : ParentDataType) -> (TokenStream, TokenStream)
{
//no predicate because there's no enum discrimnant to read
let no_predicate : syn::Expr = syn::parse(quote!{ 0 }.into()).unwrap();
let (clauses, declares, total_size_in_bits) = build_clauses(fields, no_predicate, parent_data_type);
//this literally just wraps the fields in a either a {} or ()
//depending on if the fields are named or unnamed
let wrapped_fields : TokenStream = match fields
{
Fields::Named(_fields_named) => quote!{ Ok(#name{ #(#clauses),* }) },
Fields::Unnamed(_fields_unnamed) => quote!{ Ok(#name( #(#clauses),* )) },
_ => panic!("Packattack only supports reading from structs with named or unamed fields")
};
let fin_fields = quote!
{
#(#declares)*
#wrapped_fields
};
(fin_fields, total_size_in_bits)
} |
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub struct TicTacToe {
board: Vec<String>,
result: String,
turn: i32,
win: bool,
}
#[wasm_bindgen]
impl TicTacToe {
pub fn new() -> TicTacToe {
console_error_panic_hook::set_once();
let board = (1..10).map(|_| {
String::new()
}).collect();
let result = String::new();
let win = false;
let turn = 0;
TicTacToe {board, result, turn, win}
}
pub fn play(&mut self, index: usize) -> String {
if self.board[index] == String::from("")
&& self.turn <= 9 && !self.win {
if self.turn % 2 == 0 {
self.board[index] = String::from("X");
} else {
self.board[index] = String::from("O");
}
self.turn += 1;
}
let win_condition = [
(0, 1, 2),
(3, 4, 5),
(6, 7, 8),
(0, 3, 6),
(1, 4, 7),
(2, 5, 8),
(0, 4, 8),
(2, 4, 6),
];
for arr in win_condition.iter() {
let (a, b, c) = arr;
if self.board[*a] == self.board[*b]
&& self.board[*a] == self.board[*c]
&& self.board[*b] == self.board[*c]
&& self.board[*a] != String::from("") {
if self.board[*a] == "X" {
self.result = String::from("Player 1 Win!");
} else {
self.result = String::from("Player 2 Win!");
}
self.win = true
} else if self.turn == 9 {
self.result = String::from("It's a Draw!");
}
}
self.board[index].clone()
}
pub fn change_text(&self) -> String {
if self.win || self.turn == 9 {
self.result.clone()
} else if self.turn % 2 == 0 {
String::from("Player 1 turn!")
} else {
String::from("Player 2 turn!")
}
}
}
|
use wal::{WalBuilder, WritePayload};
type TestError = Box<dyn std::error::Error + Send + Sync + 'static>;
type Result<T = (), E = TestError> = std::result::Result<T, E>;
#[test]
fn no_concurrency() -> Result {
let dir = test_helpers::tmp_dir()?;
let builder = WalBuilder::new(dir.as_ref());
let mut wal = builder.clone().wal()?;
let data = Vec::from("somedata");
let payload = WritePayload::new(data)?;
let sequence_number = wal.append(payload)?;
wal.sync_all()?;
assert_eq!(0, sequence_number);
let wal_entries: Result<Vec<_>, _> = builder.entries()?.collect();
let wal_entries = wal_entries?;
assert_eq!(1, wal_entries.len());
assert_eq!(b"somedata".as_ref(), wal_entries[0].as_data());
assert_eq!(0, wal_entries[0].sequence_number());
Ok(())
}
|
use quickcheck::Arbitrary;
use quickcheck_macros::quickcheck;
use tabled::{
builder::Builder,
grid::util::string::{string_width, string_width_multiline},
settings::Style,
Table,
};
#[quickcheck]
fn qc_table_is_consistent(data: Vec<Vec<isize>>) -> bool {
let mut builder = Builder::default();
for row in data {
let row = row.into_iter().map(|i| i.to_string()).collect::<Vec<_>>();
builder.push_record(row);
}
let table = builder.build().to_string();
let lines = table.lines().collect::<Vec<_>>();
let lines_has_the_same_length = lines
.iter()
.map(|line| string_width(line))
.all(|line_width| line_width == lines[0].len());
lines_has_the_same_length
}
#[quickcheck]
fn qc_table_is_consistent_with_borders(table_structure: TableStructure) {
let rows = table_structure.rows;
let theme = table_structure.theme;
let builder = Builder::from_iter(rows);
let mut table = builder.build();
set_theme(&mut table, theme);
let output = table.to_string();
if let Some(line) = output.lines().next() {
assert_eq!(string_width(line), string_width_multiline(&output));
}
}
#[derive(Clone, Debug)]
struct TableStructure {
pub rows: Vec<Line>,
pub theme: ThemeFixture,
}
type Line = Vec<String>;
#[derive(Clone, Debug)]
pub enum ThemeFixture {
Empty,
Blank,
Ascii,
Psql,
Markdown,
Modern,
Sharp,
Rounded,
Extended,
Dots,
RestructuredText,
AsciiRounded,
}
impl Arbitrary for TableStructure {
fn arbitrary(g: &mut quickcheck::Gen) -> Self {
Self {
rows: Arbitrary::arbitrary(g),
theme: ThemeFixture::arbitrary(g),
}
}
}
impl Arbitrary for ThemeFixture {
fn arbitrary(g: &mut quickcheck::Gen) -> Self {
use ThemeFixture::*;
g.choose(&[
Empty,
Blank,
Ascii,
Psql,
Markdown,
Modern,
Sharp,
Rounded,
Extended,
Dots,
RestructuredText,
AsciiRounded,
])
.unwrap()
.to_owned()
}
}
fn set_theme(table: &mut Table, theme: ThemeFixture) {
use ThemeFixture::*;
match theme {
Empty => {
table.with(Style::empty());
}
Blank => {
table.with(Style::blank());
}
Ascii => {
table.with(Style::ascii());
}
Psql => {
table.with(Style::psql());
}
Markdown => {
table.with(Style::markdown());
}
Modern => {
table.with(Style::modern());
}
Sharp => {
table.with(Style::sharp());
}
Rounded => {
table.with(Style::rounded());
}
Extended => {
table.with(Style::extended());
}
Dots => {
table.with(Style::dots());
}
RestructuredText => {
table.with(Style::re_structured_text());
}
AsciiRounded => {
table.with(Style::ascii_rounded());
}
}
}
|
use crate::scheduler::gc_work::ProcessEdgesWork;
use crate::scheduler::{GCWork, GCWorker};
use crate::util::{ObjectReference, OpaquePointer};
use crate::vm::{Collection, VMBinding};
use crate::MMTK;
use std::marker::PhantomData;
/// A special processor for Finalizable objects.
// TODO: we should consider if we want to merge FinalizableProcessor with ReferenceProcessor,
// and treat final reference as a special reference type in ReferenceProcessor.
#[derive(Default)]
pub struct FinalizableProcessor {
/// Candidate objects that has finalizers with them
candidates: Vec<ObjectReference>,
/// Index into candidates to record where we are up to in the last scan of the candidates.
/// Index after nursery_index are new objects inserted after the last GC.
nursery_index: usize,
/// Objects that can be finalized. They are actually dead, but we keep them alive
/// until the binding pops them from the queue.
ready_for_finalize: Vec<ObjectReference>,
}
impl FinalizableProcessor {
pub fn new() -> Self {
Self {
candidates: vec![],
nursery_index: 0,
ready_for_finalize: vec![],
}
}
pub fn add(&mut self, object: ObjectReference) {
self.candidates.push(object);
}
fn get_forwarded_finalizable<E: ProcessEdgesWork>(
e: &mut E,
object: ObjectReference,
) -> ObjectReference {
e.trace_object(object)
}
fn return_for_finalize<E: ProcessEdgesWork>(
e: &mut E,
object: ObjectReference,
) -> ObjectReference {
e.trace_object(object)
}
pub fn scan<E: ProcessEdgesWork>(&mut self, tls: OpaquePointer, e: &mut E, nursery: bool) {
let start = if nursery { self.nursery_index } else { 0 };
// We should go through ready_for_finalize objects and keep them alive.
// Unlike candidates, those objects are known to be alive. This means
// theoratically we could do the following loop at any time in a GC (not necessarily after closure phase).
// But we have to iterate through candidates after closure.
self.candidates.append(&mut self.ready_for_finalize);
for reff in self
.candidates
.drain(start..)
.collect::<Vec<ObjectReference>>()
{
trace!("Pop {:?} for finalization", reff);
if reff.is_live() {
let res = FinalizableProcessor::get_forwarded_finalizable(e, reff);
trace!("{:?} is live, push {:?} back to candidates", reff, res);
self.candidates.push(res);
continue;
}
let retained = FinalizableProcessor::return_for_finalize(e, reff);
self.ready_for_finalize.push(retained);
trace!(
"{:?} is not live, push {:?} to ready_for_finalize",
reff,
retained
);
}
e.flush();
self.nursery_index = self.candidates.len();
<<E as ProcessEdgesWork>::VM as VMBinding>::VMCollection::schedule_finalization(tls);
}
pub fn forward<E: ProcessEdgesWork>(&mut self, e: &mut E, _nursery: bool) {
self.candidates
.iter_mut()
.for_each(|reff| *reff = FinalizableProcessor::get_forwarded_finalizable(e, *reff));
e.flush();
}
pub fn get_ready_object(&mut self) -> Option<ObjectReference> {
self.ready_for_finalize.pop()
}
}
#[derive(Default)]
pub struct Finalization<E: ProcessEdgesWork>(PhantomData<E>);
impl<E: ProcessEdgesWork> GCWork<E::VM> for Finalization<E> {
fn do_work(&mut self, worker: &mut GCWorker<E::VM>, mmtk: &'static MMTK<E::VM>) {
let mut finalizable_processor = mmtk.finalizable_processor.lock().unwrap();
debug!(
"Finalization, {} objects in candidates, {} objects ready to finalize",
finalizable_processor.candidates.len(),
finalizable_processor.ready_for_finalize.len()
);
let mut w = E::new(vec![], false, mmtk);
w.set_worker(worker);
finalizable_processor.scan(worker.tls, &mut w, mmtk.plan.in_nursery());
debug!(
"Finished finalization, {} objects in candidates, {} objects ready to finalize",
finalizable_processor.candidates.len(),
finalizable_processor.ready_for_finalize.len()
);
}
}
impl<E: ProcessEdgesWork> Finalization<E> {
pub fn new() -> Self {
Self(PhantomData)
}
}
#[derive(Default)]
pub struct ForwardFinalization<E: ProcessEdgesWork>(PhantomData<E>);
impl<E: ProcessEdgesWork> GCWork<E::VM> for ForwardFinalization<E> {
fn do_work(&mut self, _worker: &mut GCWorker<E::VM>, mmtk: &'static MMTK<E::VM>) {
trace!("Forward finalization");
let mut finalizable_processor = mmtk.finalizable_processor.lock().unwrap();
let mut w = E::new(vec![], false, mmtk);
finalizable_processor.forward(&mut w, mmtk.plan.in_nursery());
trace!("Finished forwarding finlizable");
}
}
impl<E: ProcessEdgesWork> ForwardFinalization<E> {
pub fn new() -> Self {
Self(PhantomData)
}
}
|
use rustybox::Function;
use std::env::Args;
pub fn binding() -> (&'static str, Function) {
("yes", Box::new(yes))
}
fn yes(_: Args) -> i32 {
loop {
println!("y")
}
0
}
|
extern crate simplicity;
use std::{cmp, fmt, ptr};
const IN_SIZE: usize = 8;
/* A length-prefixed encoding of the following Simplicity program:
* ((false &&& scribe (toWord256 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798)) &&& zero word256) &&&
* witness (toWord512 0x787A848E71043D280C50470E8E1532B2DD5D20EE912A45DBDD2BD1DFBF187EF67031A98831859DC34DFFEEDDA86831842CCD0079E1F92AF177F7F22CC1DCED05) >>>
* schnorrAssert
*/
const SCHNORR_1: [u8; 14583] = [
0xec, 0xc5, 0x34, 0x90, 0x58, 0x28, 0x14, 0x82, 0x81, 0x61, 0x88, 0x98, 0x0a, 0x85, 0x71, 0x16,
0x58, 0x0a, 0x05, 0x80, 0x5a, 0xb3, 0x10, 0x2d, 0x58, 0x8a, 0x05, 0x88, 0x5b, 0xb7, 0x09, 0xb0,
0x5c, 0x03, 0x80, 0x8b, 0x82, 0x70, 0x41, 0x70, 0x20, 0xa8, 0x58, 0x85, 0xc0, 0x38, 0x00, 0xb8,
0x27, 0x04, 0x13, 0x11, 0x50, 0xb1, 0x0b, 0x68, 0x5c, 0x33, 0x86, 0x08, 0x16, 0xcd, 0x82, 0xd0,
0x15, 0x0b, 0x7f, 0x0e, 0x17, 0x08, 0x0b, 0x87, 0xe6, 0x28, 0x16, 0x21, 0x70, 0x3e, 0x1e, 0x2e,
0x24, 0xe0, 0xa2, 0x71, 0x30, 0xa8, 0x5b, 0x38, 0x90, 0x5b, 0x78, 0xa4, 0x50, 0x2c, 0x02, 0xd2,
0x17, 0x04, 0x0b, 0x81, 0x6f, 0x17, 0x16, 0xf1, 0x58, 0xa0, 0x5c, 0x49, 0xc4, 0x02, 0xe2, 0x3e,
0x2e, 0x14, 0x0b, 0x00, 0xb8, 0x37, 0x13, 0x09, 0xc0, 0x85, 0xc2, 0x38, 0x10, 0xb8, 0xa7, 0x8d,
0x85, 0x02, 0xc0, 0x2c, 0xc2, 0xe2, 0x2e, 0x3a, 0x17, 0x18, 0x70, 0xe1, 0x40, 0xb8, 0xbf, 0x90,
0x22, 0xe1, 0x61, 0x71, 0x3f, 0x1e, 0x8a, 0x05, 0x88, 0x58, 0xf1, 0xe0, 0xb8, 0xe3, 0x88, 0x05,
0x02, 0xd1, 0xc8, 0x71, 0x72, 0x1b, 0x88, 0xc5, 0x02, 0xc0, 0x2d, 0x01, 0x70, 0x10, 0xb8, 0x80,
0x2e, 0x49, 0x05, 0xc6, 0x7c, 0x66, 0x20, 0x40, 0x81, 0x02, 0x05, 0x99, 0xc5, 0x08, 0x31, 0x25,
0x08, 0x10, 0x20, 0x40, 0x81, 0x02, 0x09, 0xa4, 0x5a, 0x42, 0xd2, 0x16, 0x90, 0xb4, 0x85, 0xa4,
0x2c, 0xb2, 0x16, 0xe0, 0xb7, 0x05, 0x74, 0x09, 0xc0, 0x05, 0x42, 0xe0, 0x01, 0x68, 0x0b, 0x80,
0x05, 0xc0, 0x02, 0xe1, 0x44, 0x18, 0x61, 0xe0, 0xa0, 0xf8, 0x98, 0x78, 0x28, 0x41, 0x86, 0x1e,
0x0a, 0x0f, 0x89, 0x87, 0x82, 0x84, 0x18, 0x61, 0xe0, 0xa0, 0xf8, 0x98, 0x78, 0x28, 0x41, 0x86,
0x1e, 0x0a, 0x0f, 0x89, 0x87, 0x82, 0x84, 0x18, 0x61, 0xe0, 0xa0, 0xf8, 0x98, 0x78, 0x28, 0x41,
0x86, 0x1e, 0x0a, 0x0f, 0x89, 0x87, 0x82, 0x84, 0x18, 0x61, 0xe0, 0xa0, 0xf8, 0x98, 0x78, 0x28,
0x41, 0x86, 0x1e, 0x0a, 0x0f, 0x89, 0x87, 0x82, 0x81, 0x69, 0xd2, 0x72, 0x48, 0x16, 0xd8, 0x7e,
0x71, 0x0f, 0xce, 0x30, 0x60, 0x18, 0x05, 0x90, 0xe0, 0xea, 0x03, 0x68, 0x5c, 0x08, 0x2e, 0x1f,
0xc1, 0x0d, 0x81, 0xf8, 0x48, 0xa0, 0xdc, 0x28, 0xdc, 0x1c, 0x4c, 0x00, 0xd4, 0x2c, 0x07, 0xe1,
0xe9, 0x28, 0xe0, 0x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, 0x07, 0x02, 0xe8, 0x38, 0x0a, 0x85, 0x98, 0x5a,
0xfa, 0x10, 0xc5, 0xa3, 0xa0, 0xe0, 0x5d, 0x07, 0xdd, 0x07, 0x22, 0x81, 0x60, 0x17, 0x41, 0xe7,
0x41, 0xe0, 0xb8, 0x08, 0x5d, 0x07, 0xdd, 0x09, 0x62, 0x70, 0x41, 0x50, 0xb2, 0x0b, 0x60, 0x5c,
0x23, 0xa1, 0x3c, 0x5c, 0x0f, 0xa1, 0x04, 0x50, 0x2e, 0x0d, 0xc1, 0x84, 0xe8, 0x4b, 0x16, 0xfe,
0x84, 0x71, 0x40, 0xb1, 0x0b, 0x85, 0x6f, 0x16, 0xee, 0x12, 0x28, 0x17, 0x42, 0x77, 0x0e, 0x17,
0x07, 0x08, 0x16, 0x01, 0x68, 0x0b, 0x80, 0x85, 0xc5, 0x41, 0x71, 0x68, 0x0e, 0x33, 0x38, 0x3c,
0x62, 0x07, 0x19, 0x92, 0x40, 0x81, 0x06, 0xe8, 0x16, 0x15, 0x0a, 0x84, 0xe8, 0x2d, 0x30, 0x4e,
0x83, 0x83, 0x8e, 0x39, 0x24, 0x08, 0x10, 0x7e, 0x82, 0x73, 0x05, 0x80, 0x58, 0x0f, 0xd0, 0x4e,
0x61, 0xba, 0x0b, 0x8e, 0x15, 0x0b, 0xa0, 0xb7, 0xa0, 0xc0, 0xc3, 0x85, 0x80, 0x5a, 0x86, 0x1f,
0xa0, 0xdc, 0x5c, 0x34, 0x7d, 0x02, 0x83, 0x8c, 0x3f, 0x01, 0x30, 0xdc, 0x04, 0xe1, 0x51, 0xb8,
0x01, 0xc2, 0xa1, 0x69, 0x0b, 0x80, 0x0e, 0x38, 0xdd, 0x08, 0xa2, 0xe3, 0x10, 0xb8, 0xc4, 0x2e,
0x85, 0x1e, 0x85, 0x41, 0x41, 0xc7, 0x18, 0x7e, 0x85, 0x53, 0x8c, 0x37, 0x42, 0xe9, 0x87, 0x0b,
0x01, 0xb6, 0x18, 0x70, 0xb0, 0x0b, 0x60, 0xe4, 0x90, 0x20, 0x41, 0xf8, 0xac, 0xc1, 0x60, 0x16,
0x03, 0xf1, 0x69, 0x82, 0x71, 0x38, 0xb0, 0x0b, 0x8e, 0x38, 0xc8, 0xc3, 0xf4, 0x34, 0x09, 0xc8,
0x53, 0x04, 0xe3, 0xf1, 0x62, 0x38, 0x5a, 0x46, 0x1c, 0x92, 0x04, 0x08, 0x3f, 0x1e, 0x1c, 0x60,
0xb1, 0x0b, 0x11, 0xba, 0x24, 0x0c, 0x38, 0x58, 0x05, 0xd1, 0x21, 0xd1, 0x26, 0x61, 0x87, 0x0b,
0x11, 0xba, 0x21, 0x85, 0xca, 0xf0, 0xb9, 0x5e, 0x13, 0x92, 0x06, 0x0b, 0x93, 0x1c, 0x91, 0x14,
0x1c, 0x71, 0xb8, 0x90, 0x5c, 0xab, 0x0b, 0x95, 0x63, 0x74, 0x4b, 0x9f, 0xa2, 0x74, 0x50, 0x2c,
0x06, 0x1f, 0x91, 0x86, 0x1b, 0x91, 0x27, 0xe4, 0x38, 0xa0, 0x58, 0x05, 0x98, 0xe1, 0x73, 0x0f,
0xcb, 0x21, 0x73, 0x0e, 0x13, 0x8e, 0x0e, 0x38, 0xc3, 0xf2, 0x00, 0xc3, 0x71, 0x79, 0xb9, 0x54,
0x70, 0xa8, 0x58, 0x8d, 0xc8, 0x23, 0x85, 0x42, 0xd6, 0x3f, 0x32, 0xc6, 0x0b, 0x92, 0x61, 0x72,
0x4c, 0x6e, 0x8c, 0x21, 0x40, 0x9d, 0x1a, 0x29, 0x20, 0x40, 0x81, 0x02, 0xbd, 0x17, 0xa2, 0x73,
0x1a, 0x2a, 0x30, 0xc3, 0x73, 0x10, 0x27, 0x31, 0xe2, 0xa3, 0x05, 0xbc, 0x60, 0xb8, 0x40, 0x5c,
0x54, 0x17, 0x1d, 0x8c, 0x17, 0x21, 0x82, 0xe4, 0xc8, 0x5c, 0xb1, 0x0b, 0x98, 0x70, 0xb9, 0xad,
0x18, 0x27, 0x3d, 0xa2, 0xe6, 0xf4, 0x92, 0x0e, 0x41, 0x47, 0x07, 0x00, 0x34, 0x0e, 0x3f, 0x48,
0xc5, 0x25, 0x08, 0x10, 0x20, 0x40, 0x81, 0x02, 0x09, 0xa4, 0x5a, 0x42, 0xd2, 0x16, 0x90, 0xb4,
0x85, 0xa4, 0x2c, 0xb2, 0x16, 0xe0, 0xb7, 0x05, 0x74, 0x09, 0xc0, 0x05, 0x42, 0xe0, 0x01, 0x68,
0x0b, 0x80, 0x05, 0xc0, 0x02, 0xe1, 0x40, 0x3a, 0x06, 0x0f, 0xc5, 0x22, 0x74, 0x0d, 0x8a, 0x92,
0x41, 0xc9, 0x20, 0x40, 0x81, 0x02, 0x0b, 0x90, 0xb2, 0x0a, 0x41, 0x40, 0xb3, 0x0b, 0x30, 0xb3,
0x0b, 0x46, 0x81, 0x02, 0x81, 0x50, 0xb0, 0x0b, 0x10, 0xb2, 0x0b, 0x30, 0xb4, 0x05, 0xa8, 0x83,
0x74, 0x8f, 0x45, 0xd2, 0x3e, 0xe9, 0x1f, 0x0b, 0xa4, 0x67, 0xd2, 0x30, 0x17, 0x48, 0xd4, 0x2e,
0x91, 0xb7, 0x48, 0xc4, 0x5d, 0x22, 0xde, 0x91, 0x50, 0xba, 0x45, 0xe1, 0x74, 0x8c, 0x3a, 0x45,
0x62, 0xe9, 0x13, 0xf4, 0x89, 0x05, 0xd2, 0x29, 0x0b, 0xa4, 0x55, 0xd2, 0x25, 0x17, 0x48, 0x87,
0xa4, 0x3c, 0x2e, 0x91, 0x18, 0x5d, 0x22, 0x4e, 0x90, 0xf8, 0xba, 0x43, 0x7d, 0x21, 0x81, 0x74,
0x87, 0x42, 0xe9, 0x0f, 0x74, 0x86, 0x49, 0xd2, 0x00, 0x3f, 0x48, 0x58, 0xfd, 0x22, 0x30, 0xc0,
0xb0, 0x03, 0x20, 0x3a, 0x43, 0xf0, 0x50, 0x2d, 0x41, 0x74, 0x7f, 0x74, 0x7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0xd0, 0x3a, 0x3f, 0x80, 0xe8, 0xff, 0x03, 0xa4, 0x00,
0x07, 0x48, 0x04, 0x0e, 0x90, 0x10, 0x1d, 0x20, 0x30, 0x3a, 0x40, 0x80, 0x74, 0x81, 0x40, 0xe9,
0x03, 0x01, 0xd2, 0x07, 0x03, 0xa4, 0x10, 0x07, 0x48, 0x24, 0x0e, 0x90, 0x50, 0x1d, 0x20, 0xb0,
0x3a, 0x41, 0x80, 0x74, 0x83, 0x40, 0xe9, 0x07, 0x01, 0xd2, 0x0f, 0x03, 0xa4, 0x20, 0x07, 0x48,
0x44, 0x0e, 0x90, 0x90, 0x1d, 0x21, 0x30, 0x3a, 0x42, 0x81, 0x75, 0x50, 0x60, 0x73, 0x09, 0xc5,
0xe0, 0x80, 0x73, 0x0c, 0x07, 0x18, 0x85, 0xd5, 0x44, 0x00, 0xe6, 0x24, 0x0e, 0x56, 0x03, 0x98,
0xb0, 0x39, 0x1a, 0x38, 0x5c, 0xb6, 0x03, 0x98, 0xfe, 0x47, 0x82, 0x05, 0xcb, 0xa0, 0x39, 0x92,
0xe5, 0x50, 0x20, 0x1c, 0xa1, 0x0b, 0x97, 0xa0, 0x72, 0xe8, 0x0e, 0x60, 0x42, 0xea, 0xa6, 0x06,
0xea, 0xa6, 0x41, 0xcb, 0xfe, 0x5e, 0x9c, 0x2a, 0x17, 0x55, 0x65, 0xd5, 0x56, 0x0b, 0xaa, 0xb2,
0x0b, 0xaa, 0xae, 0xea, 0xab, 0x84, 0x0a, 0x85, 0xd5, 0x58, 0xf5, 0x56, 0xe2, 0xc0, 0x2e, 0xaa,
0xd7, 0xaa, 0xba, 0x17, 0x55, 0x74, 0x13, 0x31, 0x60, 0x16, 0x61, 0x63, 0xd5, 0x5c, 0x09, 0xac,
0x5a, 0xc2, 0xd6, 0x16, 0xdd, 0xa2, 0xda, 0x17, 0x02, 0xe0, 0x02, 0xea, 0xb0, 0xc2, 0x60, 0x2c,
0x02, 0xc4, 0x2c, 0x82, 0x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x40, 0x1c, 0x72, 0x6e, 0x64, 0x4f, 0xcc, 0x90, 0xa0, 0x58, 0x12, 0x41, 0xc6, 0xea,
0x9c, 0x0f, 0xd5, 0x38, 0x8a, 0x00, 0xe4, 0x21, 0xb9, 0x95, 0x3f, 0x32, 0xc2, 0x81, 0x60, 0x49,
0x07, 0x1b, 0xab, 0x1b, 0x3f, 0x56, 0x38, 0x28, 0x03, 0x91, 0xe6, 0xea, 0x5c, 0xcf, 0xd4, 0xba,
0x0a, 0x05, 0x81, 0x24, 0x1c, 0x0e, 0xb4, 0x4d, 0xc9, 0x71, 0x3a, 0xd1, 0x19, 0xfa, 0xc5, 0x39,
0xf9, 0x34, 0x18, 0x06, 0x03, 0x83, 0xa0, 0x0d, 0x83, 0x83, 0xc1, 0x80, 0xe1, 0x43, 0x83, 0xc4,
0x80, 0x71, 0x40, 0xe0, 0xf1, 0x90, 0x1c, 0x6c, 0x38, 0x3c, 0x80, 0x03, 0x90, 0x83, 0x83, 0xc8,
0xe0, 0x39, 0x24, 0x38, 0x3c, 0x9c, 0x03, 0x94, 0x03, 0x83, 0xca, 0xa0, 0x39, 0x5c, 0x07, 0x34,
0x01, 0x3a, 0xc0, 0x68, 0xba, 0x15, 0x3a, 0xc0, 0x70, 0x18, 0x1c, 0x7e, 0xb0, 0x44, 0x18, 0x06,
0x40, 0x73, 0x54, 0x07, 0x48, 0x00, 0x0e, 0x81, 0xe0, 0x9d, 0x20, 0x02, 0x75, 0x82, 0xf3, 0x8b,
0xd6, 0x06, 0x8e, 0x0d, 0x03, 0x20, 0x3a, 0x20, 0x80, 0xe8, 0x87, 0x03, 0xa4, 0x16, 0x07, 0x48,
0x7c, 0x62, 0x05, 0x09, 0x20, 0xdd, 0x60, 0x9c, 0xe3, 0x75, 0xa3, 0x23, 0x8c, 0x38, 0xe3, 0x8e,
0x38, 0xe3, 0x8e, 0x38, 0x4e, 0xb0, 0x6a, 0x2e, 0xb0, 0x8d, 0xd6, 0x12, 0xc4, 0xeb, 0x09, 0x62,
0xeb, 0x09, 0x61, 0x75, 0x84, 0xb0, 0xba, 0xc2, 0x4f, 0x58, 0x4a, 0x17, 0x58, 0x50, 0xeb, 0x09,
0x62, 0x81, 0x74, 0x4f, 0x85, 0xd6, 0x14, 0x02, 0x75, 0x83, 0xe0, 0x74, 0xfb, 0x3a, 0x9e, 0x80,
0x40, 0xba, 0xb4, 0x60, 0x1d, 0x3e, 0xf1, 0x6b, 0x01, 0xd3, 0xf1, 0x17, 0x44, 0xc0, 0x1d, 0x67,
0x1f, 0xac, 0xe0, 0x82, 0x04, 0xeb, 0x09, 0x27, 0xeb, 0x0c, 0x09, 0x20, 0x40, 0x82, 0xe0, 0x20,
0x58, 0x05, 0x80, 0x56, 0x88, 0x15, 0x0a, 0x41, 0x40, 0x9d, 0x5a, 0xc8, 0x1c, 0xe1, 0x09, 0xd4,
0x26, 0x9f, 0x7a, 0x48, 0x10, 0x20, 0xb8, 0x08, 0x16, 0x01, 0x60, 0x15, 0xa2, 0x05, 0x42, 0x90,
0x50, 0x27, 0x56, 0x5c, 0x07, 0x3a, 0x62, 0x75, 0x1a, 0x47, 0xde, 0x92, 0x04, 0x08, 0x2e, 0x02,
0x05, 0x80, 0x58, 0x05, 0x68, 0x81, 0x50, 0xa4, 0x14, 0x09, 0xd5, 0x99, 0x81, 0xcf, 0x20, 0x9d,
0x47, 0xe1, 0xf7, 0xa4, 0x81, 0x02, 0x0b, 0x80, 0x81, 0x60, 0x16, 0x01, 0x5a, 0x20, 0x54, 0x29,
0x05, 0x02, 0x75, 0x66, 0xc0, 0x73, 0xea, 0x27, 0x52, 0x4e, 0x7d, 0xe9, 0x20, 0x40, 0x82, 0xe0,
0x20, 0x58, 0x05, 0x80, 0x56, 0x88, 0x15, 0x0a, 0x41, 0x40, 0x9d, 0x59, 0xa0, 0x1d, 0x00, 0xc2,
0x75, 0x2b, 0x27, 0xde, 0x2e, 0xa8, 0xa3, 0xaa, 0x23, 0x17, 0x54, 0x4b, 0xd5, 0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0x2a, 0x3f, 0x58, 0x18, 0x30, 0xc1, 0x32, 0x03, 0xa2,
0x34, 0x4e, 0x77, 0x8f, 0xd2, 0x11, 0x0b, 0x89, 0xc1, 0x40, 0xd4, 0x17, 0x3c, 0x44, 0x90, 0x20,
0x40, 0x81, 0x05, 0xc8, 0x59, 0x05, 0x90, 0x59, 0x05, 0x90, 0x59, 0x05, 0x9e, 0x62, 0x05, 0x02,
0xa1, 0x60, 0x16, 0x21, 0x64, 0x16, 0x61, 0x68, 0x0b, 0x50, 0x5c, 0x1c, 0x50, 0x79, 0xfd, 0x03,
0xa0, 0x00, 0x70, 0x7a, 0xc9, 0xf0, 0x1d, 0x65, 0x08, 0x61, 0x89, 0x28, 0x40, 0x81, 0x02, 0x04,
0x08, 0x26, 0x81, 0x68, 0x0b, 0x40, 0x5a, 0x02, 0xd0, 0x16, 0x80, 0xb4, 0x05, 0xa0, 0x2c, 0xf7,
0x0b, 0x46, 0x81, 0x40, 0xa6, 0x91, 0x40, 0xb6, 0xf0, 0x41, 0x70, 0x40, 0xb7, 0xef, 0x17, 0x06,
0x0a, 0x85, 0x8f, 0x01, 0x17, 0x01, 0x0a, 0x85, 0xa4, 0x2d, 0xbc, 0x2c, 0x5a, 0xb4, 0x0b, 0x83,
0xe9, 0x14, 0x0b, 0x00, 0xb6, 0x6c, 0x17, 0x03, 0x0b, 0x77, 0x11, 0x89, 0xc1, 0x85, 0x42, 0xc8,
0x2d, 0x81, 0x70, 0xae, 0x27, 0x17, 0x04, 0xe2, 0x21, 0x70, 0x60, 0xa8, 0x5c, 0x27, 0x84, 0x89,
0xc4, 0xa2, 0xe0, 0x1c, 0x20, 0x50, 0x2c, 0x42, 0xe1, 0xbc, 0x00, 0x5b, 0xf8, 0x50, 0xa0, 0x5c,
0x3f, 0x88, 0x45, 0xc2, 0x02, 0x05, 0x80, 0x5a, 0x02, 0xe0, 0x41, 0x71, 0x68, 0xfd, 0x6f, 0x40,
0xbd, 0x68, 0x24, 0x4e, 0xb4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, 0xa1, 0xc4, 0x42, 0x81, 0x74, 0x26, 0xf4, 0x2a, 0x89, 0xc0, 0x45, 0xc2, 0xfa,
0x14, 0x45, 0x02, 0xc4, 0x27, 0x19, 0x0b, 0x87, 0xf1, 0x88, 0xba, 0x16, 0xf8, 0xbc, 0x50, 0x2e,
0x33, 0xe2, 0x71, 0x71, 0x2f, 0x1a, 0x0a, 0x05, 0x80, 0x4e, 0x3a, 0x17, 0x14, 0xee, 0x17, 0x1b,
0x74, 0x32, 0x8a, 0x05, 0xc5, 0x5c, 0x54, 0x2e, 0x85, 0xee, 0x04, 0x28, 0x16, 0x01, 0x39, 0x04,
0x2e, 0x86, 0xae, 0x26, 0x17, 0x07, 0xe8, 0x69, 0x14, 0x0b, 0x90, 0x1d, 0x0d, 0xa2, 0xe2, 0x80,
0xa8, 0x4e, 0x44, 0x8b, 0x8b, 0x7a, 0x1b, 0x05, 0xd0, 0xe1, 0xd0, 0xe4, 0x28, 0x17, 0x10, 0x72,
0x28, 0x5c, 0x8c, 0xe3, 0xf1, 0x40, 0xb0, 0x09, 0xc9, 0x11, 0x72, 0x3f, 0x91, 0xe2, 0xe4, 0x6f,
0x23, 0x85, 0x02, 0xe8, 0x7e, 0xe4, 0x18, 0xb9, 0x23, 0xd0, 0xf6, 0x28, 0x16, 0x01, 0x39, 0x32,
0x2e, 0x88, 0x3e, 0x3d, 0x13, 0x68, 0xb9, 0x33, 0xc8, 0xa1, 0x74, 0x43, 0x74, 0x3f, 0x8a, 0x05,
0x80, 0x4e, 0x50, 0x0b, 0x8d, 0x39, 0x36, 0x2e, 0x48, 0x72, 0x4c, 0x50, 0x2e, 0x51, 0x74, 0x45,
0x8b, 0x93, 0x9c, 0x96, 0x14, 0x0b, 0x00, 0x9c, 0xa8, 0x17, 0x44, 0x47, 0x29, 0xc5, 0xc9, 0x8e,
0x52, 0x8a, 0x05, 0xca, 0x6e, 0x49, 0x0b, 0x93, 0x3d, 0x12, 0xc2, 0x81, 0x60, 0x13, 0x96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e5, 0x0b, 0xad, 0xf2, 0x85,
0xd8, 0x15, 0xa0, 0x3a, 0xbb, 0x03, 0x0d, 0x0d, 0x4d, 0x81, 0xb1, 0x36, 0x46, 0xcc, 0xda, 0x0d,
0xa4, 0xfa, 0x85, 0x07, 0x0b, 0x11, 0xc2, 0xd0, 0x38, 0x5a, 0xc7, 0x0b, 0x70, 0xe1, 0x70, 0x11,
0xc2, 0xe0, 0x83, 0x85, 0xc1, 0xc7, 0x0b, 0x85, 0x01, 0xd5, 0xea, 0x04, 0xeb, 0xd1, 0xe0, 0x75,
0x73, 0x87, 0x1c, 0x7e, 0xb0, 0xf6, 0x6e, 0xae, 0x7c, 0xfa, 0x05, 0x00, 0x75, 0x88, 0x23, 0x05,
0x90, 0x0e, 0xb1, 0x34, 0x2d, 0x20, 0x3a, 0xc4, 0x38, 0xb8, 0xc4, 0x0e, 0x4d, 0x81, 0xca, 0x41,
0xba, 0xc4, 0x49, 0xfa, 0xf5, 0x08, 0xa0, 0x1d, 0x62, 0x8f, 0x95, 0x80, 0x81, 0x64, 0x39, 0x24,
0x08, 0x10, 0x20, 0x41, 0x72, 0x16, 0x41, 0x64, 0x16, 0x41, 0x64, 0x16, 0x41, 0x67, 0x98, 0x81,
0x40, 0xa8, 0x58, 0x05, 0x88, 0x59, 0x05, 0x98, 0x5a, 0x02, 0xd4, 0x10, 0x2d, 0x74, 0x50, 0x70,
0x78, 0x58, 0x1c, 0xe8, 0x85, 0xd0, 0x10, 0x3f, 0x11, 0xa0, 0xc3, 0x04, 0xc0, 0x1c, 0x51, 0xd6,
0x96, 0xc5, 0xc5, 0x21, 0x75, 0x8b, 0x4e, 0xb1, 0x96, 0x08, 0x16, 0x63, 0x75, 0x8b, 0x61, 0x38,
0xf0, 0x0e, 0xb1, 0xa0, 0x6e, 0xb1, 0x74, 0x7e, 0xb1, 0x76, 0x28, 0x03, 0xac, 0x6a, 0x0b, 0x10,
0x34, 0x81, 0xbc, 0x6e, 0x37, 0x14, 0x1f, 0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xb4, 0x8b, 0xc0, 0x05,
0xc0, 0x02, 0xe0, 0x01, 0x70, 0x00, 0xb8, 0x00, 0x5c, 0x00, 0x26, 0x81, 0x02, 0x69, 0x16, 0xa1,
0xc6, 0xe8, 0x7b, 0x3f, 0x3e, 0x22, 0x83, 0x83, 0x88, 0x1c, 0x42, 0x38, 0xe0, 0xf1, 0x40, 0x1c,
0xd8, 0x01, 0xcd, 0xa8, 0x1c, 0xe9, 0x0e, 0x49, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0xa0, 0x54,
0x2c, 0x02, 0xc4, 0x2c, 0x82, 0xcc, 0x2d, 0x01, 0x69, 0x24, 0x81, 0x02, 0x04, 0x08, 0x2e, 0x42,
0xc8, 0x2c, 0x82, 0xc8, 0x2c, 0x82, 0xc8, 0x2c, 0xf3, 0x10, 0x28, 0x15, 0x0b, 0x00, 0xb1, 0x0b,
0x20, 0xb3, 0x0b, 0x40, 0x5a, 0x82, 0xe8, 0x20, 0x1c, 0x2e, 0x12, 0x38, 0x3c, 0x56, 0x07, 0x40,
0x50, 0x4e, 0x7a, 0x04, 0xe8, 0x05, 0x3f, 0x48, 0xc8, 0xc3, 0x0f, 0xd0, 0x56, 0x28, 0x03, 0x42,
0x0c, 0x15, 0x09, 0x91, 0xb5, 0x18, 0x7e, 0x83, 0x41, 0x40, 0x1c, 0x05, 0x06, 0x0a, 0x84, 0xc8,
0xdc, 0x0c, 0xc3, 0xf4, 0x1e, 0x8a, 0x00, 0xe1, 0x48, 0x30, 0x54, 0x26, 0x46, 0xe1, 0x86, 0x1f,
0xa1, 0x18, 0x50, 0x07, 0x11, 0xa0, 0xc1, 0x50, 0x99, 0x1b, 0x89, 0x4c, 0x3f, 0x42, 0x78, 0xa0,
0x0e, 0x2c, 0x41, 0x82, 0xa1, 0x32, 0x37, 0x17, 0x18, 0x7e, 0x85, 0x81, 0x40, 0x1c, 0x6a, 0x83,
0x05, 0x40, 0xd2, 0x07, 0x03, 0x03, 0x86, 0x81, 0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0xda, 0x8a, 0x00, 0xe0, 0x62, 0xc8, 0x7c, 0x8d, 0xa8, 0xfa, 0x85, 0x02, 0xc0, 0x0c, 0x80, 0xe0,
0x00, 0x72, 0xb8, 0x6e, 0xc7, 0xa2, 0x13, 0xb1, 0x47, 0xcc, 0x3c, 0x14, 0x18, 0x78, 0x28, 0x38,
0x5a, 0x88, 0x38, 0xc3, 0x73, 0x88, 0x61, 0xfb, 0x1f, 0x64, 0x50, 0x07, 0x03, 0x16, 0x43, 0xe4,
0x6d, 0x47, 0xd4, 0x28, 0x16, 0x00, 0x64, 0x07, 0x00, 0x03, 0x99, 0x21, 0xbb, 0x1f, 0x18, 0x4e,
0xc5, 0x15, 0x30, 0xf0, 0x50, 0x61, 0xe0, 0xa0, 0xe1, 0x6a, 0x20, 0xe3, 0x0d, 0xce, 0xf9, 0x87,
0xec, 0x7f, 0xd1, 0x40, 0x1c, 0x0c, 0x59, 0x0f, 0x91, 0xb5, 0x1f, 0x50, 0xa0, 0x58, 0x01, 0x90,
0x1c, 0x00, 0x0e, 0x6d, 0x86, 0xec, 0x7e, 0xa1, 0x3b, 0x14, 0x28, 0xc3, 0xc1, 0x41, 0x87, 0x82,
0x83, 0x85, 0xa8, 0x83, 0x8c, 0x37, 0x3f, 0x46, 0x1f, 0xb2, 0x08, 0x45, 0x00, 0x70, 0x31, 0x64,
0x3e, 0x46, 0xd4, 0x7d, 0x42, 0x81, 0x60, 0x06, 0x40, 0x70, 0x00, 0x39, 0xda, 0x1b, 0xb2, 0x03,
0x84, 0xec, 0x20, 0x83, 0x0f, 0x05, 0x06, 0x1e, 0x0a, 0x0e, 0x16, 0xa2, 0x0e, 0x30, 0xdd, 0x02,
0xa6, 0x1f, 0xb2, 0x16, 0x05, 0x00, 0x70, 0x31, 0x64, 0x3e, 0x46, 0xd4, 0x7d, 0x42, 0x81, 0x60,
0x06, 0x40, 0x70, 0x00, 0x39, 0xfe, 0x1b, 0xb2, 0x0c, 0x8f, 0xd9, 0x06, 0x62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70, 0xbb, 0x0f, 0x63,
0xb0, 0xf6, 0x04, 0x0a, 0x05, 0x42, 0xc0, 0x2c, 0x42, 0xc8, 0x2c, 0xc2, 0xd0, 0x16, 0xa0, 0xb6,
0x80, 0xea, 0xc3, 0xc5, 0xcd, 0x50, 0xfd, 0x10, 0x66, 0xea, 0x43, 0x12, 0x40, 0x81, 0x02, 0x04,
0x17, 0x21, 0x64, 0x16, 0x41, 0x64, 0x16, 0x41, 0x64, 0x16, 0x79, 0x88, 0x14, 0x0a, 0x85, 0x80,
0x58, 0x85, 0x90, 0x59, 0x85, 0xa0, 0x2d, 0x41, 0x02, 0xd7, 0x45, 0x07, 0xe8, 0x32, 0x14, 0x0b,
0x86, 0x0d, 0xd4, 0xa3, 0x98, 0x6e, 0x86, 0xd4, 0x1c, 0x2a, 0x37, 0x52, 0xd2, 0x61, 0xba, 0x19,
0xcf, 0x90, 0xa0, 0xdd, 0x4c, 0x51, 0x86, 0xe8, 0x60, 0x3e, 0xb1, 0x41, 0xba, 0x9a, 0x83, 0x0d,
0xd0, 0xb2, 0x7e, 0x00, 0x28, 0x37, 0x59, 0x4f, 0x38, 0xf0, 0x4e, 0x80, 0xb0, 0x3a, 0x02, 0x83,
0x80, 0x19, 0x8f, 0xd0, 0x90, 0x28, 0x16, 0xd0, 0x18, 0x83, 0x80, 0x8f, 0xd0, 0x9a, 0x28, 0x17,
0x07, 0x01, 0x88, 0x38, 0x58, 0xfd, 0x0a, 0x42, 0x81, 0x71, 0x08, 0x0c, 0x41, 0xc4, 0xa3, 0xf4,
0x2b, 0x8a, 0x05, 0xc5, 0x80, 0x31, 0x07, 0x18, 0x05, 0xc8, 0xe0, 0xba, 0xc8, 0xaf, 0x59, 0x20,
0x03, 0xb0, 0x8b, 0x85, 0xd5, 0xff, 0x0f, 0xd8, 0x43, 0x02, 0xec, 0x19, 0x8e, 0xb3, 0xe8, 0x07,
0x61, 0x09, 0x0a, 0x81, 0xd8, 0x46, 0x9d, 0x84, 0x2e, 0x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0xcf, 0x48, 0x01, 0xe1, 0xea, 0x12, 0x39, 0xc4, 0x10, 0xf4, 0xa0, 0x31,
0x41, 0x1c, 0x3a, 0x38, 0x54, 0xca, 0xcb, 0x75, 0x74, 0x83, 0xba, 0x44, 0xa9, 0x17, 0x6f, 0x74,
0xaf, 0x47, 0x7e, 0xfc, 0x61, 0xfb, 0xd9, 0xc0, 0xc6, 0xa6, 0x20, 0xc6, 0x16, 0x77, 0x0d, 0x37,
0xff, 0xbb, 0x76, 0xa1, 0xa0, 0xc6, 0x10, 0xb3, 0x34, 0x01, 0xe7, 0x87, 0xe4, 0xab, 0xc5, 0xdf,
0xdf, 0xc8, 0xb3, 0x07, 0x73, 0xb4, 0x14,
];
/* The commitment Merkle root of the above schnorr1 Simplicity expression. */
const SCHNORR_1_CMR: [u32; 8] = [
0xc64df1cb, 0xdd50bd2c, 0x979ad948, 0x742d253c, 0xd2c0ea83, 0xe635ea96, 0xb8ba8c8e, 0xb61a2181,
];
/* The witness Merkle root of the above schnorr1 Simplicity expression. */
const SCHNORR_1_WMR: [u32; 8] = [
0xdebfd1b6, 0x7e14c364, 0x9ab5fc33, 0x432af0b0, 0x4568ab5d, 0x2eb15c8c, 0xa53701ab, 0x86524eab,
];
struct BitIter<I: Iterator<Item = u8>> {
iter: I,
cached_byte: u8,
read_bits: usize,
}
impl<I: Iterator<Item = u8>> From<I> for BitIter<I> {
fn from(iter: I) -> Self {
BitIter {
iter: iter,
cached_byte: 0,
read_bits: 8,
}
}
}
impl<I: Iterator<Item = u8>> Iterator for BitIter<I> {
type Item = bool;
fn next(&mut self) -> Option<bool> {
if self.read_bits < 8 {
self.read_bits += 1;
Some(self.cached_byte & (1 << (8 - self.read_bits as u8)) != 0)
} else {
self.cached_byte = self.iter.next()?;
self.read_bits = 0;
self.next()
}
}
}
struct Frame {
data: *mut u8,
abs_pos: isize,
start: isize,
len: isize,
}
impl fmt::Debug for Frame {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
unsafe {
for i in 0..self.len {
if i == self.abs_pos - self.start {
f.write_str("^")?;
}
let p = self.data.offset((self.start + i) / 8);
if *p & (1 << ((self.start + i) % 8)) != 0 {
f.write_str("1")?;
} else {
f.write_str("0")?;
}
}
}
Ok(())
}
}
impl Frame {
fn read_at_rel(&self, n: isize) -> bool {
unsafe {
let p = self.data.offset((self.abs_pos + n) / 8);
*p & (1 << ((self.abs_pos + n) % 8)) != 0
}
}
fn read(&self) -> bool {
unsafe {
let p = self.data.offset(self.abs_pos / 8);
*p & (1 << (self.abs_pos % 8)) != 0
}
}
fn write(&mut self, b: bool) {
let mask = 1 << (self.abs_pos % 8);
unsafe {
let p = self.data.offset(self.abs_pos / 8);
if b {
*p |= mask;
} else {
*p &= !mask;
}
}
self.abs_pos += 1;
}
fn fwd(&mut self, n: usize) {
self.abs_pos += n as isize;
}
fn back(&mut self, n: usize) {
self.abs_pos -= n as isize;
}
fn copy_from(&mut self, other: &Frame, n: usize) {
if self.abs_pos % 8 == 0 && other.abs_pos % 8 == 0 {
unsafe {
ptr::copy_nonoverlapping(
other.data.offset(other.abs_pos / 8),
self.data.offset(self.abs_pos / 8),
(n + 7) / 8,
);
self.abs_pos += n as isize;
}
} else {
for i in 0..n as isize {
let bit = unsafe {
let p = other.data.offset((other.abs_pos + i) / 8);
*p & (1 << ((other.abs_pos + i) % 8)) != 0
};
self.write(bit);
}
}
}
}
struct BitMachine {
data: [u8; 29_082],
next_pos: isize,
read: Vec<Frame>,
write: Vec<Frame>,
}
impl BitMachine {
fn new_frame(&mut self, len: usize) {
assert!(self.next_pos as usize + len < self.data.len() * 8);
assert!(self.write.len() + self.read.len() < self.read.capacity());
self.write.push(Frame {
data: self.data.as_mut_ptr(),
abs_pos: self.next_pos,
start: self.next_pos,
len: len as isize,
});
self.next_pos += len as isize;
}
fn move_frame(&mut self) {
let mut pop = self.write.pop().unwrap();
pop.abs_pos = pop.start;
self.read.push(pop);
}
fn drop_frame(&mut self) {
let d = self.read.pop().unwrap();
self.next_pos -= d.len;
assert_eq!(self.next_pos, d.start);
}
fn write(&mut self, bit: bool) {
let idx = self.write.len() - 1;
self.write[idx].write(bit);
}
fn skip(&mut self, n: usize) {
let idx = self.write.len() - 1;
self.write[idx].fwd(n);
}
fn copy(&mut self, n: usize) {
let widx = self.write.len() - 1;
let ridx = self.read.len() - 1;
self.write[widx].copy_from(&self.read[ridx], n);
}
fn fwd(&mut self, n: usize) {
let idx = self.read.len() - 1;
self.read[idx].fwd(n);
}
fn back(&mut self, n: usize) {
let idx = self.read.len() - 1;
self.read[idx].back(n);
}
fn write_value(&mut self, val: &simplicity::Value) {
match *val {
simplicity::Value::Unit => {}
simplicity::Value::SumL(ref a) => {
self.write(false);
self.write_value(a);
}
simplicity::Value::SumR(ref a) => {
self.write(true);
self.write_value(a);
}
simplicity::Value::Prod(ref a, ref b) => {
self.write_value(a);
self.write_value(b);
}
}
}
fn new(frame_count: usize) -> BitMachine {
let mut ret = BitMachine {
data: [0; 29_082],
next_pos: 0,
read: Vec::with_capacity(frame_count),
write: Vec::with_capacity(frame_count),
};
ret.new_frame(0);
ret.move_frame();
ret
}
fn exec(&mut self, program: &simplicity::types::TypedNode, iters: &mut usize, data: &mut [CacheVals]) {
*iters += 1;
let in_size = program.source_ty.bit_width();
let out_size = program.target_ty.bit_width();
let mut input = 0;
if in_size <= IN_SIZE && out_size <= 64 {
for i in 0..in_size {
input += if self.read[self.read.len() - 1].read_at_rel(i as isize) {
1 << (in_size - i - 1)
} else {
0
};
}
if let Some(mut val) = data[program.index].cache[input] {
for _ in 0..out_size {
self.write(val % 2 == 1);
val /= 2;
}
return;
}
}
if *iters % 100_000_000 == 0 {
println!("({:5} M) exec {}", *iters / 1_000_000, program);
//println!(" {}", simplicity::types::FullPrint(&program));
}
match program.node {
simplicity::Node::Iden => {
self.copy(program.source_ty.bit_width());
}
simplicity::Node::Unit => {}
simplicity::Node::InjL(ref t) => {
self.write(false);
if let simplicity::types::FinalTypeInner::Sum(ref a, _) = program.target_ty.ty {
let aw = a.bit_width();
self.skip(program.target_ty.bit_width() - aw - 1);
self.exec(t, iters, data);
} else {
panic!("type error")
}
}
simplicity::Node::InjR(ref t) => {
self.write(true);
if let simplicity::types::FinalTypeInner::Sum(_, ref b) = program.target_ty.ty {
let bw = b.bit_width();
self.skip(program.target_ty.bit_width() - bw - 1);
self.exec(t, iters, data);
} else {
panic!("type error")
}
}
simplicity::Node::Pair(ref s, ref t) => {
self.exec(s, iters, data);
self.exec(t, iters, data);
}
simplicity::Node::Comp(ref s, ref t) => {
let size = s.target_ty.bit_width();
self.new_frame(size);
self.exec(s, iters, data);
self.move_frame();
self.exec(t, iters, data);
self.drop_frame();
}
simplicity::Node::Take(ref t) => {
self.exec(t, iters, data);
}
simplicity::Node::Drop(ref t) => {
if let simplicity::types::FinalTypeInner::Product(ref a, _) = program.source_ty.ty {
let aw = a.bit_width();
self.fwd(aw);
self.exec(t, iters, data);
self.back(aw);
} else {
panic!("type error")
}
}
simplicity::Node::Case(ref s, ref t) => {
let sw = self.read[self.read.len() - 1].read();
let aw;
let bw;
if let simplicity::types::FinalTypeInner::Product(ref a, _) = program.source_ty.ty {
if let simplicity::types::FinalTypeInner::Sum(ref a, ref b) = a.ty {
aw = a.bit_width();
bw = b.bit_width();
} else {
panic!("type error");
}
} else {
panic!("type error");
}
if sw {
self.fwd(1 + cmp::max(aw, bw) - bw);
self.exec(t, iters, data);
self.back(1 + cmp::max(aw, bw) - bw);
} else {
self.fwd(1 + cmp::max(aw, bw) - aw);
self.exec(s, iters, data);
self.back(1 + cmp::max(aw, bw) - aw);
}
}
simplicity::Node::Witness(ref value) => {
self.write_value(value.as_ref().unwrap());
}
simplicity::Node::Hidden(ref h) => {
panic!("Hit hidden node {} at iter {} (hash {:?})", program, iters, h);
}
ref x => panic!("Don't know how to handle {:?}", x),
}
if in_size <= IN_SIZE && out_size <= 64 {
let mut output = 0;
for i in 0..out_size {
output += if self.write[self.write.len() - 1].read_at_rel(-(1 + i as isize)) {
1 << (out_size - i - 1)
} else {
0
};
}
data[program.index].cache[input] = Some(output);
}
}
}
#[derive(Clone)]
struct CacheVals {
cache: Vec<Option<u64>>,
}
fn main() {
let mut bits: BitIter<_> = SCHNORR_1.iter().cloned().into();
let program =
simplicity::encode::decode_program_no_witness(&mut bits).expect("decoding program");
let wit_len = match bits.next() {
Some(false) => 0,
Some(true) => {
simplicity::encode::decode_natural(&mut bits).expect("decoding witness length")
}
None => panic!("No witness data"),
};
let typeck = simplicity::types::type_check(&program, Some(bits.by_ref().take(wit_len)));
println!("{}", typeck);
println!("extra cells: {}", typeck.extra_cells_bound);
println!("frame count: {}", typeck.frame_count_bound);
println!("Running program ... warning, this will take several hours even in release mode");
let mut mac = BitMachine::new(typeck.frame_count_bound);
let mut iters = 0;
let mut run_stats = vec![CacheVals { cache: vec![None; 1 << IN_SIZE] }; 7251];
mac.exec(&typeck, &mut iters, &mut run_stats[..]);
println!("{} iterations", iters);
}
|
pub enum Progress {
Waiting,
Started,
Packet(u8),
}
pub type ProgressFn = fn(Progress);
pub fn noop(_: Progress) {}
|
use crate::config::AndroidConfig;
use crate::ops::install;
use anyhow::format_err;
use cargo::core::{TargetKind, Workspace};
use cargo::util::process_builder::process;
use cargo::util::CargoResult;
use clap::ArgMatches;
pub fn run(workspace: &Workspace, config: &AndroidConfig, options: &ArgMatches) -> CargoResult<()> {
let build_result = install::install(workspace, config, options)?;
// Determine the target that should be executed
let requested_target = if options.is_present("example") && options.is_present("bin") {
return Err(format_err!(
"Specifying both example and bin targets is not supported"
));
} else if let Some(bin) = options.value_of("bin") {
(TargetKind::Bin, bin.to_owned())
} else if let Some(example) = options.value_of("example") {
(TargetKind::ExampleBin, example.to_owned())
} else {
match build_result.target_to_apk_map.len() {
1 => build_result
.target_to_apk_map
.keys()
.next()
.unwrap()
.to_owned(),
0 => return Err(format_err!("No APKs to execute.")),
_ => {
return Err(format_err!(
"Multiple APKs built. Specify which APK to execute using '--bin' or '--example'."
))
}
}
};
// Determine package name
let package_name = config.resolve(requested_target)?.package_name;
//
// Start the APK using adb
//
let adb = config.sdk_path.join("platform-tools/adb");
// Found it by doing this :
// adb shell "cmd package resolve-activity --brief com.author.myproject | tail -n 1"
let activity_path = format!(
"{}/android.app.NativeActivity",
package_name.replace("-", "_"),
);
drop(writeln!(workspace.config().shell().err(), "Running apk"));
process(&adb)
.arg("shell")
.arg("am")
.arg("start")
.arg("-a")
.arg("android.intent.action.MAIN")
.arg("-n")
.arg(&activity_path)
.exec()?;
Ok(())
}
|
extern crate a01;
extern crate rand;
use std::env;
use a01::*;
use std::process;
use std::net;
use std::net::UdpSocket;
use rand::Rng;
use std::thread;
use std::time::Duration;
static MIN_JOB_TIME_MS : u32 = 6000;
static MAX_JOB_TIME_MS : u32 = 6500;
static MIN_SLEEP_TIME_MS : u64 = 100;
static MAX_SLEEP_TIME_MS : u64 = 500;
fn main() -> std::io::Result<()> {
// Get the command line args
let args : Vec<String> = env::args()
.skip(1) // Skip the first argument, it's the app name
.collect();
let mobile_id = parse_id(args.get(0))
// This function either gets the parsed id or invokes this lambda/anonymous function
// which invokes an error that can be redirected to sterr
.unwrap_or_else(|e| {
eprintln!("MobileId Parsing Error: {}", e);
process::exit(1);
});
// We get the args and pass them to parse the endpoint
let endpoint = parse_endpoint(args.get(1), args.get(2))
.unwrap_or_else(|e| {
eprintln!("Endpoint Parsing Error: {}", e);
process::exit(1);
});
// Get the client port so we can bind to a UDP socket, we need to get this from the
// command line, unless we're prepared to just try random ports
let client_port = parse_client_port(args.get(3))
.unwrap_or_else(|e| {
eprintln!("Client Port Parsing Error: {}", e);
process::exit(1);
});
println!("Connecting Mobile with Id {} to Endpoint {}:{}",
mobile_id,
endpoint.ip(),
endpoint.port());
// Create an IP
let local = net::Ipv4Addr::new(127, 0, 0, 1);
// Create the Socket Address that we will bind to, not the server endpoint, that's later
let socket_addr = std::net::SocketAddrV4::new(local, client_port as u16);
// Here we bind to the UDP socket. The bind() function returns a Result<T, E>, where
// T is a Socket and E is an error. First we create
let socket = UdpSocket::bind(socket_addr)
// Same thing as before, either return the socket, or throw the error in this lambda
.unwrap_or_else(|e| {
eprintln!("Connection Error: {}", e);
process::exit(1);
});
println!("Connected!");
// Rust requires us to mark certain operations as unsafe, taking raw bits or data types and
// conveting them into others is one of them. Here, transmute converts an unsigned 32-bit
// integer into an array of bytes (unsigned 8 bit) with a size of 4. Rust also requires
// that the size is known at compile time. This prepares the mobile_id number to be sent
// over the wire via UDP
let mobile_id_buf = unsafe {
std::mem::transmute::<u32, [u8; 4]>(mobile_id)
};
// Loops are simple in Rust
let mut job_id_count = 0;
loop {
let random = rand::thread_rng().gen_range(MIN_JOB_TIME_MS, MAX_JOB_TIME_MS);
// Same as previous unsafe call, this one is nested in the loop cause it changes
// every cycle, no need to do that for the mobile_id, it doesn't change
let time_buf = unsafe {
std::mem::transmute::<u32, [u8; 4]>(random)
};
let job_id_buf = unsafe {
job_id_count += 1;
std::mem::transmute::<u32, [u8; 4]>(job_id_count)
};
// We create a buffer of size 12 and populate it with the mobile_id, job_id and the random time.
// This Buf will then be sent over the wire
let mut buf : [u8; 12] = [0; 12];
for i in 0..buf.len() {
if i < 4 {
buf[i] = mobile_id_buf[i];
} else if i < 8 {
buf[i] = job_id_buf[i - 4];
} else {
buf[i] = time_buf[i - 8];
}
}
println!("Sending job {} that will take {} milliseconds", job_id_count, random);
// Off we go!
socket.send_to(&buf, endpoint)?;
let sleep_rand = rand::thread_rng().gen_range(MIN_SLEEP_TIME_MS, MAX_SLEEP_TIME_MS);
println!("Sent! Sleeping for {}", sleep_rand);
// Now we sleep till the next iteration
thread::sleep(Duration::from_millis(sleep_rand));
}
}
// The function array.get() returns and Option, which can be either None or Some<T>
// We pattern match to extract the values, returning errors as strings when something goes wrong
// If no parameter was passed in through the terminal, we get the None case. If Some, we attempt
// to parse to unsigned 32-bit integer. If that causes and error, the user didn't provide a valid
// integer. map_err converts one error type to anothre
fn parse_id(id_arg : Option<&String>) -> Result<u32, String> {
match id_arg {
None => Err(String::from("No MobileId argument provided")),
Some(a) => a.parse::<u32>().map_err(|_| String::from("Invalid MobileId provided")),
}
}
// Same principle as the previous function
fn parse_client_port(port_arg : Option<&String>) -> Result<u32, String> {
match port_arg {
None => Err(String::from("No Client Port argument provided")),
Some(a) => a.parse::<u32>().map_err(|_| String::from("Invalid Client Port provided")),
}
}
|
use alloc::string::ToString;
use core::fmt;
use crate::base58;
pub type Result<T> = core::result::Result<T, Error>;
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Error {
/// Base58 encoding error
Base58(base58::Error),
/// secp256k1-related error
Secp256k1(secp256k1::Error),
/// hash error
Hash(bitcoin_hashes::error::Error),
/// verify failed
VerifyFailed,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::Base58(ref e) => fmt::Display::fmt(e, f),
Error::Secp256k1(ref e) => f.write_str(&e.to_string()),
Error::Hash(ref e) => f.write_str(&e.to_string()),
Error::VerifyFailed => f.write_str("Verify failed"),
}
}
}
//#[cfg(feature = "std")]
//impl std::error::Error for Error {
// fn description(&self) -> &str {
// match *self {
// Error::Base58(ref e) => e.description(),
// Error::Secp256k1(ref e) => &e.as_str(),
// Error::Hash(ref e) => &e.as_str(),
// ref VerifyFailed => "Verify failed",
// }
// }
//
// fn cause(&self) -> Option<&dyn std::error::Error> {
// match *self {
// Error::Base58(ref e) => Some(e),
// Error::Secp256k1(ref e) => None,
// Error::Hash(ref e) => None,
// ref VerifyFailed => None,
// }
// }
//}
impl From<base58::Error> for Error {
fn from(e: base58::Error) -> Error {
Error::Base58(e)
}
}
impl From<secp256k1::Error> for Error {
fn from(e: secp256k1::Error) -> Error {
Error::Secp256k1(e)
}
}
impl From<bitcoin_hashes::error::Error> for Error {
fn from(e: bitcoin_hashes::error::Error) -> Error {
Error::Hash(e)
}
}
|
use super::super::context::Context;
use super::super::error::Result;
use super::ToDuktape;
#[cfg(feature = "value")]
use value::Value;
macro_rules! push_or_pop {
($dims:expr, $ctx: ident, $popc: expr) => {
match $dims.to_context($ctx) {
Ok(_) => {}
Err(e) => {
$ctx.pop($popc);
return Err(e);
}
};
};
}
pub trait ArgumentList {
fn len(&self) -> i32;
fn push_args(self, ctx: &Context) -> Result<()>;
}
impl<'a> ArgumentList for &'a str {
fn len(&self) -> i32 {
1
}
fn push_args(self, ctx: &Context) -> Result<()> {
ctx.push_string(self);
Ok(())
}
}
impl<'a> ArgumentList for &'a [u8] {
fn len(&self) -> i32 {
1
}
fn push_args(self, ctx: &Context) -> Result<()> {
ctx.push_bytes(self);
Ok(())
}
}
// impl<T: ToDuktape> ArgumentList for T
// where
// T: ToDuktape,
// {
// fn len(&self) -> i32 {
// 1
// }
// fn push_args(self, ctx: &Context) -> Result<()> {
// // ctx.push_bytes(self);
// // Ok(())
// self.to_context(ctx)
// }
// }
#[cfg(feature = "value")]
impl ArgumentList for Value {
fn len(&self) -> i32 {
1
}
fn push_args(self, ctx: &Context) -> Result<()> {
ctx.push(self)?;
Ok(())
}
}
impl ArgumentList for () {
fn len(&self) -> i32 {
0
}
fn push_args(self, _ctx: &Context) -> Result<()> {
Ok(())
}
}
impl<'a, T1: 'a + ToDuktape, T2: 'a + ToDuktape> ArgumentList for (T1, T2)
where
&'a T1: ToDuktape,
&'a T2: ToDuktape,
{
fn len(&self) -> i32 {
2
}
fn push_args(self, ctx: &Context) -> Result<()> {
push_or_pop!(self.0, ctx, 0);
push_or_pop!(self.1, ctx, 1);
Ok(())
}
}
impl<'a, T1: 'a + ToDuktape, T2: 'a + ToDuktape, T3: 'a + ToDuktape> ArgumentList for (T1, T2, T3)
where
&'a T1: ToDuktape,
&'a T2: ToDuktape,
&'a T3: ToDuktape,
{
fn len(&self) -> i32 {
3
}
fn push_args(self, ctx: &Context) -> Result<()> {
push_or_pop!(self.0, ctx, 0);
push_or_pop!(self.1, ctx, 1);
push_or_pop!(self.2, ctx, 2);
Ok(())
}
}
impl<'a, T1: 'a + ToDuktape, T2: 'a + ToDuktape, T3: 'a + ToDuktape, T4: 'a + ToDuktape>
ArgumentList for (T1, T2, T3, T4)
where
&'a T1: ToDuktape,
&'a T2: ToDuktape,
&'a T3: ToDuktape,
&'a T4: ToDuktape,
{
fn len(&self) -> i32 {
4
}
fn push_args(self, ctx: &Context) -> Result<()> {
push_or_pop!(self.0, ctx, 0);
push_or_pop!(self.1, ctx, 1);
push_or_pop!(self.2, ctx, 2);
push_or_pop!(self.3, ctx, 3);
Ok(())
}
}
impl<
'a,
T1: 'a + ToDuktape,
T2: 'a + ToDuktape,
T3: 'a + ToDuktape,
T4: 'a + ToDuktape,
T5: 'a + ToDuktape,
> ArgumentList for (T1, T2, T3, T4, T5)
where
&'a T1: ToDuktape,
&'a T2: ToDuktape,
&'a T3: ToDuktape,
&'a T4: ToDuktape,
&'a T5: ToDuktape,
{
fn len(&self) -> i32 {
5
}
fn push_args(self, ctx: &Context) -> Result<()> {
push_or_pop!(self.0, ctx, 0);
push_or_pop!(self.1, ctx, 1);
push_or_pop!(self.2, ctx, 2);
push_or_pop!(self.3, ctx, 3);
push_or_pop!(self.4, ctx, 4);
Ok(())
}
}
|
use druid::{Command, FileDialogOptions, FileSpec, Selector, Target};
use crate::dialogs::NewFileSettings;
const IMAGE_FILE_TYPE: FileSpec = FileSpec::new("Images", &["bmp", "png", "gif", "jpg", "jpeg"]);
pub(crate) const FILE_EXIT_ACTION: Selector = Selector::new("menu-exit-action");
pub(crate) const FILE_NEW_ACTION: Selector = Selector::new("menu-new-action");
pub(crate) const FILE_NEW_CLIPBOARD_ACTION: Selector = Selector::new("menu-new-clipboard-action");
pub(crate) const EDIT_UNDO_ACTION: Selector = Selector::new("edit-undo-action");
pub(crate) const EDIT_REDO_ACTION: Selector = Selector::new("edit-redo-action");
pub(crate) const EDIT_COPY_ACTION: Selector = Selector::new("edit-copy-action");
pub(crate) const EDIT_PASTE_ACTION: Selector = Selector::new("edit-paste-action");
pub(crate) const ABOUT_TEST_ACTION: Selector = Selector::new("about-test-action");
pub(crate) const NEW_IMAGE_ACTION: Selector<NewFileSettings> = Selector::new("new-image-action");
pub(crate) fn file_open_command() -> Command {
Command::new(
druid::commands::SHOW_OPEN_PANEL,
FileDialogOptions::new().allowed_types(vec![IMAGE_FILE_TYPE]),
Target::Auto,
)
}
pub(crate) fn file_save_as_command() -> Command {
Command::new(
druid::commands::SHOW_SAVE_PANEL,
FileDialogOptions::new().allowed_types(vec![IMAGE_FILE_TYPE]),
Target::Auto,
)
}
|
extern crate dotenv;
use actix_web::error;
use actix_web::error::ErrorUnauthorized;
use actix_web::{web, Error, HttpRequest, HttpResponse};
use postgres::NoTls;
use r2d2::Pool;
use r2d2_postgres::PostgresConnectionManager;
use validator::Validate;
use crate::accounts::*;
use crate::auth::*;
use crate::jwt::*;
use crate::model::*;
pub async fn index() -> Result<HttpResponse, Error> {
Ok(HttpResponse::Ok().body("OK"))
}
pub async fn signup(
form: web::Json<FormLogin>,
db: web::Data<Pool<PostgresConnectionManager<NoTls>>>,
) -> Result<HttpResponse, Error> {
let data = form.into_inner();
match data.clone().validate() {
Ok(_) => (),
Err(e) => return Err(error::ErrorBadRequest(e)),
}
let res = web::block(move || create_account(&data.email, &data.password, db))
.await
.map(|row| match row {
Some(row) => {
let account_id: i32 = row.get("account_id");
let email: String = row.get("email");
let _token = jwt_sign(account_id, email);
let _cookie = get_cookie(_token.clone());
let _res = ResultToken {
success: true,
token: _token,
error: "".to_owned(),
};
HttpResponse::Ok().cookie(_cookie).json(_res)
}
None => {
let _res = ResultToken {
success: false,
token: "".to_owned(),
error: format!("{}", "Faild to sighup."),
};
HttpResponse::Ok().json(_res)
}
})
.map_err(|_| HttpResponse::InternalServerError())?;
Ok(res)
}
pub async fn login(
form: web::Json<FormLogin>,
db: web::Data<Pool<PostgresConnectionManager<NoTls>>>,
) -> Result<HttpResponse, Error> {
let data = form.into_inner();
let email = data.email;
let password = data.password;
let res = web::block(move || find_account(&email, db))
.await
.map(|row| match row {
Some(row) => {
let _account_id: i32 = row.get("account_id");
let _email: String = row.get("email");
let _password: String = row.get("password");
let _hash = get_hash(password.as_str());
if _password == _hash {
let _token = jwt_sign(_account_id, _email);
let _cookie = get_cookie(_token.clone());
let _res = ResultToken {
success: true,
token: _token,
error: "".to_owned(),
};
HttpResponse::Ok().cookie(_cookie).json(_res)
} else {
let _res = ResultToken {
success: false,
token: "".to_owned(),
error: format!("{}", "Password is invalid"),
};
HttpResponse::Ok().json(_res)
}
}
None => {
let _res = ResultToken {
success: false,
token: "".to_owned(),
error: format!("{}", "This email doesn't exist."),
};
HttpResponse::Ok().json(_res)
}
})
.map_err(|_| HttpResponse::InternalServerError())?;
Ok(res)
}
pub async fn verify(req: HttpRequest) -> Result<HttpResponse, Error> {
let res = match req.headers().get("Authorization") {
Some(auth) => {
let _token: Vec<&str> = auth.to_str().unwrap().split("Bearer").collect();
let token = _token[1].trim();
match jwt_verify(token) {
Some(claims) => ResponseAccount {
account_id: claims.sub,
email: claims.email,
},
None => return Err(ErrorUnauthorized("invalid token!")),
}
}
None => return Err(ErrorUnauthorized("invalid token!")),
};
Ok(HttpResponse::Ok().json(res))
}
|
//! # MIR: Mid-level IR
//! We use MIR in optimizing and tracing JIT, MIR includes a few Waffle specific optimizations and it is lowered to LIR or MacroAssembler directly.
pub mod basic_block;
pub mod node;
pub mod opcodes;
pub struct MIRGraph {
pub basic_blocks: Vec<basic_block::BasicBlock>,
pub values: Vec<ValueData>,
pub func_signatures: Vec<(Vec<Type>, Vec<Type>)>,
current_bb: u32,
}
impl MIRGraph {
pub fn walk_value_uses(&self, value: u32, mut f: impl FnMut((u32, u32))) {
for i in 0..self.values[value as usize].uses.len() {
f(self.values[value as usize].uses[i]);
}
}
}
pub struct ValueData {
pub ty: Type,
pub uses: Vec<(u32, u32)>,
}
#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Debug)]
pub enum Type {
ValueI32,
ValueNum,
ValueAnyNum,
ValueString,
ValueArray,
ValueUndefOrNull,
ValueObject,
ValueUnknown,
I32,
I64,
I8,
I16,
F32,
F64,
Func(u32),
Unknown,
}
|
use crate::toCKB_typescript::utils::{case_builder::*, case_runner};
use tockb_types::{
config::{AUCTION_MAX_TIME, CKB_UNITS, LOCK_TYPE_FLAG, SINCE_TYPE_TIMESTAMP, XT_CELL_CAPACITY},
Error,
};
const BTC_BURN_AMOUNT: u128 = 25_000_000;
const TOCKB_CELL_CAPACITY: u64 = 3_750_000 * CKB_UNITS;
const SINCE: u64 = LOCK_TYPE_FLAG | SINCE_TYPE_TIMESTAMP | AUCTION_MAX_TIME;
#[test]
fn test_correct_btc_tx() {
let case = get_correct_btc_case();
case_runner::run_test(case)
}
#[test]
fn test_correct_btc_tx_with_xt_change_back() {
let mut case = get_correct_btc_case();
const CHANGE: u128 = 100;
case.sudt_cells.inputs[0].amount += CHANGE;
case.sudt_cells.outputs.push(SudtCell {
capacity: CKB_UNITS,
amount: CHANGE,
lockscript: Default::default(),
owner_script: Default::default(),
index: 2,
});
case_runner::run_test(case)
}
#[test]
fn test_wrong_btc_tx_with_xt_change_back() {
let mut case = get_correct_btc_case();
const CHANGE: u128 = 100;
case.sudt_cells.inputs[0].amount += CHANGE;
case.sudt_cells.outputs.push(SudtCell {
capacity: CKB_UNITS,
amount: CHANGE + 1,
lockscript: Default::default(),
owner_script: Default::default(),
index: 2,
});
case.expect_return_code = Error::XTAmountInvalid as i8;
case_runner::run_test(case)
}
#[test]
fn test_wrong_input_since() {
let mut case = get_correct_btc_case();
case.toCKB_cells.inputs[0].since = 1;
case.expect_return_code = Error::InputSinceInvalid as i8;
case_runner::run_test(case)
}
#[test]
fn test_wrong_auction_capacity() {
let mut case = get_correct_btc_case();
case.toCKB_cells.inputs[0].since = LOCK_TYPE_FLAG | SINCE_TYPE_TIMESTAMP | 100;
case.expect_return_code = Error::InvalidTriggerOrSignerCell as i8;
case_runner::run_test(case)
}
#[test]
fn test_wrong_xt_burn() {
let mut case = get_correct_btc_case();
case.sudt_cells.inputs[0].amount = 1;
case.expect_return_code = Error::FundingNotEnough as i8;
case_runner::run_test(case)
}
#[test]
fn test_wrong_xt_refund_amount() {
let mut case = get_correct_btc_case();
case.sudt_cells.outputs[0].amount = 1;
case.expect_return_code = Error::InvalidAuctionXTCell as i8;
case_runner::run_test(case)
}
#[test]
fn test_wrong_xt_refund_capacity() {
let mut case = get_correct_btc_case();
case.sudt_cells.outputs[0].capacity = 1;
case.expect_return_code = Error::InvalidAuctionXTCell as i8;
case_runner::run_test(case)
}
#[test]
fn test_wrong_trigger_refund() {
let mut case = get_correct_btc_case();
case.capacity_cells.outputs.push(CapacityCell {
capacity: 100,
lockscript: Default::default(),
index: 1,
});
case.sudt_cells.outputs[0].index = 2;
case.expect_return_code = Error::InvalidAuctionXTCell as i8;
case_runner::run_test(case)
}
#[test]
fn test_wrong_signer_refund() {
let mut case = get_correct_btc_case();
case.capacity_cells.outputs.push(CapacityCell {
capacity: 100,
lockscript: Default::default(),
index: 1,
});
case.sudt_cells.outputs[0].index = 2;
case.expect_return_code = Error::InvalidAuctionXTCell as i8;
case_runner::run_test(case)
}
fn get_correct_btc_case() -> TestCase {
TestCase {
cell_deps: vec![],
toCKB_cells: ToCKBCells {
inputs: vec![ToCKBCell {
capacity: TOCKB_CELL_CAPACITY + XT_CELL_CAPACITY,
data: ToCKBCellDataView {
status: 5,
lot_size: 1,
user_lockscript: Default::default(),
x_lock_address: Default::default(),
signer_lockscript: Default::default(),
x_unlock_address: Default::default(),
redeemer_lockscript: Default::default(),
liquidation_trigger_lockscript: Default::default(),
x_extra: Default::default(),
},
type_args: ToCKBTypeArgsView {
xchain_kind: 1,
cell_id: ToCKBTypeArgsView::default_cell_id(),
},
since: SINCE,
index: 0,
}],
outputs: vec![],
},
sudt_cells: SudtCells {
inputs: vec![SudtCell {
capacity: 210 * CKB_UNITS,
amount: BTC_BURN_AMOUNT,
lockscript: Default::default(),
owner_script: Default::default(),
index: 1,
}],
outputs: vec![SudtCell {
capacity: XT_CELL_CAPACITY,
amount: BTC_BURN_AMOUNT,
lockscript: Default::default(),
owner_script: Default::default(),
index: 1,
}],
},
capacity_cells: CapacityCells {
inputs: vec![],
outputs: vec![CapacityCell {
capacity: TOCKB_CELL_CAPACITY + 1,
lockscript: Default::default(),
index: 0,
}],
},
witnesses: vec![],
expect_return_code: 0,
}
}
|
extern crate image;
// https://drive.google.com/drive/folders/14yayBb9XiL16lmuhbYhhvea8mKUUK77W
use std::ops::Sub;
use std::ops::Add;
use std::ops::Mul;
use std::path::Path;
struct Point {
x: f32,
y: f32,
z: f32,
}
impl Copy for Point {}
impl Clone for Point {
fn clone(&self) -> Point {
*self
}
}
impl Sub for Point {
type Output = Vector;
fn sub(self, other: Point) -> Vector {
Vector::new(self.x - other.x, self.y - other.y, self.z - other.z)
}
}
impl Point {
fn zero() -> Point {
Point { x: 0.0, y: 0.0, z: 0.0, }
}
fn new(x: f32, y: f32, z: f32) -> Point {
Point { x: x, y: y, z: z }
}
}
struct Color { r: f32, b: f32, g: f32, a: f32, }
impl Color {
fn new(r: f32, b: f32, g: f32, a: f32) -> Color {
Color { r: r, b: b, g: g, a: a, }
}
}
impl Copy for Color {}
impl Clone for Color {
fn clone(&self) -> Color {
*self
}
}
#[derive(Debug)]
struct Vector { x: f32, y: f32, z: f32, }
impl Vector {
fn new(x: f32, y: f32, z: f32) -> Vector {
Vector { x: x, y: y, z: z }
}
fn length(&self) -> f32 {
(self.x * self.x + self.y * self.y + self.z * self.z).sqrt()
}
fn make_unit_vector(self) -> Vector {
let k = 1.0 / self.length();
Vector::new( self.x * k, self.y * k, self.z * k)
}
}
// dot product
impl Mul<Vector> for Vector {
type Output = f32;
fn mul(self, other: Vector) -> f32 {
(self.x * other.x + self.y * other.y + self.z * other.z)
}
}
impl Mul<f32> for Vector {
type Output = Vector;
fn mul(self, other: f32) -> Vector {
Vector::new(self.x * other, self.y * other, self.z * other)
}
}
impl Sub<Vector> for Vector {
type Output = Vector;
fn sub(self, other: Vector) -> Vector {
Vector::new(self.x - other.x, self.y - other.y, self.z - other.z)
}
}
impl Add<Vector> for Vector {
type Output = Vector;
fn add(self, other: Vector) -> Vector {
Vector::new(self.x + other.x, self.y + other.y, self.z + other.z)
}
}
struct Sphere {
radius: f32,
center: Point,
}
const WIDTH: usize = 800;
const HEIGHT: usize = 800;
fn display_color(color: &Color) {
println!("({}, {}, {}, {})", color.r, color.g, color.b, color.a);
}
fn flatten(pixels: &mut Vec<Color>) -> Vec<u8> {
const MAX_N: usize = WIDTH * HEIGHT * 4;
let mut buffer = vec![0; MAX_N];
for (i, color) in pixels.iter().enumerate() {
let index = i * 4;
buffer[index + 0] = (color.r * 255.99) as u8;
buffer[index + 1] = (color.g * 255.99) as u8;
buffer[index + 2] = (color.b * 255.99) as u8;
buffer[index + 3] = (color.a * 255.99) as u8;
}
return buffer;
}
fn main() {
let eye = Point::new(0.0, 0.0, 10.0);
let mut pixels = vec![Color::new(0.0, 0.0, 0.0, 1.0); WIDTH * HEIGHT];
for i in 0..pixels.len() {
let x = i as i32 % 800;
let y = i as i32 / 800;
pixels[i].r = x as f32 / 800.0;
pixels[i].g = y as f32 / 800.0;
pixels[i].b = 0.2;
}
let a = Point::new(0.0, 0.0, 0.0);
let b = Point::new(1.0, 1.0, 1.0);
let p1 = b - a;
let p2 = a - b;
println!("{:?}", p1);
println!("{:?}", p1.length());
println!("{:?}", p1*3);
// flatten the color vect to a buffer.
let buffer = flatten(&mut pixels);
// Save the buffer as "image.png"
image::save_buffer(&Path::new("image.png"), &buffer, 800, 800, image::RGBA(8)).unwrap();
}
|
use error::Result;
use std::fmt;
use std::path::Path;
#[macro_use] mod utils;
pub mod sys;
#[cfg(feature = "zip")] pub mod zip;
pub trait Handler: fmt::Debug {
fn stat(&mut self, path: &Path) -> Result<::fs::stat::Stat>;
fn read_dir(&mut self, path: &Path) -> Result<::fs::dir::ReadDirIterator>;
fn open(&mut self, path: &Path) -> Result<::fs::file::File<::fs::file::Read>>;
fn exists(&mut self, path: &Path) -> bool {
self.stat(path).is_ok()
}
}
|
//! Link: https://adventofcode.com/2019/day/14
//! Day 14: Oxygen System
//!
//! Out here in deep space, many things can go wrong.
//! Fortunately, many of those things have indicator lights.
//! Unfortunately, one of those lights is lit:
//! the oxygen system for part of the ship has failed!
//!
//! According to the readouts, the oxygen system must have failed
//! days ago after a rupture in oxygen tank two;
//! that section of the ship was automatically
//! sealed once oxygen levels went dangerously low.
//! A single remotely-operated repair droid is your
//! only option for fixing the oxygen system.
//!
//! The Elves' care package included an Intcode program (your puzzle input)
//! that you can use to remotely control the repair droid.
//! By running that program, you can direct the repair droid
//! to the oxygen system and fix the problem.
use crate::common::intcode::{vm::Intcode};
use std::collections::HashMap;
const NORTH: i8 = 1;
const SOUTH: i8 = 2;
const WEST: i8 = 3;
const EAST: i8 = 4;
const DIRECTIONS: [i8; 4] = [NORTH, SOUTH, EAST, WEST];
const WALL: i8 = 1;
const OXYGEN: i8 = 2;
const SPACE: i8 = 3;
#[aoc_generator(day15)]
fn input_generator(input: &str) -> Intcode {
Intcode::from(input)
}
// The remote control program executes the following steps in a loop forever:
//
// Accept a movement command via an input instruction.
// Send the movement command to the repair droid.
// Wait for the repair droid to finish the movement operation.
// Report on the status of the repair droid via an output instruction.
//
// Only four movement commands are understood:
// north (1), south (2), west (3), and east (4).
// Any other command is invalid.
// The movements differ in direction, but not in distance:
// in a long enough east-west hallway,
// a series of commands like 4,4,4,4,3,3,3,3
// would leave the repair droid back where it started.
//
// The repair droid can reply with any of the following status codes:
// - 0: The repair droid hit a wall. Its position has not changed.
// - 1: The repair droid has moved one step in the requested direction.
// - 2: The repair droid has moved one step in the requested direction;
// its new position is the location of the oxygen system.
//
// You don't know anything about the area around the repair droid,
// but you can figure it out by watching the status codes.
//
// What is the fewest number of movement commands required to
// move the repair droid from its starting position to the location of the oxygen system?
//
// Your puzzle answer was 308.
#[aoc(day15, part1, Base)]
fn solve_part1_base(vm: &Intcode) -> usize {
let mut all_vms = vec![(vm.clone(), (0, 0))];
let mut map: HashMap<(i64, i64), i8> = HashMap::new();
let mut steps = None;
'a: for i in 1.. {
for (prog, pos) in all_vms.drain(..).collect::<Vec<_>>().into_iter() {
for &dir in DIRECTIONS.iter() {
let new_pos = translate(&pos, dir);
if map.contains_key(&new_pos) {
continue;
}
let mut new = prog.clone();
new.inputs.push_back(dir.into());
match new.next().unwrap().unwrap() {
0 => {
map.insert(new_pos, WALL);
}
1 => {
map.insert(new_pos, SPACE);
all_vms.push((new, new_pos));
}
2 => {
map.insert(new_pos, OXYGEN);
steps = Some(i);
break 'a;
}
_ => unreachable!(),
}
}
}
}
steps.unwrap()
}
// You quickly repair the oxygen system; oxygen gradually fills the area.
//
// Oxygen starts in the location containing the repaired oxygen system.
// It takes one minute for oxygen to spread to all open
// locations that are adjacent to a location that already contains oxygen.
// Diagonal locations are not adjacent.
//
// Use the repair droid to get a complete map of the area.
// How many minutes will it take to fill with oxygen.
//
// Your puzzle answer was 328.
#[aoc(day15, part2, Base)]
fn solve_part2_base(vm: &Intcode) -> usize {
let mut all_vms = vec![(vm.clone(), (0, 0))];
let mut map: HashMap<(i64, i64), i8> = HashMap::new();
let mut goal_prog = None;
'a: for _ in 1.. {
for (prog, pos) in all_vms.drain(..).collect::<Vec<_>>().into_iter() {
for &dir in DIRECTIONS.iter() {
let new_pos = translate(&pos, dir);
if map.contains_key(&new_pos) {
continue;
}
let mut new = prog.clone();
new.inputs.push_back(dir.into());
match new.next().unwrap().unwrap() {
0 => {
map.insert(new_pos, WALL);
}
1 => {
map.insert(new_pos, SPACE);
all_vms.push((new, new_pos));
}
2 => {
map.insert(new_pos, OXYGEN);
goal_prog = Some((new, new_pos));
break 'a;
}
_ => unreachable!(),
}
}
}
}
all_vms = vec![(goal_prog.unwrap())];
map = map.into_iter().filter(|(_k, v)| *v != SPACE.into()).collect();
let mut minutes = None;
for i in 0.. {
if all_vms.is_empty() {
minutes = Some(i - 1);
break;
}
for (prog, pos) in all_vms.drain(..).collect::<Vec<_>>().into_iter() {
for &dir in DIRECTIONS.iter() {
let new_pos = translate(&pos, dir);
if map.contains_key(&new_pos) {
continue;
}
let mut new = prog.clone();
new.inputs.push_back(dir.into());
match new.next().unwrap().unwrap() {
0 => {
map.insert(new_pos, WALL);
}
1 => {
map.insert(new_pos, SPACE);
all_vms.push((new, new_pos));
}
_ => unreachable!(),
}
}
}
}
minutes.unwrap()
}
fn translate(pos: &(i64, i64), direction: i8) -> (i64, i64) {
match direction {
NORTH => (pos.0 - 1, pos.1),
SOUTH => (pos.0 + 1, pos.1),
WEST => (pos.0, pos.1 - 1),
EAST => (pos.0, pos.1 + 1),
_ => unreachable!(),
}
} |
#[doc = "Register `HDP_CTRL` reader"]
pub type R = crate::R<HDP_CTRL_SPEC>;
#[doc = "Register `HDP_CTRL` writer"]
pub type W = crate::W<HDP_CTRL_SPEC>;
#[doc = "Field `EN` reader - EN"]
pub type EN_R = crate::BitReader;
#[doc = "Field `EN` writer - EN"]
pub type EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - EN"]
#[inline(always)]
pub fn en(&self) -> EN_R {
EN_R::new((self.bits & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - EN"]
#[inline(always)]
#[must_use]
pub fn en(&mut self) -> EN_W<HDP_CTRL_SPEC, 0> {
EN_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 = "HDP Control\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hdp_ctrl::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 [`hdp_ctrl::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct HDP_CTRL_SPEC;
impl crate::RegisterSpec for HDP_CTRL_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`hdp_ctrl::R`](R) reader structure"]
impl crate::Readable for HDP_CTRL_SPEC {}
#[doc = "`write(|w| ..)` method takes [`hdp_ctrl::W`](W) writer structure"]
impl crate::Writable for HDP_CTRL_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets HDP_CTRL to value 0"]
impl crate::Resettable for HDP_CTRL_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use serde_json::Value;
pub(crate) fn get_json_value_difference(
reference: String,
desire: &Value,
current: &Value,
) -> Option<Value> {
match (desire, current) {
(Value::Bool(des), Value::Bool(cur)) => {
if des != cur {
Some(Value::String(format!(
"{}: desire bool: {}, current: {}",
&reference, des, cur
)))
} else {
None
}
}
(Value::Number(des), Value::Number(cur)) => {
if des != cur {
Some(Value::String(format!(
"{}: desire number: {}, current: {}",
&reference, des, cur
)))
} else {
None
}
}
(Value::String(des), Value::String(cur)) => {
if des != cur {
Some(Value::String(format!(
"{}: desire string: {}, current: {}",
&reference, des, cur
)))
} else {
None
}
}
(Value::Array(des), Value::Array(cur)) => {
if des.len() != cur.len() {
Some(Value::String(format!(
"{} different array length {} vs {}: \
desire {}, current: {}",
&reference,
des.len(),
cur.len(),
desire.to_string(),
current.to_string()
)))
} else {
for (index, des_element) in des.iter().enumerate() {
// The [] is safe as we already checked the length
let cur_element = &cur[index];
if let Some(difference) = get_json_value_difference(
format!("{}[{}]", &reference, index),
des_element,
cur_element,
) {
return Some(difference);
}
}
None
}
}
(Value::Object(des), Value::Object(cur)) => {
for (key, des_value) in des.iter() {
let reference = format!("{}.{}", reference, key);
if let Some(cur_value) = cur.get(key) {
if let Some(difference) = get_json_value_difference(
reference.clone(),
des_value,
cur_value,
) {
return Some(difference);
}
} else {
return Some(Value::String(format!(
"{}: desire: {}, current: None",
&reference,
des_value.to_string()
)));
}
}
None
}
(Value::Null, _) => None,
(_, _) => Some(Value::String(format!(
"{}: type miss match, desire: {} current: {}",
&reference,
desire.to_string(),
current.to_string()
))),
}
}
|
//! The file tree generator.
//!
//! Unlike the other generators the file generator does not "connect" however
//! losely to the target but instead, without coordination, merely generates
//! a file tree and generates random acess/rename operations.
use rand::{
distributions::{Alphanumeric, DistString},
seq::SliceRandom,
};
use std::{
collections::VecDeque,
num::{NonZeroU32, NonZeroUsize},
path,
path::Path,
path::PathBuf,
str,
};
use rand::{prelude::StdRng, SeedableRng};
use serde::Deserialize;
use tokio::{fs::create_dir, fs::rename, fs::File};
use tracing::info;
use crate::{
signals::Shutdown,
throttle::{self, Throttle},
};
static FILE_EXTENSION: &str = "txt";
#[derive(thiserror::Error, Debug)]
/// Errors produced by [`FileTree`].
pub enum Error {
/// Wrapper around [`std::io::Error`].
#[error("Io error: {0}")]
Io(::std::io::Error),
}
impl From<::std::io::Error> for Error {
fn from(error: ::std::io::Error) -> Self {
Error::Io(error)
}
}
fn default_max_depth() -> NonZeroUsize {
NonZeroUsize::new(10).unwrap()
}
fn default_max_sub_folders() -> NonZeroU32 {
NonZeroU32::new(5).unwrap()
}
fn default_max_files() -> NonZeroU32 {
NonZeroU32::new(5).unwrap()
}
fn default_max_nodes() -> NonZeroUsize {
NonZeroUsize::new(100).unwrap()
}
fn default_name_len() -> NonZeroUsize {
NonZeroUsize::new(8).unwrap()
}
fn default_open_per_second() -> NonZeroU32 {
NonZeroU32::new(8).unwrap()
}
fn default_rename_per_name() -> NonZeroU32 {
NonZeroU32::new(1).unwrap()
}
#[derive(Debug, Deserialize, PartialEq, Clone)]
/// Configuration of [`FileTree`]
pub struct Config {
/// The seed for random operations against this target
pub seed: [u8; 32],
/// The maximum depth of the file tree
#[serde(default = "default_max_depth")]
pub max_depth: NonZeroUsize,
/// The maximum number of sub folders
#[serde(default = "default_max_sub_folders")]
pub max_sub_folders: NonZeroU32,
/// The maximum number of files per folder
#[serde(default = "default_max_files")]
pub max_files: NonZeroU32,
/// The maximum number of nodes (folder/file) created
#[serde(default = "default_max_nodes")]
pub max_nodes: NonZeroUsize,
/// The name length of the nodes (folder/file) without the extension
#[serde(default = "default_name_len")]
pub name_len: NonZeroUsize,
/// The root folder where the nodes will be created
pub root: String,
/// The number of nodes opened per second
#[serde(default = "default_open_per_second")]
pub open_per_second: NonZeroU32,
#[serde(default = "default_rename_per_name")]
/// The number of rename per second
pub rename_per_second: NonZeroU32,
/// The load throttle configuration
#[serde(default)]
pub throttle: throttle::Config,
}
#[derive(Debug)]
/// The file tree generator.
///
/// This generator generates a file tree and generates random access/rename operations,
/// this without coordination to the target.
pub struct FileTree {
name_len: NonZeroUsize,
open_throttle: Throttle,
rename_throttle: Throttle,
total_folder: usize,
nodes: VecDeque<PathBuf>,
rng: StdRng,
shutdown: Shutdown,
}
impl FileTree {
/// Create a new [`FileTree`]
///
/// # Errors
///
/// Creation will fail if the target file/folder cannot be opened for writing.
#[allow(clippy::cast_possible_truncation)]
pub fn new(config: &Config, shutdown: Shutdown) -> Result<Self, Error> {
let mut rng = StdRng::from_seed(config.seed);
let (nodes, _total_files, total_folder) = generate_tree(&mut rng, config);
let open_throttle = Throttle::new_with_config(config.throttle, config.open_per_second);
let rename_throttle = Throttle::new_with_config(config.throttle, config.rename_per_second);
Ok(Self {
name_len: config.name_len,
open_throttle,
rename_throttle,
total_folder,
nodes,
rng,
shutdown,
})
}
/// Run [`FileTree`] to completion or until a shutdown signal is received.
///
/// In this loop the file tree will be generated and accessed.
///
/// # Errors
///
/// This function will terminate with an error if file permissions are not
/// correct, if the file cannot be written to etc. Any error from
/// `std::io::Error` is possible.
///
/// # Panics
///
/// Function will panic if one node is not path is not populated properly
pub async fn spin(mut self) -> Result<(), Error> {
let mut iter = self.nodes.iter().cycle();
let mut folders = Vec::with_capacity(self.total_folder);
loop {
tokio::select! {
_ = self.open_throttle.wait() => {
let node = iter.next().unwrap();
if node.exists() {
File::open(node.as_path()).await?;
} else {
create_node(node).await?;
if is_folder(node) {
folders.push(node);
}
}
},
_ = self.rename_throttle.wait() => {
if let Some(folder) = folders.choose_mut(&mut self.rng) {
rename_folder(&mut self.rng, folder, self.name_len.get()).await?;
}
}
_ = self.shutdown.recv() => {
info!("shutdown signal received");
break;
},
}
}
Ok(())
}
}
fn generate_tree(rng: &mut StdRng, config: &Config) -> (VecDeque<PathBuf>, usize, usize) {
let mut nodes = VecDeque::new();
let root_depth = config.root.matches(path::MAIN_SEPARATOR).count();
let mut total_file: usize = 0;
let mut total_folder: usize = 0;
let mut stack = Vec::new();
stack.push(PathBuf::from(config.root.clone()));
loop {
if let Some(node) = stack.pop() {
if is_folder(&node) {
// generate files
for _n in 0..config.max_files.get() {
if total_file + total_folder < config.max_nodes.get() {
let file = rnd_file_name(rng, &node, config.name_len.get());
stack.push(file);
total_file += 1;
}
}
let curr_depth =
node.to_str().unwrap().matches(path::MAIN_SEPARATOR).count() - root_depth;
// generate sub folders
if curr_depth < config.max_depth.get() {
for _n in 0..config.max_sub_folders.get() {
if total_file + total_folder < config.max_nodes.get() {
let dir = rnd_node_name(rng, &node, config.name_len.get());
stack.push(dir);
total_folder += 1;
}
}
}
}
nodes.push_back(node);
} else {
return (nodes, total_file, total_folder);
}
}
}
#[inline]
async fn rename_folder(rng: &mut StdRng, folder: &Path, len: usize) -> Result<(), Error> {
let parent = PathBuf::from(folder.parent().unwrap());
let dir = rnd_node_name(rng, &parent, len);
// rename twice to keep the original folder name so that future file access
// in the folder will still work
rename(&folder, &dir).await?;
rename(&dir, &folder).await?;
Ok(())
}
#[inline]
fn is_folder(node: &Path) -> bool {
node.extension().is_none()
}
#[inline]
async fn create_node(node: &Path) -> Result<(), Error> {
if is_folder(node) {
create_dir(node).await?;
} else {
File::create(node).await?;
}
Ok(())
}
#[inline]
fn rnd_node_name(rng: &mut StdRng, dir: &Path, len: usize) -> PathBuf {
let name = Alphanumeric.sample_string(rng, len);
dir.join(name)
}
#[inline]
fn rnd_file_name(rng: &mut StdRng, dir: &Path, len: usize) -> PathBuf {
let mut node = rnd_node_name(rng, dir, len);
node.set_extension(FILE_EXTENSION);
node
}
|
#![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 operations {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list(operation_config: &crate::OperationConfig) -> std::result::Result<OperationsList, list::Error> {
let client = &operation_config.client;
let uri_str = &format!("{}/providers/Microsoft.SecurityInsights/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: OperationsList = serde_json::from_slice(&body).context(list::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?;
list::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod list {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
UnexpectedResponse { status_code: StatusCode, body: bytes::Bytes },
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 alert_rules {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
) -> std::result::Result<AlertRulesList, list::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/alertRules",
&operation_config.base_path, subscription_id, resource_group_name, operational_insights_resource_provider, workspace_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(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: AlertRulesList = 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: CloudError = 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::CloudError,
},
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,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
rule_id: &str,
) -> std::result::Result<AlertRule, get::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/alertRules/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
rule_id
);
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: AlertRule = 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: CloudError = 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::CloudError,
},
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,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
rule_id: &str,
alert_rule: &AlertRule,
) -> std::result::Result<create_or_update::Response, create_or_update::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/alertRules/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
rule_id
);
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(alert_rule);
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: AlertRule = 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: AlertRule = 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: CloudError = 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(AlertRule),
Created201(AlertRule),
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
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,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
rule_id: &str,
) -> std::result::Result<delete::Response, delete::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/alertRules/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
rule_id
);
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(delete::Response::Ok200),
StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(delete::ResponseBytesError)?;
let rsp_value: CloudError = 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)]
pub enum Response {
Ok200,
NoContent204,
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
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_action(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
rule_id: &str,
action_id: &str,
) -> std::result::Result<ActionResponse, get_action::Error> {
let client = &operation_config.client;
let uri_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/alertRules/{}/actions/{}" , & operation_config . base_path , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , rule_id , action_id) ;
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_action::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_action::BuildRequestError)?;
let rsp = client.execute(req).await.context(get_action::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(get_action::ResponseBytesError)?;
let rsp_value: ActionResponse = serde_json::from_slice(&body).context(get_action::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get_action::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(get_action::DeserializeError { body })?;
get_action::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod get_action {
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::CloudError,
},
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_action(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
rule_id: &str,
action_id: &str,
action: &ActionRequest,
) -> std::result::Result<create_or_update_action::Response, create_or_update_action::Error> {
let client = &operation_config.client;
let uri_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/alertRules/{}/actions/{}" , & operation_config . base_path , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , rule_id , action_id) ;
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_action::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(action);
let req = req_builder.build().context(create_or_update_action::BuildRequestError)?;
let rsp = client.execute(req).await.context(create_or_update_action::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update_action::ResponseBytesError)?;
let rsp_value: ActionResponse =
serde_json::from_slice(&body).context(create_or_update_action::DeserializeError { body })?;
Ok(create_or_update_action::Response::Ok200(rsp_value))
}
StatusCode::CREATED => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update_action::ResponseBytesError)?;
let rsp_value: ActionResponse =
serde_json::from_slice(&body).context(create_or_update_action::DeserializeError { body })?;
Ok(create_or_update_action::Response::Created201(rsp_value))
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update_action::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(create_or_update_action::DeserializeError { body })?;
create_or_update_action::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod create_or_update_action {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(ActionResponse),
Created201(ActionResponse),
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
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_action(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
rule_id: &str,
action_id: &str,
) -> std::result::Result<delete_action::Response, delete_action::Error> {
let client = &operation_config.client;
let uri_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/alertRules/{}/actions/{}" , & operation_config . base_path , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , rule_id , action_id) ;
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_action::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_action::BuildRequestError)?;
let rsp = client.execute(req).await.context(delete_action::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => Ok(delete_action::Response::Ok200),
StatusCode::NO_CONTENT => Ok(delete_action::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(delete_action::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(delete_action::DeserializeError { body })?;
delete_action::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod delete_action {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200,
NoContent204,
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
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 actions {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list_by_alert_rule(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
rule_id: &str,
) -> std::result::Result<ActionsList, list_by_alert_rule::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/alertRules/{}/actions",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
rule_id
);
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_alert_rule::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_by_alert_rule::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_by_alert_rule::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_alert_rule::ResponseBytesError)?;
let rsp_value: ActionsList = serde_json::from_slice(&body).context(list_by_alert_rule::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_alert_rule::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(list_by_alert_rule::DeserializeError { body })?;
list_by_alert_rule::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod list_by_alert_rule {
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::CloudError,
},
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 alert_rule_templates {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
) -> std::result::Result<AlertRuleTemplatesList, list::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/alertRuleTemplates",
&operation_config.base_path, subscription_id, resource_group_name, operational_insights_resource_provider, workspace_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(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: AlertRuleTemplatesList = 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: CloudError = 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::CloudError,
},
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,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
alert_rule_template_id: &str,
) -> std::result::Result<AlertRuleTemplate, get::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/alertRuleTemplates/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
alert_rule_template_id
);
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: AlertRuleTemplate = 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: CloudError = 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::CloudError,
},
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 cases {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
filter: Option<&str>,
orderby: Option<&str>,
top: Option<i32>,
skip_token: Option<&str>,
) -> std::result::Result<CaseList, list::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/cases",
&operation_config.base_path, subscription_id, resource_group_name, operational_insights_resource_provider, workspace_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(list::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(orderby) = orderby {
req_builder = req_builder.query(&[("$orderby", orderby)]);
}
if let Some(top) = top {
req_builder = req_builder.query(&[("$top", top)]);
}
if let Some(skip_token) = skip_token {
req_builder = req_builder.query(&[("$skipToken", skip_token)]);
}
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: CaseList = 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: CloudError = 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::CloudError,
},
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,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
case_id: &str,
) -> std::result::Result<Case, get::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/cases/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
case_id
);
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: Case = 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: CloudError = 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::CloudError,
},
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,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
case_id: &str,
case: &Case,
) -> std::result::Result<create_or_update::Response, create_or_update::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/cases/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
case_id
);
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(case);
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: Case = 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: Case = 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: CloudError = 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(Case),
Created201(Case),
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
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,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
case_id: &str,
) -> std::result::Result<delete::Response, delete::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/cases/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
case_id
);
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(delete::Response::Ok200),
StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(delete::ResponseBytesError)?;
let rsp_value: CloudError = 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)]
pub enum Response {
Ok200,
NoContent204,
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
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_comment(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
case_id: &str,
case_comment_id: &str,
) -> std::result::Result<CaseComment, get_comment::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/cases/{}/comments/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
case_id,
case_comment_id
);
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_comment::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_comment::BuildRequestError)?;
let rsp = client.execute(req).await.context(get_comment::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(get_comment::ResponseBytesError)?;
let rsp_value: CaseComment = serde_json::from_slice(&body).context(get_comment::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get_comment::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(get_comment::DeserializeError { body })?;
get_comment::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod get_comment {
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::CloudError,
},
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 comments {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list_by_case(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
case_id: &str,
filter: Option<&str>,
orderby: Option<&str>,
top: Option<i32>,
skip_token: Option<&str>,
) -> std::result::Result<CaseCommentList, list_by_case::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/cases/{}/comments",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
case_id
);
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_case::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(orderby) = orderby {
req_builder = req_builder.query(&[("$orderby", orderby)]);
}
if let Some(top) = top {
req_builder = req_builder.query(&[("$top", top)]);
}
if let Some(skip_token) = skip_token {
req_builder = req_builder.query(&[("$skipToken", skip_token)]);
}
let req = req_builder.build().context(list_by_case::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_by_case::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_case::ResponseBytesError)?;
let rsp_value: CaseCommentList = serde_json::from_slice(&body).context(list_by_case::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_case::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(list_by_case::DeserializeError { body })?;
list_by_case::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod list_by_case {
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::CloudError,
},
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 case_comments {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn create_comment(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
case_id: &str,
case_comment_id: &str,
case_comment: &CaseComment,
) -> std::result::Result<CaseComment, create_comment::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/cases/{}/comments/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
case_id,
case_comment_id
);
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_comment::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(case_comment);
let req = req_builder.build().context(create_comment::BuildRequestError)?;
let rsp = client.execute(req).await.context(create_comment::ExecuteRequestError)?;
match rsp.status() {
StatusCode::CREATED => {
let body: bytes::Bytes = rsp.bytes().await.context(create_comment::ResponseBytesError)?;
let rsp_value: CaseComment = serde_json::from_slice(&body).context(create_comment::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(create_comment::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(create_comment::DeserializeError { body })?;
create_comment::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod create_comment {
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::CloudError,
},
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 bookmarks {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
) -> std::result::Result<BookmarkList, list::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/bookmarks",
&operation_config.base_path, subscription_id, resource_group_name, operational_insights_resource_provider, workspace_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(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: BookmarkList = 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: CloudError = 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::CloudError,
},
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,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
bookmark_id: &str,
) -> std::result::Result<Bookmark, get::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/bookmarks/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
bookmark_id
);
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: Bookmark = 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: CloudError = 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::CloudError,
},
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,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
bookmark_id: &str,
bookmark: &Bookmark,
) -> std::result::Result<create_or_update::Response, create_or_update::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/bookmarks/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
bookmark_id
);
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(bookmark);
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: Bookmark = 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: Bookmark = 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: CloudError = 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(Bookmark),
Created201(Bookmark),
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
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,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
bookmark_id: &str,
) -> std::result::Result<delete::Response, delete::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/bookmarks/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
bookmark_id
);
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(delete::Response::Ok200),
StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(delete::ResponseBytesError)?;
let rsp_value: CloudError = 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)]
pub enum Response {
Ok200,
NoContent204,
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
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 case_relations {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
case_id: &str,
filter: Option<&str>,
orderby: Option<&str>,
top: Option<i32>,
skip_token: Option<&str>,
) -> std::result::Result<CaseRelationList, list::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/cases/{}/relations",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
case_id
);
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)]);
if let Some(filter) = filter {
req_builder = req_builder.query(&[("$filter", filter)]);
}
if let Some(orderby) = orderby {
req_builder = req_builder.query(&[("$orderby", orderby)]);
}
if let Some(top) = top {
req_builder = req_builder.query(&[("$top", top)]);
}
if let Some(skip_token) = skip_token {
req_builder = req_builder.query(&[("$skipToken", skip_token)]);
}
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: CaseRelationList = 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: CloudError = 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::CloudError,
},
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_relation(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
case_id: &str,
relation_name: &str,
) -> std::result::Result<CaseRelation, get_relation::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/cases/{}/relations/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
case_id,
relation_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_relation::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_relation::BuildRequestError)?;
let rsp = client.execute(req).await.context(get_relation::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(get_relation::ResponseBytesError)?;
let rsp_value: CaseRelation = serde_json::from_slice(&body).context(get_relation::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get_relation::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(get_relation::DeserializeError { body })?;
get_relation::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod get_relation {
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::CloudError,
},
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_relation(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
case_id: &str,
relation_name: &str,
relation_input_model: &RelationsModelInput,
) -> std::result::Result<create_or_update_relation::Response, create_or_update_relation::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/cases/{}/relations/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
case_id,
relation_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_relation::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(relation_input_model);
let req = req_builder.build().context(create_or_update_relation::BuildRequestError)?;
let rsp = client.execute(req).await.context(create_or_update_relation::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update_relation::ResponseBytesError)?;
let rsp_value: CaseRelation =
serde_json::from_slice(&body).context(create_or_update_relation::DeserializeError { body })?;
Ok(create_or_update_relation::Response::Ok200(rsp_value))
}
StatusCode::CREATED => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update_relation::ResponseBytesError)?;
let rsp_value: CaseRelation =
serde_json::from_slice(&body).context(create_or_update_relation::DeserializeError { body })?;
Ok(create_or_update_relation::Response::Created201(rsp_value))
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update_relation::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(create_or_update_relation::DeserializeError { body })?;
create_or_update_relation::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod create_or_update_relation {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(CaseRelation),
Created201(CaseRelation),
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
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_relation(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
case_id: &str,
relation_name: &str,
) -> std::result::Result<delete_relation::Response, delete_relation::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/cases/{}/relations/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
case_id,
relation_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_relation::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_relation::BuildRequestError)?;
let rsp = client.execute(req).await.context(delete_relation::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => Ok(delete_relation::Response::Ok200),
StatusCode::NO_CONTENT => Ok(delete_relation::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(delete_relation::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(delete_relation::DeserializeError { body })?;
delete_relation::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod delete_relation {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200,
NoContent204,
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
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 bookmark_relations {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
bookmark_id: &str,
filter: Option<&str>,
orderby: Option<&str>,
top: Option<i32>,
skip_token: Option<&str>,
) -> std::result::Result<RelationList, list::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/bookmarks/{}/relations",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
bookmark_id
);
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)]);
if let Some(filter) = filter {
req_builder = req_builder.query(&[("$filter", filter)]);
}
if let Some(orderby) = orderby {
req_builder = req_builder.query(&[("$orderby", orderby)]);
}
if let Some(top) = top {
req_builder = req_builder.query(&[("$top", top)]);
}
if let Some(skip_token) = skip_token {
req_builder = req_builder.query(&[("$skipToken", skip_token)]);
}
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: RelationList = 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: CloudError = 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::CloudError,
},
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_relation(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
bookmark_id: &str,
relation_name: &str,
) -> std::result::Result<Relation, get_relation::Error> {
let client = &operation_config.client;
let uri_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/bookmarks/{}/relations/{}" , & operation_config . base_path , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , bookmark_id , relation_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_relation::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_relation::BuildRequestError)?;
let rsp = client.execute(req).await.context(get_relation::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(get_relation::ResponseBytesError)?;
let rsp_value: Relation = serde_json::from_slice(&body).context(get_relation::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get_relation::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(get_relation::DeserializeError { body })?;
get_relation::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod get_relation {
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::CloudError,
},
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_relation(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
bookmark_id: &str,
relation_name: &str,
relation: &Relation,
) -> std::result::Result<create_or_update_relation::Response, create_or_update_relation::Error> {
let client = &operation_config.client;
let uri_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/bookmarks/{}/relations/{}" , & operation_config . base_path , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , bookmark_id , relation_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_relation::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(relation);
let req = req_builder.build().context(create_or_update_relation::BuildRequestError)?;
let rsp = client.execute(req).await.context(create_or_update_relation::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update_relation::ResponseBytesError)?;
let rsp_value: Relation = serde_json::from_slice(&body).context(create_or_update_relation::DeserializeError { body })?;
Ok(create_or_update_relation::Response::Ok200(rsp_value))
}
StatusCode::CREATED => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update_relation::ResponseBytesError)?;
let rsp_value: Relation = serde_json::from_slice(&body).context(create_or_update_relation::DeserializeError { body })?;
Ok(create_or_update_relation::Response::Created201(rsp_value))
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update_relation::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(create_or_update_relation::DeserializeError { body })?;
create_or_update_relation::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod create_or_update_relation {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(Relation),
Created201(Relation),
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
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_relation(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
bookmark_id: &str,
relation_name: &str,
) -> std::result::Result<delete_relation::Response, delete_relation::Error> {
let client = &operation_config.client;
let uri_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/bookmarks/{}/relations/{}" , & operation_config . base_path , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , bookmark_id , relation_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_relation::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_relation::BuildRequestError)?;
let rsp = client.execute(req).await.context(delete_relation::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => Ok(delete_relation::Response::Ok200),
StatusCode::NO_CONTENT => Ok(delete_relation::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(delete_relation::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(delete_relation::DeserializeError { body })?;
delete_relation::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod delete_relation {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200,
NoContent204,
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
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 bookmark {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn expand(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
bookmark_id: &str,
parameters: &BookmarkExpandParameters,
) -> std::result::Result<BookmarkExpandResponse, expand::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/bookmarks/{}/expand",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
bookmark_id
);
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(expand::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(expand::BuildRequestError)?;
let rsp = client.execute(req).await.context(expand::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(expand::ResponseBytesError)?;
let rsp_value: BookmarkExpandResponse = serde_json::from_slice(&body).context(expand::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(expand::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(expand::DeserializeError { body })?;
expand::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod expand {
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::CloudError,
},
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 data_connectors {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
) -> std::result::Result<DataConnectorList, list::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/dataConnectors",
&operation_config.base_path, subscription_id, resource_group_name, operational_insights_resource_provider, workspace_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(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: DataConnectorList = 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: CloudError = 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::CloudError,
},
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,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
data_connector_id: &str,
) -> std::result::Result<DataConnector, get::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/dataConnectors/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
data_connector_id
);
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: DataConnector = 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: CloudError = 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::CloudError,
},
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,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
data_connector_id: &str,
data_connector: &DataConnector,
) -> std::result::Result<create_or_update::Response, create_or_update::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/dataConnectors/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
data_connector_id
);
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(data_connector);
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: DataConnector = 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: DataConnector = 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: CloudError = 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(DataConnector),
Created201(DataConnector),
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
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,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
data_connector_id: &str,
) -> std::result::Result<delete::Response, delete::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/dataConnectors/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
data_connector_id
);
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(delete::Response::Ok200),
StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(delete::ResponseBytesError)?;
let rsp_value: CloudError = 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)]
pub enum Response {
Ok200,
NoContent204,
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
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 data_connectors_check_requirements {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn post(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
workspace_name: &str,
operational_insights_resource_provider: &str,
data_connectors_check_requirements: &DataConnectorsCheckRequirements,
) -> std::result::Result<DataConnectorRequirementsState, post::Error> {
let client = &operation_config.client;
let uri_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/dataConnectorsCheckRequirements" , & operation_config . base_path , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_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(post::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(data_connectors_check_requirements);
let req = req_builder.build().context(post::BuildRequestError)?;
let rsp = client.execute(req).await.context(post::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(post::ResponseBytesError)?;
let rsp_value: DataConnectorRequirementsState = serde_json::from_slice(&body).context(post::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(post::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(post::DeserializeError { body })?;
post::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod post {
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::CloudError,
},
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 entities {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
) -> std::result::Result<EntityList, list::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/entities",
&operation_config.base_path, subscription_id, resource_group_name, operational_insights_resource_provider, workspace_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(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: EntityList = 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: CloudError = 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::CloudError,
},
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,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
entity_id: &str,
) -> std::result::Result<Entity, get::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/entities/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
entity_id
);
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: Entity = 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: CloudError = 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::CloudError,
},
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 expand(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
entity_id: &str,
parameters: &EntityExpandParameters,
) -> std::result::Result<EntityExpandResponse, expand::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/entities/{}/expand",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
entity_id
);
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(expand::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(expand::BuildRequestError)?;
let rsp = client.execute(req).await.context(expand::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(expand::ResponseBytesError)?;
let rsp_value: EntityExpandResponse = serde_json::from_slice(&body).context(expand::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(expand::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(expand::DeserializeError { body })?;
expand::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod expand {
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::CloudError,
},
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 entities_get_timeline {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
entity_id: &str,
parameters: &EntityTimelineParameters,
) -> std::result::Result<EntityTimelineResponse, list::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/entities/{}/getTimeline",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
entity_id
);
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(list::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(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: EntityTimelineResponse = 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: CloudError = 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::CloudError,
},
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 entities_relations {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
entity_id: &str,
filter: Option<&str>,
orderby: Option<&str>,
top: Option<i32>,
skip_token: Option<&str>,
) -> std::result::Result<RelationList, list::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/entities/{}/relations",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
entity_id
);
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)]);
if let Some(filter) = filter {
req_builder = req_builder.query(&[("$filter", filter)]);
}
if let Some(orderby) = orderby {
req_builder = req_builder.query(&[("$orderby", orderby)]);
}
if let Some(top) = top {
req_builder = req_builder.query(&[("$top", top)]);
}
if let Some(skip_token) = skip_token {
req_builder = req_builder.query(&[("$skipToken", skip_token)]);
}
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: RelationList = 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: CloudError = 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::CloudError,
},
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 entity_relations {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn get_relation(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
entity_id: &str,
relation_name: &str,
) -> std::result::Result<Relation, get_relation::Error> {
let client = &operation_config.client;
let uri_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/entities/{}/relations/{}" , & operation_config . base_path , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , entity_id , relation_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_relation::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_relation::BuildRequestError)?;
let rsp = client.execute(req).await.context(get_relation::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(get_relation::ResponseBytesError)?;
let rsp_value: Relation = serde_json::from_slice(&body).context(get_relation::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get_relation::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(get_relation::DeserializeError { body })?;
get_relation::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod get_relation {
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::CloudError,
},
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 office_consents {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
) -> std::result::Result<OfficeConsentList, list::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/officeConsents",
&operation_config.base_path, subscription_id, resource_group_name, operational_insights_resource_provider, workspace_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(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: OfficeConsentList = 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: CloudError = 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::CloudError,
},
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,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
consent_id: &str,
) -> std::result::Result<OfficeConsent, get::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/officeConsents/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
consent_id
);
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: OfficeConsent = 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: CloudError = 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::CloudError,
},
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,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
consent_id: &str,
) -> std::result::Result<delete::Response, delete::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/officeConsents/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
consent_id
);
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(delete::Response::Ok200),
StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(delete::ResponseBytesError)?;
let rsp_value: CloudError = 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)]
pub enum Response {
Ok200,
NoContent204,
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
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 product_settings {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn get_all(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
) -> std::result::Result<SettingList, get_all::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/settings",
&operation_config.base_path, subscription_id, resource_group_name, operational_insights_resource_provider, workspace_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_all::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_all::BuildRequestError)?;
let rsp = client.execute(req).await.context(get_all::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(get_all::ResponseBytesError)?;
let rsp_value: SettingList = serde_json::from_slice(&body).context(get_all::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get_all::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(get_all::DeserializeError { body })?;
get_all::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod get_all {
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::CloudError,
},
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,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
settings_name: &str,
) -> std::result::Result<Settings, get::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/settings/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
settings_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: Settings = 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: CloudError = 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::CloudError,
},
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 update(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
settings_name: &str,
settings: &Settings,
) -> std::result::Result<Settings, update::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/settings/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
settings_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(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(settings);
let req = req_builder.build().context(update::BuildRequestError)?;
let rsp = client.execute(req).await.context(update::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?;
let rsp_value: Settings = serde_json::from_slice(&body).context(update::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(update::DeserializeError { body })?;
update::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod update {
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::CloudError,
},
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,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
settings_name: &str,
) -> std::result::Result<delete::Response, delete::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/settings/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
settings_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(delete::Response::Ok200),
StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(delete::ResponseBytesError)?;
let rsp_value: CloudError = 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)]
pub enum Response {
Ok200,
NoContent204,
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
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 cases_aggregations {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn get(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
aggregations_name: &str,
) -> std::result::Result<Aggregations, get::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/aggregations/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
aggregations_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: Aggregations = 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: CloudError = 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::CloudError,
},
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 entity_queries {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
) -> std::result::Result<EntityQueryList, list::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/entityQueries",
&operation_config.base_path, subscription_id, resource_group_name, operational_insights_resource_provider, workspace_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(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: EntityQueryList = 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: CloudError = 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::CloudError,
},
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,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
entity_query_id: &str,
) -> std::result::Result<EntityQuery, get::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/entityQueries/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
entity_query_id
);
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: EntityQuery = 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: CloudError = 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::CloudError,
},
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 incidents {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
filter: Option<&str>,
orderby: Option<&str>,
top: Option<i32>,
skip_token: Option<&str>,
) -> std::result::Result<IncidentList, list::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/incidents",
&operation_config.base_path, subscription_id, resource_group_name, operational_insights_resource_provider, workspace_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(list::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(orderby) = orderby {
req_builder = req_builder.query(&[("$orderby", orderby)]);
}
if let Some(top) = top {
req_builder = req_builder.query(&[("$top", top)]);
}
if let Some(skip_token) = skip_token {
req_builder = req_builder.query(&[("$skipToken", skip_token)]);
}
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: IncidentList = 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: CloudError = 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::CloudError,
},
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,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
incident_id: &str,
) -> std::result::Result<Incident, get::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/incidents/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
incident_id
);
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: Incident = 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: CloudError = 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::CloudError,
},
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,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
incident_id: &str,
incident: &Incident,
) -> std::result::Result<create_or_update::Response, create_or_update::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/incidents/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
incident_id
);
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(incident);
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: Incident = 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: Incident = 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: CloudError = 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(Incident),
Created201(Incident),
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
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,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
incident_id: &str,
) -> std::result::Result<delete::Response, delete::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/incidents/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
incident_id
);
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(delete::Response::Ok200),
StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(delete::ResponseBytesError)?;
let rsp_value: CloudError = 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)]
pub enum Response {
Ok200,
NoContent204,
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
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 list_of_alerts(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
incident_id: &str,
) -> std::result::Result<IncidentAlertList, list_of_alerts::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/incidents/{}/alerts",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
incident_id
);
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(list_of_alerts::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(list_of_alerts::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_of_alerts::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_of_alerts::ResponseBytesError)?;
let rsp_value: IncidentAlertList = serde_json::from_slice(&body).context(list_of_alerts::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_of_alerts::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(list_of_alerts::DeserializeError { body })?;
list_of_alerts::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod list_of_alerts {
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::CloudError,
},
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 list_of_bookmarks(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
incident_id: &str,
) -> std::result::Result<IncidentBookmarkList, list_of_bookmarks::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/incidents/{}/bookmarks",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
incident_id
);
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(list_of_bookmarks::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(list_of_bookmarks::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_of_bookmarks::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_of_bookmarks::ResponseBytesError)?;
let rsp_value: IncidentBookmarkList =
serde_json::from_slice(&body).context(list_of_bookmarks::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_of_bookmarks::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(list_of_bookmarks::DeserializeError { body })?;
list_of_bookmarks::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod list_of_bookmarks {
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::CloudError,
},
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 list_of_entities(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
incident_id: &str,
) -> std::result::Result<IncidentEntitiesResponse, list_of_entities::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/incidents/{}/entities",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
incident_id
);
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(list_of_entities::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(list_of_entities::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_of_entities::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_of_entities::ResponseBytesError)?;
let rsp_value: IncidentEntitiesResponse =
serde_json::from_slice(&body).context(list_of_entities::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_of_entities::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(list_of_entities::DeserializeError { body })?;
list_of_entities::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod list_of_entities {
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::CloudError,
},
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 incident_comments {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list_by_incident(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
incident_id: &str,
filter: Option<&str>,
orderby: Option<&str>,
top: Option<i32>,
skip_token: Option<&str>,
) -> std::result::Result<IncidentCommentList, list_by_incident::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/incidents/{}/comments",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
incident_id
);
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_incident::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(orderby) = orderby {
req_builder = req_builder.query(&[("$orderby", orderby)]);
}
if let Some(top) = top {
req_builder = req_builder.query(&[("$top", top)]);
}
if let Some(skip_token) = skip_token {
req_builder = req_builder.query(&[("$skipToken", skip_token)]);
}
let req = req_builder.build().context(list_by_incident::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_by_incident::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_incident::ResponseBytesError)?;
let rsp_value: IncidentCommentList = serde_json::from_slice(&body).context(list_by_incident::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_incident::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(list_by_incident::DeserializeError { body })?;
list_by_incident::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod list_by_incident {
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::CloudError,
},
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_comment(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
incident_id: &str,
incident_comment_id: &str,
) -> std::result::Result<IncidentComment, get_comment::Error> {
let client = &operation_config.client;
let uri_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/incidents/{}/comments/{}" , & operation_config . base_path , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , incident_id , incident_comment_id) ;
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_comment::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_comment::BuildRequestError)?;
let rsp = client.execute(req).await.context(get_comment::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(get_comment::ResponseBytesError)?;
let rsp_value: IncidentComment = serde_json::from_slice(&body).context(get_comment::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get_comment::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(get_comment::DeserializeError { body })?;
get_comment::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod get_comment {
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::CloudError,
},
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_comment(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
incident_id: &str,
incident_comment_id: &str,
incident_comment: &IncidentComment,
) -> std::result::Result<create_comment::Response, create_comment::Error> {
let client = &operation_config.client;
let uri_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/incidents/{}/comments/{}" , & operation_config . base_path , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , incident_id , incident_comment_id) ;
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_comment::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(incident_comment);
let req = req_builder.build().context(create_comment::BuildRequestError)?;
let rsp = client.execute(req).await.context(create_comment::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(create_comment::ResponseBytesError)?;
let rsp_value: IncidentComment = serde_json::from_slice(&body).context(create_comment::DeserializeError { body })?;
Ok(create_comment::Response::Ok200(rsp_value))
}
StatusCode::CREATED => {
let body: bytes::Bytes = rsp.bytes().await.context(create_comment::ResponseBytesError)?;
let rsp_value: IncidentComment = serde_json::from_slice(&body).context(create_comment::DeserializeError { body })?;
Ok(create_comment::Response::Created201(rsp_value))
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(create_comment::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(create_comment::DeserializeError { body })?;
create_comment::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod create_comment {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(IncidentComment),
Created201(IncidentComment),
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
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_comment(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
incident_id: &str,
incident_comment_id: &str,
) -> std::result::Result<delete_comment::Response, delete_comment::Error> {
let client = &operation_config.client;
let uri_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/incidents/{}/comments/{}" , & operation_config . base_path , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , incident_id , incident_comment_id) ;
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_comment::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_comment::BuildRequestError)?;
let rsp = client.execute(req).await.context(delete_comment::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => Ok(delete_comment::Response::Ok200),
StatusCode::NO_CONTENT => Ok(delete_comment::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(delete_comment::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(delete_comment::DeserializeError { body })?;
delete_comment::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod delete_comment {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200,
NoContent204,
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
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 incident_relations {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
incident_id: &str,
filter: Option<&str>,
orderby: Option<&str>,
top: Option<i32>,
skip_token: Option<&str>,
) -> std::result::Result<RelationList, list::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/incidents/{}/relations",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
incident_id
);
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)]);
if let Some(filter) = filter {
req_builder = req_builder.query(&[("$filter", filter)]);
}
if let Some(orderby) = orderby {
req_builder = req_builder.query(&[("$orderby", orderby)]);
}
if let Some(top) = top {
req_builder = req_builder.query(&[("$top", top)]);
}
if let Some(skip_token) = skip_token {
req_builder = req_builder.query(&[("$skipToken", skip_token)]);
}
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: RelationList = 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: CloudError = 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::CloudError,
},
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_relation(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
incident_id: &str,
relation_name: &str,
) -> std::result::Result<Relation, get_relation::Error> {
let client = &operation_config.client;
let uri_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/incidents/{}/relations/{}" , & operation_config . base_path , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , incident_id , relation_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_relation::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_relation::BuildRequestError)?;
let rsp = client.execute(req).await.context(get_relation::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(get_relation::ResponseBytesError)?;
let rsp_value: Relation = serde_json::from_slice(&body).context(get_relation::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get_relation::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(get_relation::DeserializeError { body })?;
get_relation::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod get_relation {
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::CloudError,
},
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_relation(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
incident_id: &str,
relation_name: &str,
relation: &Relation,
) -> std::result::Result<create_or_update_relation::Response, create_or_update_relation::Error> {
let client = &operation_config.client;
let uri_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/incidents/{}/relations/{}" , & operation_config . base_path , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , incident_id , relation_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_relation::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(relation);
let req = req_builder.build().context(create_or_update_relation::BuildRequestError)?;
let rsp = client.execute(req).await.context(create_or_update_relation::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update_relation::ResponseBytesError)?;
let rsp_value: Relation = serde_json::from_slice(&body).context(create_or_update_relation::DeserializeError { body })?;
Ok(create_or_update_relation::Response::Ok200(rsp_value))
}
StatusCode::CREATED => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update_relation::ResponseBytesError)?;
let rsp_value: Relation = serde_json::from_slice(&body).context(create_or_update_relation::DeserializeError { body })?;
Ok(create_or_update_relation::Response::Created201(rsp_value))
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update_relation::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(create_or_update_relation::DeserializeError { body })?;
create_or_update_relation::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod create_or_update_relation {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(Relation),
Created201(Relation),
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
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_relation(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
incident_id: &str,
relation_name: &str,
) -> std::result::Result<delete_relation::Response, delete_relation::Error> {
let client = &operation_config.client;
let uri_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/incidents/{}/relations/{}" , & operation_config . base_path , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , incident_id , relation_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_relation::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_relation::BuildRequestError)?;
let rsp = client.execute(req).await.context(delete_relation::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => Ok(delete_relation::Response::Ok200),
StatusCode::NO_CONTENT => Ok(delete_relation::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(delete_relation::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(delete_relation::DeserializeError { body })?;
delete_relation::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod delete_relation {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200,
NoContent204,
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
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 watchlists {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
) -> std::result::Result<WatchlistList, list::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/watchlists",
&operation_config.base_path, subscription_id, resource_group_name, operational_insights_resource_provider, workspace_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(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: WatchlistList = 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: CloudError = 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::CloudError,
},
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,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
watchlist_alias: &str,
) -> std::result::Result<Watchlist, get::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/watchlists/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
watchlist_alias
);
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: Watchlist = 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: CloudError = 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::CloudError,
},
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(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
watchlist_alias: &str,
watchlist: &Watchlist,
) -> std::result::Result<create::Response, create::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/watchlists/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
watchlist_alias
);
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::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(watchlist);
let req = req_builder.build().context(create::BuildRequestError)?;
let rsp = client.execute(req).await.context(create::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?;
let rsp_value: Watchlist = serde_json::from_slice(&body).context(create::DeserializeError { body })?;
Ok(create::Response::Ok200(rsp_value))
}
StatusCode::CREATED => {
let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?;
let rsp_value: Watchlist = serde_json::from_slice(&body).context(create::DeserializeError { body })?;
Ok(create::Response::Created201(rsp_value))
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(create::DeserializeError { body })?;
create::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod create {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(Watchlist),
Created201(Watchlist),
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
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,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
watchlist_alias: &str,
) -> std::result::Result<delete::Response, delete::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/watchlists/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
operational_insights_resource_provider,
workspace_name,
watchlist_alias
);
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(delete::Response::Ok200),
StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(delete::ResponseBytesError)?;
let rsp_value: CloudError = 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)]
pub enum Response {
Ok200,
NoContent204,
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
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_threat_intelligence(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
threat_intelligence_indicator_object_to_upsert: &ThreatIntelligenceIndicatorWithoutReadOnlyFields,
) -> std::result::Result<create_threat_intelligence::Response, create_threat_intelligence::Error> {
let client = &operation_config.client;
let uri_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/threatIntelligence/main/createIndicator" , & operation_config . base_path , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_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(create_threat_intelligence::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(threat_intelligence_indicator_object_to_upsert);
let req = req_builder.build().context(create_threat_intelligence::BuildRequestError)?;
let rsp = client.execute(req).await.context(create_threat_intelligence::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(create_threat_intelligence::ResponseBytesError)?;
let rsp_value: ThreatIntelligenceResource =
serde_json::from_slice(&body).context(create_threat_intelligence::DeserializeError { body })?;
Ok(create_threat_intelligence::Response::Ok200(rsp_value))
}
StatusCode::CREATED => {
let body: bytes::Bytes = rsp.bytes().await.context(create_threat_intelligence::ResponseBytesError)?;
let rsp_value: ThreatIntelligenceResource =
serde_json::from_slice(&body).context(create_threat_intelligence::DeserializeError { body })?;
Ok(create_threat_intelligence::Response::Created201(rsp_value))
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(create_threat_intelligence::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(create_threat_intelligence::DeserializeError { body })?;
create_threat_intelligence::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod create_threat_intelligence {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(ThreatIntelligenceResource),
Created201(ThreatIntelligenceResource),
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
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 threat_intelligence_indicators {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
filter: Option<&str>,
top: Option<i32>,
skip_token: Option<&str>,
orderby: Option<&str>,
) -> std::result::Result<ThreatIntelligenceResourceList, list::Error> {
let client = &operation_config.client;
let uri_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/threatIntelligence/main/indicators" , & operation_config . base_path , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_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(list::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(top) = top {
req_builder = req_builder.query(&[("$top", top)]);
}
if let Some(skip_token) = skip_token {
req_builder = req_builder.query(&[("$skipToken", skip_token)]);
}
if let Some(orderby) = orderby {
req_builder = req_builder.query(&[("$orderby", orderby)]);
}
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: ThreatIntelligenceResourceList = 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: CloudError = 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::CloudError,
},
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 threat_intelligence_indicator {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn get(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
name: &str,
) -> std::result::Result<ThreatIntelligenceResource, get::Error> {
let client = &operation_config.client;
let uri_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/threatIntelligence/main/indicators/{}" , & operation_config . base_path , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , 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: ThreatIntelligenceResource = 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: CloudError = 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::CloudError,
},
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,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
name: &str,
) -> std::result::Result<delete::Response, delete::Error> {
let client = &operation_config.client;
let uri_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/threatIntelligence/main/indicators/{}" , & operation_config . base_path , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , 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(delete::Response::Ok200),
StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(delete::ResponseBytesError)?;
let rsp_value: CloudError = 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)]
pub enum Response {
Ok200,
NoContent204,
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
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 append_tags(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
name: &str,
threat_intelligence_append_tags_request_body: &ThreatIntelligenceAppendTagsRequestBody,
) -> std::result::Result<(), append_tags::Error> {
let client = &operation_config.client;
let uri_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/threatIntelligence/main/indicators/{}/appendTags" , & operation_config . base_path , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , 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(append_tags::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(threat_intelligence_append_tags_request_body);
let req = req_builder.build().context(append_tags::BuildRequestError)?;
let rsp = client.execute(req).await.context(append_tags::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => Ok(()),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(append_tags::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(append_tags::DeserializeError { body })?;
append_tags::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod append_tags {
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::CloudError,
},
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 replace_tags(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
name: &str,
threat_intelligence_replace_tags_model: &ThreatIntelligenceIndicatorWithoutReadOnlyFields,
) -> std::result::Result<ThreatIntelligenceResource, replace_tags::Error> {
let client = &operation_config.client;
let uri_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/threatIntelligence/main/indicators/{}/replaceTags" , & operation_config . base_path , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , 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(replace_tags::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(threat_intelligence_replace_tags_model);
let req = req_builder.build().context(replace_tags::BuildRequestError)?;
let rsp = client.execute(req).await.context(replace_tags::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(replace_tags::ResponseBytesError)?;
let rsp_value: ThreatIntelligenceResource =
serde_json::from_slice(&body).context(replace_tags::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(replace_tags::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(replace_tags::DeserializeError { body })?;
replace_tags::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod replace_tags {
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::CloudError,
},
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 threat_intelligence_indicator_upsert {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn create(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
name: &str,
threat_intelligence_indicator_object_to_upsert: &ThreatIntelligenceIndicatorWithoutReadOnlyFields,
) -> std::result::Result<create::Response, create::Error> {
let client = &operation_config.client;
let uri_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/threatIntelligence/main/indicators/{}" , & operation_config . base_path , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , 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::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(threat_intelligence_indicator_object_to_upsert);
let req = req_builder.build().context(create::BuildRequestError)?;
let rsp = client.execute(req).await.context(create::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?;
let rsp_value: ThreatIntelligenceResource = serde_json::from_slice(&body).context(create::DeserializeError { body })?;
Ok(create::Response::Ok200(rsp_value))
}
StatusCode::CREATED => {
let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?;
let rsp_value: ThreatIntelligenceResource = serde_json::from_slice(&body).context(create::DeserializeError { body })?;
Ok(create::Response::Created201(rsp_value))
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(create::DeserializeError { body })?;
create::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod create {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(ThreatIntelligenceResource),
Created201(ThreatIntelligenceResource),
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
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 threat_intelligence_indicators_list {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn query(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
threat_intelligence_arm_stix_query: &ThreatIntelligenceArmStixQuery,
) -> std::result::Result<ThreatIntelligenceResourceList, query::Error> {
let client = &operation_config.client;
let uri_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/threatIntelligence/main/queryIndicators" , & operation_config . base_path , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_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(query::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(threat_intelligence_arm_stix_query);
let req = req_builder.build().context(query::BuildRequestError)?;
let rsp = client.execute(req).await.context(query::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(query::ResponseBytesError)?;
let rsp_value: ThreatIntelligenceResourceList = serde_json::from_slice(&body).context(query::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(query::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(query::DeserializeError { body })?;
query::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod query {
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::CloudError,
},
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 threat_intelligence_indicator_metrics {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn get(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
operational_insights_resource_provider: &str,
workspace_name: &str,
cti_entity_kind: Option<&str>,
) -> std::result::Result<ThreatIntelligenceMetricResourceList, get::Error> {
let client = &operation_config.client;
let uri_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/threatIntelligence/main/metrics" , & operation_config . base_path , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_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)]);
if let Some(cti_entity_kind) = cti_entity_kind {
req_builder = req_builder.query(&[("ctiEntityKind", cti_entity_kind)]);
}
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: ThreatIntelligenceMetricResourceList =
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: CloudError = 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::CloudError,
},
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,
},
}
}
}
|
#[no_mangle]
pub extern "C" fn banana() -> i32 {
return 42;
}
|
use cpal;
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use std::sync::{Arc, Mutex, MutexGuard};
use circular_queue::CircularQueue;
use friday_error;
use friday_error::{frierr, propagate, FridayError};
use friday_logging;
use crate::recorder::Recorder;
use crate::RecordingConfig;
use std::thread;
use std::time;
fn write_to_buffer<T>(input: &[T], buffer: &Arc<Mutex<CircularQueue<i16>>>,
loudness_contant: i16)
where T: cpal::Sample {
fn insert<T>(samples: &[T], q: &mut MutexGuard<CircularQueue<i16>>, loudness: i16)
where T: cpal::Sample {
for sample in samples.iter() {
let mut i16sample = sample.to_i16();
// To avoid overflowing issues
if i16sample == -32768 {
i16sample = -32767;
}
// To avoid overflowing issues
match i16sample.checked_mul(loudness) {
Some(v) => q.push(v),
None => q.push(32767 * i16sample.signum())
};
}
}
match buffer.lock() {
Ok(mut guard) => insert(input, &mut guard, loudness_contant),
Err(err) => {
friday_logging::fatal!("(audioio) - Failed to aquire lock for writing audio data\
- Reason: {}", err);
// To not spam the living #!#! out of the audio device mutex if we get a poison
// error
thread::sleep(time::Duration::from_secs(1));
}
}
}
fn get_recording_device(conf: &RecordingConfig) -> Result<cpal::Device, FridayError> {
//for host in cpal::available_hosts().iter() {
//friday_logging::info!("Found Host {}", host.name());
//}
//for device in cpal::default_host().input_devices().unwrap() {
//friday_logging::info!("Found {}", device.name().unwrap());
//}
//for device in cpal::default_host().devices().unwrap() {
//friday_logging::info!("Found device {}", device.name().unwrap());
//}
// TODO: Make a smart choice of device here
// For some platforms the default device is not a good choice
// E.g raspberry PI
// The current work-around is that I manually set the default device on the pi
// to make this code work - but would be better if this code could
// recognize what device has recording capabilities and then use it
match cpal::default_host().input_devices() {
Err(err) => frierr!("Failed to read input devices, Reason: {:?}", err),
Ok(mut device_it) =>
match device_it.find(|device| match device.name() {
Err(err) => {
friday_logging::error!("Device name error {:?} ... Ignoring device", err);
false
},
Ok(name) => name == conf.device
}) {
Some(device) => {
friday_logging::info!("Found recording device {}", conf.device);
Ok(device)
}
None => frierr!("Could not find any device matching {}", conf.device)
}
}
}
pub struct CPALIStream {
config: RecordingConfig,
_stream: cpal::Stream,
buffer: Arc<Mutex<CircularQueue<i16>>>,
}
// If things break, this is possibly a culprit
// It should be threadsafe though since we're using sync primitives for our audio buffer
unsafe impl Send for CPALIStream { }
impl CPALIStream {
pub fn record(conf: &RecordingConfig) -> Result<Arc<Mutex<CPALIStream>>, FridayError> {
return get_recording_device(conf)
.map_or_else(
propagate!("Could not setup any recording device..."),
|device| {
friday_logging::info!("Using device {}", device.name().unwrap());
let config = cpal::StreamConfig {
channels: 1,
sample_rate: cpal::SampleRate{ 0: conf.sample_rate },
buffer_size: cpal::BufferSize::Default,
};
let write_buffer = Arc::new(
Mutex::new(
CircularQueue::with_capacity(conf.model_frame_size)));
let read_buffer = write_buffer.clone();
let loudness = conf.loudness.clone();
return device.build_input_stream(
&config.into(),
move |data, _: &_| write_to_buffer::<i16>(data, &write_buffer, loudness),
|err| {
friday_logging::fatal!("Recording error - {}", err);
// To not spam the living #!#! out of the audio device if an error
// occurs - e.g someone janks out the audio device from the
// computer
thread::sleep(time::Duration::from_secs(10));
}
).map_or_else(
|err| frierr!("Failed to create input stream: {}", err),
|stream| {
stream.play()
.map_or_else(
|err| frierr!("Recording Failed {}", err),
|_| {
Ok(Arc::new(Mutex::new(CPALIStream{
config: conf.clone(),
_stream: stream,
buffer: read_buffer,
})))
})
});
});
}
}
impl Recorder for CPALIStream {
fn read(&self) -> Option<Vec<i16>> {
match self.buffer.lock() {
Ok(guard) => {
let mut data: Vec<i16> = Vec::with_capacity(self.config.model_frame_size);
data.extend(guard.asc_iter());
data.resize(self.config.model_frame_size, 0);
return Some(data);
}
Err(err) => {
friday_logging::fatal!("Failed to aquire lock for reading audio data -
Reason: {}", err);
// To not spam the living #!#! out of the audio device mutex if we get a poison
// error
thread::sleep(time::Duration::from_secs(10));
None
}
}
}
fn sample_rate(&self) -> u32 {
self.config.sample_rate
}
fn clear(&self) -> Result<(), FridayError> {
match self.buffer.lock() {
Err(err) => frierr!("Failed to aquire audio buffer lock, Reason: {:?}", err),
Ok(mut buffer) => {
buffer.clear();
Ok(())
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs::File;
use std::path::Path;
use wav;
#[test]
fn cpal_some_printing() {
let r = RecordingConfig {
sample_rate: 8000,
model_frame_size: 16000,
loudness: 1,
device: "default".to_owned()
};
let istream = CPALIStream::record(&r).unwrap();
std::thread::sleep(std::time::Duration::from_secs(1));
match istream.clone().lock().unwrap().read() {
Some(v) => friday_logging::info!("{:?}", v[0..1000].iter()),
_ => friday_logging::info!("Failed to read")
}
std::thread::sleep(std::time::Duration::from_secs(2));
match istream.clone().lock().unwrap().read() {
Some(v) => friday_logging::info!("{:?}", v[0..1000].iter()),
_ => friday_logging::info!("Failed to read")
}
}
#[test]
fn normal_workload() {
let r = RecordingConfig {
sample_rate: 8000,
model_frame_size: 16000,
loudness: 1,
device: "default".to_owned()
};
let istream = CPALIStream::record(&r).unwrap();
for _ in 0..50 {
std::thread::sleep(std::time::Duration::from_millis(250));
match istream.lock().unwrap().read() {
Some(_) => friday_logging::info!("Read Ok!"),
_ => friday_logging::info!("Failed to read")
}
}
}
fn energy(audio: &Vec<i16>) -> f64 {
let mut e = 0.0;
for sample in audio.iter() {
let f64sample = (sample.clone() as f64) / 32768.0;
e += f64::sqrt(f64sample * f64sample);
}
return e / 16000.0;
}
#[test]
fn record_audio_files() {
let r = RecordingConfig {
sample_rate: 8000,
model_frame_size: 16000,
loudness: 3,
device: "sysdefault:CARD=MICCU100BK".to_owned()
};
let istream = CPALIStream::record(&r).unwrap();
for index in 0..8 {
std::thread::sleep(std::time::Duration::from_millis(2000));
match istream.lock().unwrap().read() {
Some(data) => {
friday_logging::info!("Read Ok!, energy {}", energy(&data));
let out = File::create(
Path::new(&format!("test-{}.wav", index)));
match out {
Ok(mut fw) => {
let header = wav::Header::new(1, 1, r.sample_rate, 16);
match wav::write(header, wav::BitDepth::Sixteen(data), &mut fw) {
Ok(_) => friday_logging::info!("Successfully wrote to wav file!"),
Err(e) => friday_logging::info!("Failed to write to wav file - Reason: {}", e)
}
},
Err(e) => friday_logging::info!("Failed to create out file - Reason: {}", e)
}
},
_ => friday_logging::info!("Failed to read")
}
}
}
}
|
use crate::features::syntax::StatementFeature;
use crate::parse::visitor::tests::assert_stmt_feature;
#[test]
fn continue_no_label() {
assert_stmt_feature(
"with ({ a: 123 }) {
a = 0;
}",
StatementFeature::WithStatement,
);
}
|
#[doc = "Register `MACDR` reader"]
pub type R = crate::R<MACDR_SPEC>;
#[doc = "Field `RPESTS` reader - MAC MII Receive Protocol Engine Status When this bit is set, it indicates that the MAC MII receive protocol engine is actively receiving data, and it is not in the Idle state."]
pub type RPESTS_R = crate::BitReader;
#[doc = "Field `RFCFCSTS` reader - MAC Receive Packet Controller FIFO Status When this bit is set, this field indicates the active state of the small FIFO Read and Write controllers of the MAC Receive Packet Controller module."]
pub type RFCFCSTS_R = crate::FieldReader;
#[doc = "Field `TPESTS` reader - MAC MII Transmit Protocol Engine Status When this bit is set, it indicates that the MAC MII transmit protocol engine is actively transmitting data, and it is not in the Idle state."]
pub type TPESTS_R = crate::BitReader;
#[doc = "Field `TFCSTS` reader - MAC Transmit Packet Controller Status This field indicates the state of the MAC Transmit Packet Controller module: Status of the previous packet IPG or backoff period to be over"]
pub type TFCSTS_R = crate::FieldReader;
impl R {
#[doc = "Bit 0 - MAC MII Receive Protocol Engine Status When this bit is set, it indicates that the MAC MII receive protocol engine is actively receiving data, and it is not in the Idle state."]
#[inline(always)]
pub fn rpests(&self) -> RPESTS_R {
RPESTS_R::new((self.bits & 1) != 0)
}
#[doc = "Bits 1:2 - MAC Receive Packet Controller FIFO Status When this bit is set, this field indicates the active state of the small FIFO Read and Write controllers of the MAC Receive Packet Controller module."]
#[inline(always)]
pub fn rfcfcsts(&self) -> RFCFCSTS_R {
RFCFCSTS_R::new(((self.bits >> 1) & 3) as u8)
}
#[doc = "Bit 16 - MAC MII Transmit Protocol Engine Status When this bit is set, it indicates that the MAC MII transmit protocol engine is actively transmitting data, and it is not in the Idle state."]
#[inline(always)]
pub fn tpests(&self) -> TPESTS_R {
TPESTS_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bits 17:18 - MAC Transmit Packet Controller Status This field indicates the state of the MAC Transmit Packet Controller module: Status of the previous packet IPG or backoff period to be over"]
#[inline(always)]
pub fn tfcsts(&self) -> TFCSTS_R {
TFCSTS_R::new(((self.bits >> 17) & 3) as u8)
}
}
#[doc = "Debug register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`macdr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct MACDR_SPEC;
impl crate::RegisterSpec for MACDR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`macdr::R`](R) reader structure"]
impl crate::Readable for MACDR_SPEC {}
#[doc = "`reset()` method sets MACDR to value 0"]
impl crate::Resettable for MACDR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use objc::Encode;
use objc::Encoding;
use crate::foundation::NSPoint;
use crate::foundation::NSSize;
// https://developer.apple.com/documentation/foundation/nsrect
#[derive(Clone, Copy, Debug, Default)]
#[repr(C)]
pub struct NSRect {
pub origin: NSPoint,
pub size: NSSize,
}
impl NSRect {
pub fn new(origin: NSPoint, size: NSSize) -> Self {
Self { origin, size }
}
}
unsafe impl Encode for NSRect {
fn encode() -> Encoding {
let encoding = format!(
"{{CGRect={}{}}}",
NSPoint::encode().as_str(),
NSSize::encode().as_str(),
);
unsafe { Encoding::from_str(&encoding) }
}
}
|
use schema::pages;
use std::time::SystemTime;
use stq_api::pages::*;
use stq_types::{PageId, PageSlug};
#[derive(From, Into, Queryable, Insertable, Identifiable)]
#[table_name = "pages"]
pub struct DbPage {
pub id: PageId,
pub slug: PageSlug,
pub html: String,
pub css: String,
pub created_at: SystemTime,
pub updated_at: SystemTime,
}
impl From<DbPage> for Page {
fn from(v: DbPage) -> Self {
Self {
id: v.id,
slug: v.slug,
html: v.html,
css: v.css,
created_at: v.created_at,
updated_at: v.updated_at,
}
}
}
#[derive(Insertable)]
#[table_name = "pages"]
pub struct DbNewPage {
pub id: PageId,
pub slug: PageSlug,
pub html: String,
pub css: String,
}
impl From<NewPage> for DbNewPage {
fn from(v: NewPage) -> Self {
Self {
id: v.id,
slug: v.slug.0.to_lowercase().into(),
html: v.html,
css: v.css,
}
}
}
|
#[doc = "Register `PUCRG` reader"]
pub type R = crate::R<PUCRG_SPEC>;
#[doc = "Register `PUCRG` writer"]
pub type W = crate::W<PUCRG_SPEC>;
#[doc = "Field `PU0` reader - Port G pull-up bit y (y=0..15)"]
pub type PU0_R = crate::BitReader;
#[doc = "Field `PU0` writer - Port G pull-up bit y (y=0..15)"]
pub type PU0_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PU1` reader - Port G pull-up bit y (y=0..15)"]
pub type PU1_R = crate::BitReader;
#[doc = "Field `PU1` writer - Port G pull-up bit y (y=0..15)"]
pub type PU1_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PU2` reader - Port G pull-up bit y (y=0..15)"]
pub type PU2_R = crate::BitReader;
#[doc = "Field `PU2` writer - Port G pull-up bit y (y=0..15)"]
pub type PU2_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PU3` reader - Port G pull-up bit y (y=0..15)"]
pub type PU3_R = crate::BitReader;
#[doc = "Field `PU3` writer - Port G pull-up bit y (y=0..15)"]
pub type PU3_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PU4` reader - Port G pull-up bit y (y=0..15)"]
pub type PU4_R = crate::BitReader;
#[doc = "Field `PU4` writer - Port G pull-up bit y (y=0..15)"]
pub type PU4_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PU5` reader - Port G pull-up bit y (y=0..15)"]
pub type PU5_R = crate::BitReader;
#[doc = "Field `PU5` writer - Port G pull-up bit y (y=0..15)"]
pub type PU5_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PU6` reader - Port G pull-up bit y (y=0..15)"]
pub type PU6_R = crate::BitReader;
#[doc = "Field `PU6` writer - Port G pull-up bit y (y=0..15)"]
pub type PU6_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PU7` reader - Port G pull-up bit y (y=0..15)"]
pub type PU7_R = crate::BitReader;
#[doc = "Field `PU7` writer - Port G pull-up bit y (y=0..15)"]
pub type PU7_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PU8` reader - Port G pull-up bit y (y=0..15)"]
pub type PU8_R = crate::BitReader;
#[doc = "Field `PU8` writer - Port G pull-up bit y (y=0..15)"]
pub type PU8_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PU9` reader - Port G pull-up bit y (y=0..15)"]
pub type PU9_R = crate::BitReader;
#[doc = "Field `PU9` writer - Port G pull-up bit y (y=0..15)"]
pub type PU9_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PU10` reader - Port G pull-up bit y (y=0..15)"]
pub type PU10_R = crate::BitReader;
#[doc = "Field `PU10` writer - Port G pull-up bit y (y=0..15)"]
pub type PU10_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - Port G pull-up bit y (y=0..15)"]
#[inline(always)]
pub fn pu0(&self) -> PU0_R {
PU0_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - Port G pull-up bit y (y=0..15)"]
#[inline(always)]
pub fn pu1(&self) -> PU1_R {
PU1_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - Port G pull-up bit y (y=0..15)"]
#[inline(always)]
pub fn pu2(&self) -> PU2_R {
PU2_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - Port G pull-up bit y (y=0..15)"]
#[inline(always)]
pub fn pu3(&self) -> PU3_R {
PU3_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - Port G pull-up bit y (y=0..15)"]
#[inline(always)]
pub fn pu4(&self) -> PU4_R {
PU4_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - Port G pull-up bit y (y=0..15)"]
#[inline(always)]
pub fn pu5(&self) -> PU5_R {
PU5_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 6 - Port G pull-up bit y (y=0..15)"]
#[inline(always)]
pub fn pu6(&self) -> PU6_R {
PU6_R::new(((self.bits >> 6) & 1) != 0)
}
#[doc = "Bit 7 - Port G pull-up bit y (y=0..15)"]
#[inline(always)]
pub fn pu7(&self) -> PU7_R {
PU7_R::new(((self.bits >> 7) & 1) != 0)
}
#[doc = "Bit 8 - Port G pull-up bit y (y=0..15)"]
#[inline(always)]
pub fn pu8(&self) -> PU8_R {
PU8_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - Port G pull-up bit y (y=0..15)"]
#[inline(always)]
pub fn pu9(&self) -> PU9_R {
PU9_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - Port G pull-up bit y (y=0..15)"]
#[inline(always)]
pub fn pu10(&self) -> PU10_R {
PU10_R::new(((self.bits >> 10) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - Port G pull-up bit y (y=0..15)"]
#[inline(always)]
#[must_use]
pub fn pu0(&mut self) -> PU0_W<PUCRG_SPEC, 0> {
PU0_W::new(self)
}
#[doc = "Bit 1 - Port G pull-up bit y (y=0..15)"]
#[inline(always)]
#[must_use]
pub fn pu1(&mut self) -> PU1_W<PUCRG_SPEC, 1> {
PU1_W::new(self)
}
#[doc = "Bit 2 - Port G pull-up bit y (y=0..15)"]
#[inline(always)]
#[must_use]
pub fn pu2(&mut self) -> PU2_W<PUCRG_SPEC, 2> {
PU2_W::new(self)
}
#[doc = "Bit 3 - Port G pull-up bit y (y=0..15)"]
#[inline(always)]
#[must_use]
pub fn pu3(&mut self) -> PU3_W<PUCRG_SPEC, 3> {
PU3_W::new(self)
}
#[doc = "Bit 4 - Port G pull-up bit y (y=0..15)"]
#[inline(always)]
#[must_use]
pub fn pu4(&mut self) -> PU4_W<PUCRG_SPEC, 4> {
PU4_W::new(self)
}
#[doc = "Bit 5 - Port G pull-up bit y (y=0..15)"]
#[inline(always)]
#[must_use]
pub fn pu5(&mut self) -> PU5_W<PUCRG_SPEC, 5> {
PU5_W::new(self)
}
#[doc = "Bit 6 - Port G pull-up bit y (y=0..15)"]
#[inline(always)]
#[must_use]
pub fn pu6(&mut self) -> PU6_W<PUCRG_SPEC, 6> {
PU6_W::new(self)
}
#[doc = "Bit 7 - Port G pull-up bit y (y=0..15)"]
#[inline(always)]
#[must_use]
pub fn pu7(&mut self) -> PU7_W<PUCRG_SPEC, 7> {
PU7_W::new(self)
}
#[doc = "Bit 8 - Port G pull-up bit y (y=0..15)"]
#[inline(always)]
#[must_use]
pub fn pu8(&mut self) -> PU8_W<PUCRG_SPEC, 8> {
PU8_W::new(self)
}
#[doc = "Bit 9 - Port G pull-up bit y (y=0..15)"]
#[inline(always)]
#[must_use]
pub fn pu9(&mut self) -> PU9_W<PUCRG_SPEC, 9> {
PU9_W::new(self)
}
#[doc = "Bit 10 - Port G pull-up bit y (y=0..15)"]
#[inline(always)]
#[must_use]
pub fn pu10(&mut self) -> PU10_W<PUCRG_SPEC, 10> {
PU10_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 = "Power Port G pull-up control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`pucrg::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 [`pucrg::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct PUCRG_SPEC;
impl crate::RegisterSpec for PUCRG_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`pucrg::R`](R) reader structure"]
impl crate::Readable for PUCRG_SPEC {}
#[doc = "`write(|w| ..)` method takes [`pucrg::W`](W) writer structure"]
impl crate::Writable for PUCRG_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets PUCRG to value 0"]
impl crate::Resettable for PUCRG_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use crate::*;
pub fn init_method(globals: &mut Globals) -> Value {
let proc_id = globals.get_ident_id("Method");
let class = ClassRef::from(proc_id, globals.builtins.object);
globals.add_builtin_instance_method(class, "call", method_call);
Value::class(globals, class)
}
pub fn method_call(vm: &mut VM, self_val: Value, args: &Args) -> VMResult {
let method = match self_val.as_method() {
Some(method) => method,
None => return Err(vm.error_unimplemented("Expected Method object.")),
};
let res = vm.eval_send(method.method, method.receiver, args)?;
Ok(res)
}
|
use nu_engine::CallExt;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
ast::Call, Category, Example, IntoPipelineData, PipelineData, ShellError, Signature, Span,
Spanned, SyntaxShape, Value,
};
#[derive(Clone)]
pub struct SeqChar;
impl Command for SeqChar {
fn name(&self) -> &str {
"seq char"
}
fn usage(&self) -> &str {
"Print sequence of chars"
}
fn signature(&self) -> Signature {
Signature::build("seq char")
.rest("rest", SyntaxShape::String, "sequence chars")
.named(
"separator",
SyntaxShape::String,
"separator character (defaults to \\n)",
Some('s'),
)
.named(
"terminator",
SyntaxShape::String,
"terminator character (defaults to \\n)",
Some('t'),
)
.category(Category::Generators)
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "sequence a to e with newline separator",
example: "seq char a e",
result: Some(Value::List {
vals: vec![
Value::test_string('a'),
Value::test_string('b'),
Value::test_string('c'),
Value::test_string('d'),
Value::test_string('e'),
],
span: Span::test_data(),
}),
},
Example {
description: "sequence a to e with pipe separator separator",
example: "seq char -s '|' a e",
result: Some(Value::test_string("a|b|c|d|e")),
},
]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
seq_char(engine_state, stack, call)
}
}
fn is_single_character(ch: &str) -> bool {
ch.is_ascii() && ch.len() == 1 && ch.chars().all(char::is_alphabetic)
}
fn seq_char(
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
) -> Result<PipelineData, ShellError> {
// input check.
let separator: Option<Spanned<String>> = call.get_flag(engine_state, stack, "separator")?;
let terminator: Option<Spanned<String>> = call.get_flag(engine_state, stack, "terminator")?;
let rest_inputs: Vec<Spanned<String>> = call.rest(engine_state, stack, 0)?;
let (start_ch, end_ch) = if rest_inputs.len() != 2
|| !is_single_character(&rest_inputs[0].item)
|| !is_single_character(&rest_inputs[1].item)
{
return Err(ShellError::GenericError(
"seq char required two character parameters".into(),
"needs parameter".into(),
Some(call.head),
None,
Vec::new(),
));
} else {
// unwrap here is ok, because we just check the length of `rest_inputs`.
(
rest_inputs[0]
.item
.chars()
.next()
.expect("seq char input must contains 2 inputs"),
rest_inputs[1]
.item
.chars()
.next()
.expect("seq char input must contains 2 inputs"),
)
};
let sep: String = match separator {
Some(s) => {
if s.item == r"\t" {
'\t'.to_string()
} else if s.item == r"\n" {
'\n'.to_string()
} else if s.item == r"\r" {
'\r'.to_string()
} else {
let vec_s: Vec<char> = s.item.chars().collect();
if vec_s.is_empty() {
return Err(ShellError::GenericError(
"Expected a single separator char from --separator".into(),
"requires a single character string input".into(),
Some(s.span),
None,
Vec::new(),
));
};
vec_s.iter().collect()
}
}
_ => '\n'.to_string(),
};
let terminator: String = match terminator {
Some(t) => {
if t.item == r"\t" {
'\t'.to_string()
} else if t.item == r"\n" {
'\n'.to_string()
} else if t.item == r"\r" {
'\r'.to_string()
} else {
let vec_t: Vec<char> = t.item.chars().collect();
if vec_t.is_empty() {
return Err(ShellError::GenericError(
"Expected a single terminator char from --terminator".into(),
"requires a single character string input".into(),
Some(t.span),
None,
Vec::new(),
));
};
vec_t.iter().collect()
}
}
_ => '\n'.to_string(),
};
let span = call.head;
run_seq_char(start_ch, end_ch, sep, terminator, span)
}
fn run_seq_char(
start_ch: char,
end_ch: char,
sep: String,
terminator: String,
span: Span,
) -> Result<PipelineData, ShellError> {
let mut result_vec = vec![];
for current_ch in start_ch as u8..end_ch as u8 + 1 {
result_vec.push((current_ch as char).to_string())
}
let return_list = (sep == "\n" || sep == "\r") && (terminator == "\n" || terminator == "\r");
if return_list {
let result = result_vec
.into_iter()
.map(|x| Value::String { val: x, span })
.collect::<Vec<Value>>();
Ok(Value::List { vals: result, span }.into_pipeline_data())
} else {
let mut result = result_vec.join(&sep);
result.push_str(&terminator);
// doesn't output a list, if separator is '\n', it's better to eliminate them.
// and it matches `seq` behavior.
let result = result.lines().collect();
Ok(Value::String { val: result, span }.into_pipeline_data())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(SeqChar {})
}
}
|
use std::ops::Range;
use super::{
binding::{self, Buffer, BufferGroup, TextureBinding},
frame::Framebuffer,
grid::Grid,
model::{Material, Mesh, Model},
};
pub trait Vertex {
fn desc<'a>() -> wgpu::VertexBufferDescriptor<'a>;
}
pub trait DrawModel<'a, 'b>
where
'b: 'a,
{
fn draw_mesh(
&mut self,
mesh: &'b Mesh,
material: &'b Material,
uniforms: &'b binding::BufferGroup,
light: &'b binding::BufferGroup,
);
fn draw_mesh_instanced(
&mut self,
mesh: &'b Mesh,
material: &'b Material,
instances: Range<u32>,
uniforms: &'b binding::BufferGroup,
light: &'b binding::BufferGroup,
);
fn draw_model(
&mut self,
model: &'b Model,
uniforms: &'b binding::BufferGroup,
light: &'b binding::BufferGroup,
);
fn draw_model_instanced(
&mut self,
model: &'b Model,
instances: Range<u32>,
uniforms: &'b binding::BufferGroup,
light: &'b binding::BufferGroup,
);
fn draw_model_with_material(
&mut self,
model: &'b Model,
material: &'b Material,
uniforms: &'b binding::BufferGroup,
light: &'b binding::BufferGroup,
);
fn draw_model_instanced_with_material(
&mut self,
model: &'b Model,
material: &'b Material,
instances: Range<u32>,
uniforms: &'b binding::BufferGroup,
light: &'b binding::BufferGroup,
);
fn bind_material(&mut self, index: u32, material: &'b Material);
}
pub trait DrawLight<'a, 'b>
where
'b: 'a,
{
fn draw_light_mesh(
&mut self,
mesh: &'b Mesh,
uniforms: &'b binding::BufferGroup,
light: &'b binding::BufferGroup,
);
fn draw_light_mesh_instanced(
&mut self,
mesh: &'b Mesh,
instances: Range<u32>,
uniforms: &'b binding::BufferGroup,
light: &'b binding::BufferGroup,
);
fn draw_light_model(
&mut self,
model: &'b Model,
uniforms: &'b binding::BufferGroup,
light: &'b binding::BufferGroup,
);
fn draw_light_model_instanced(
&mut self,
model: &'b Model,
instances: Range<u32>,
uniforms: &'b binding::BufferGroup,
light: &'b binding::BufferGroup,
);
}
pub trait Binding<'a, 'b>
where
'b: 'a,
{
fn bind_textures(&mut self, index: u32, textures: &'b TextureBinding);
fn bind_group(&mut self, index: u32, group: &'b BufferGroup);
fn bind_buffer(&mut self, slot: u32, buffer: &'b Buffer);
fn bind_vertex_buffer(&mut self, slot: u32, buffer: &'b Buffer);
fn bind_index_buffer(&mut self, buffer: &'b Buffer);
}
pub trait DrawFramebuffer<'a, 'b>
where
'b: 'a,
{
fn draw_framebuffer(&mut self, frame: &'b Framebuffer, uniforms: &'b binding::BufferGroup);
}
pub trait DrawGrid<'a, 'b>
where
'b: 'a,
{
fn draw_grid(&mut self, grid: &'b Grid, uniforms: &'b binding::BufferGroup);
}
|
fn main() {
let x = 5i32;
let y = { if x == 4i32 { 3i32} else { 6i32 }};
println!("{}" ,y);
} |
use crate::core::compiler::{Compilation, CompileKind, Doctest, Metadata, Unit, UnitOutput};
use crate::core::shell::Verbosity;
use crate::core::{TargetKind, Workspace};
use crate::ops;
use crate::util::errors::CargoResult;
use crate::util::{add_path_args, CargoTestError, Config, Test};
use cargo_util::{ProcessBuilder, ProcessError};
use std::ffi::OsString;
use std::path::{Path, PathBuf};
pub struct TestOptions {
pub compile_opts: ops::CompileOptions,
pub no_run: bool,
pub no_fail_fast: bool,
}
pub fn run_tests(
ws: &Workspace<'_>,
options: &TestOptions,
test_args: &[&str],
) -> CargoResult<Option<CargoTestError>> {
let compilation = compile_tests(ws, options)?;
if options.no_run {
if !options.compile_opts.build_config.emit_json() {
display_no_run_information(ws, test_args, &compilation, "unittests")?;
}
return Ok(None);
}
let (test, mut errors) = run_unit_tests(ws.config(), options, test_args, &compilation)?;
// If we have an error and want to fail fast, then return.
if !errors.is_empty() && !options.no_fail_fast {
return Ok(Some(CargoTestError::new(test, errors)));
}
let (doctest, docerrors) = run_doc_tests(ws, options, test_args, &compilation)?;
let test = if docerrors.is_empty() { test } else { doctest };
errors.extend(docerrors);
if errors.is_empty() {
Ok(None)
} else {
Ok(Some(CargoTestError::new(test, errors)))
}
}
pub fn run_benches(
ws: &Workspace<'_>,
options: &TestOptions,
args: &[&str],
) -> CargoResult<Option<CargoTestError>> {
let compilation = compile_tests(ws, options)?;
if options.no_run {
if !options.compile_opts.build_config.emit_json() {
display_no_run_information(ws, args, &compilation, "benches")?;
}
return Ok(None);
}
let mut args = args.to_vec();
args.push("--bench");
let (test, errors) = run_unit_tests(ws.config(), options, &args, &compilation)?;
match errors.len() {
0 => Ok(None),
_ => Ok(Some(CargoTestError::new(test, errors))),
}
}
fn compile_tests<'a>(ws: &Workspace<'a>, options: &TestOptions) -> CargoResult<Compilation<'a>> {
let mut compilation = ops::compile(ws, &options.compile_opts)?;
compilation.tests.sort();
Ok(compilation)
}
/// Runs the unit and integration tests of a package.
fn run_unit_tests(
config: &Config,
options: &TestOptions,
test_args: &[&str],
compilation: &Compilation<'_>,
) -> CargoResult<(Test, Vec<ProcessError>)> {
let cwd = config.cwd();
let mut errors = Vec::new();
for UnitOutput {
unit,
path,
script_meta,
} in compilation.tests.iter()
{
let (exe_display, cmd) = cmd_builds(
config,
cwd,
unit,
path,
script_meta,
test_args,
compilation,
"unittests",
)?;
config
.shell()
.concise(|shell| shell.status("Running", &exe_display))?;
config
.shell()
.verbose(|shell| shell.status("Running", &cmd))?;
let result = cmd.exec();
if let Err(e) = result {
let e = e.downcast::<ProcessError>()?;
errors.push((
unit.target.kind().clone(),
unit.target.name().to_string(),
unit.pkg.name().to_string(),
e,
));
if !options.no_fail_fast {
break;
}
}
}
if errors.len() == 1 {
let (kind, name, pkg_name, e) = errors.pop().unwrap();
Ok((
Test::UnitTest {
kind,
name,
pkg_name,
},
vec![e],
))
} else {
Ok((
Test::Multiple,
errors.into_iter().map(|(_, _, _, e)| e).collect(),
))
}
}
fn run_doc_tests(
ws: &Workspace<'_>,
options: &TestOptions,
test_args: &[&str],
compilation: &Compilation<'_>,
) -> CargoResult<(Test, Vec<ProcessError>)> {
let config = ws.config();
let mut errors = Vec::new();
let doctest_xcompile = config.cli_unstable().doctest_xcompile;
let doctest_in_workspace = config.cli_unstable().doctest_in_workspace;
for doctest_info in &compilation.to_doc_test {
let Doctest {
args,
unstable_opts,
unit,
linker,
script_meta,
env,
} = doctest_info;
if !doctest_xcompile {
match unit.kind {
CompileKind::Host => {}
CompileKind::Target(target) => {
if target.short_name() != compilation.host {
// Skip doctests, -Zdoctest-xcompile not enabled.
config.shell().verbose(|shell| {
shell.note(format!(
"skipping doctests for {} ({}), \
cross-compilation doctests are not yet supported\n\
See https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#doctest-xcompile \
for more information.",
unit.pkg,
unit.target.description_named()
))
})?;
continue;
}
}
}
}
config.shell().status("Doc-tests", unit.target.name())?;
let mut p = compilation.rustdoc_process(unit, *script_meta)?;
for (var, value) in env {
p.env(var, value);
}
p.arg("--crate-name").arg(&unit.target.crate_name());
p.arg("--test");
if doctest_in_workspace {
add_path_args(ws, unit, &mut p);
// FIXME(swatinem): remove the `unstable-options` once rustdoc stabilizes the `test-run-directory` option
p.arg("-Z").arg("unstable-options");
p.arg("--test-run-directory")
.arg(unit.pkg.root().to_path_buf());
} else {
p.arg(unit.target.src_path().path().unwrap());
}
if let CompileKind::Target(target) = unit.kind {
// use `rustc_target()` to properly handle JSON target paths
p.arg("--target").arg(target.rustc_target());
}
if doctest_xcompile {
p.arg("-Zunstable-options");
p.arg("--enable-per-target-ignores");
if let Some((runtool, runtool_args)) = compilation.target_runner(unit.kind) {
p.arg("--runtool").arg(runtool);
for arg in runtool_args {
p.arg("--runtool-arg").arg(arg);
}
}
if let Some(linker) = linker {
let mut joined = OsString::from("linker=");
joined.push(linker);
p.arg("-C").arg(joined);
}
}
for &rust_dep in &[
&compilation.deps_output[&unit.kind],
&compilation.deps_output[&CompileKind::Host],
] {
let mut arg = OsString::from("dependency=");
arg.push(rust_dep);
p.arg("-L").arg(arg);
}
for native_dep in compilation.native_dirs.iter() {
p.arg("-L").arg(native_dep);
}
for arg in test_args {
p.arg("--test-args").arg(arg);
}
if config.shell().verbosity() == Verbosity::Quiet {
p.arg("--test-args").arg("--quiet");
}
p.args(args);
if *unstable_opts {
p.arg("-Zunstable-options");
}
config
.shell()
.verbose(|shell| shell.status("Running", p.to_string()))?;
if let Err(e) = p.exec() {
let e = e.downcast::<ProcessError>()?;
errors.push(e);
if !options.no_fail_fast {
return Ok((Test::Doc, errors));
}
}
}
Ok((Test::Doc, errors))
}
fn display_no_run_information(
ws: &Workspace<'_>,
test_args: &[&str],
compilation: &Compilation<'_>,
exec_type: &str,
) -> CargoResult<()> {
let config = ws.config();
let cwd = config.cwd();
for UnitOutput {
unit,
path,
script_meta,
} in compilation.tests.iter()
{
let (exe_display, cmd) = cmd_builds(
config,
cwd,
unit,
path,
script_meta,
test_args,
compilation,
exec_type,
)?;
config
.shell()
.concise(|shell| shell.status("Executable", &exe_display))?;
config
.shell()
.verbose(|shell| shell.status("Executable", &cmd))?;
}
return Ok(());
}
fn cmd_builds(
config: &Config,
cwd: &Path,
unit: &Unit,
path: &PathBuf,
script_meta: &Option<Metadata>,
test_args: &[&str],
compilation: &Compilation<'_>,
exec_type: &str,
) -> CargoResult<(String, ProcessBuilder)> {
let test_path = unit.target.src_path().path().unwrap();
let short_test_path = test_path
.strip_prefix(unit.pkg.root())
.unwrap_or(test_path)
.display();
let exe_display = match unit.target.kind() {
TargetKind::Test | TargetKind::Bench => format!(
"{} ({})",
short_test_path,
path.strip_prefix(cwd).unwrap_or(path).display()
),
_ => format!(
"{} {} ({})",
exec_type,
short_test_path,
path.strip_prefix(cwd).unwrap_or(path).display()
),
};
let mut cmd = compilation.target_process(path, unit.kind, &unit.pkg, *script_meta)?;
cmd.args(test_args);
if unit.target.harness() && config.shell().verbosity() == Verbosity::Quiet {
cmd.arg("--quiet");
}
Ok((exe_display, cmd))
}
|
use std::{
collections::HashMap,
convert::{TryFrom, TryInto},
fmt::Debug,
pin::Pin,
};
use futures::{
future::ready,
stream::{empty, once, select_all, BoxStream},
Future, FutureExt, Sink, SinkExt, Stream, StreamExt, TryFutureExt, TryStreamExt,
};
use stomp_parser::{client::*, headers::*, server::*};
use tokio::sync::mpsc::{unbounded_channel, UnboundedSender};
use tokio_stream::wrappers::UnboundedReceiverStream;
use crate::{error::StompClientError, session::StompClientSession, spawn};
pub type BytesStream = BoxStream<'static, Result<Vec<u8>, StompClientError>>;
pub type BytesSink = Pin<Box<dyn Sink<Vec<u8>, Error = StompClientError> + Sync + Send + 'static>>;
pub struct DestinationId(pub String);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SubscriptionId(pub String);
pub enum SessionEvent {
Subscribe(DestinationId, UnboundedSender<MessageFrame>),
Unsubscribe(SubscriptionId),
Send(DestinationId, Vec<u8>),
ServerFrame(Result<ServerFrame, StompClientError>),
ServerHeartBeat,
Close,
Disconnected,
}
impl Debug for SessionEvent {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Subscribe(_, _) => "Subscribe",
Self::Unsubscribe(_) => "Unsubscribe",
Self::Send(_, _) => "Send",
Self::ServerFrame(_) => "ServerFrame",
Self::ServerHeartBeat => "ServerHeartBeat",
Self::Close => "Close",
Self::Disconnected => "Disconnected",
})
}
}
pub enum SessionState {
Alive,
Dead,
}
pub enum MessageToServer {
ClientFrame(ClientFrame),
Heartbeat,
}
type EventResult = Result<(SessionState, Option<MessageToServer>), StompClientError>;
type EventResultFuture = Pin<Box<dyn Future<Output = EventResult> + Send + 'static>>;
pub struct SessionEventLoop {
client_event_sender: UnboundedSender<SessionEvent>,
subscriptions: HashMap<SubscriptionId, UnboundedSender<MessageFrame>>,
}
async fn perform_handshake(
host_id: String,
stream_from_server: &mut BytesStream,
sink_to_server: &mut BytesSink,
) -> Result<(), StompClientError> {
sink_to_server.send(connect_frame(host_id)).await?;
match stream_from_server.next().await {
None => Err(StompClientError::new(
"Stream from server ended before handshake",
)),
Some(Err(client_err)) => Err(client_err),
Some(Ok(bytes)) => validate_handshake(Some(bytes)),
}
}
impl SessionEventLoop {
fn new(client_event_sender: UnboundedSender<SessionEvent>) -> SessionEventLoop {
SessionEventLoop {
client_event_sender,
subscriptions: HashMap::new(),
}
}
pub async fn start(
host_id: String,
mut stream_from_server: BytesStream,
mut sink_to_server: BytesSink,
) -> Result<StompClientSession, StompClientError> {
perform_handshake(host_id, &mut stream_from_server, &mut &mut sink_to_server).await?;
// the handshake complete succressfully!
let stream_from_server = create_server_event_stream(stream_from_server);
let (client_event_sender, stream_from_client) = unbounded_channel();
let stream_from_client = UnboundedReceiverStream::new(stream_from_client)
.chain(once(ready(SessionEvent::Close)));
let client_heartbeat_stream = empty();
let all_events = select_all(vec![
stream_from_client.boxed(),
stream_from_server.boxed(),
client_heartbeat_stream.boxed(),
])
.inspect(|item| {
log::debug!("Event: {:?}", item);
});
let event_handler = {
let mut session = SessionEventLoop::new(client_event_sender.clone());
// client_session.start_heartbeat_listener(client_heartbeat_stream);
move |event| session.handle_event(event)
};
let response_stream = all_events
.then(event_handler)
.inspect_ok(|_| {
log::debug!("Response");
})
.inspect_err(Self::log_error)
.take_while(Self::not_dead)
.filter_map(Self::into_opt_ok_of_bytes)
.forward(sink_to_server)
.map(|_| ());
spawn(response_stream);
Ok(StompClientSession::new(client_event_sender))
}
fn into_opt_ok_of_bytes(
result: Result<(SessionState, Option<MessageToServer>), StompClientError>,
) -> impl Future<Output = Option<Result<Vec<u8>, StompClientError>>> {
ready(
// Drop the ClientState, already handled
result
.map(|(_, opt_frame)| {
// serialize the frame
opt_frame.map(|either| match either {
MessageToServer::ClientFrame(frame) => {
frame.try_into().expect("Serialisation failed")
}
MessageToServer::Heartbeat => b"\n".to_vec(),
})
})
// drop errors
.or(Ok(None))
// cause only Some(Ok(bytes)) values to be passed on
.transpose(),
)
}
fn log_error(error: &StompClientError) {
log::error!("SessionEventLoop error: {:?}", error);
}
fn not_dead(event_result: &EventResult) -> impl Future<Output = bool> {
ready(!matches!(event_result, Ok((SessionState::Dead, _))))
}
fn subscribe(
&mut self,
destination: DestinationId,
sender: UnboundedSender<MessageFrame>,
) -> EventResult {
let subscription_id = SubscriptionId(self.subscriptions.len().to_string());
self.start_subscription_end_listener(sender.clone(), subscription_id.clone());
log::info!(
"Subscribing to destination '{:?}' with id '{:?}'",
&destination.0,
&subscription_id
);
let message_to_server = MessageToServer::ClientFrame(ClientFrame::Subscribe(
SubscribeFrameBuilder::new(destination.0, subscription_id.0.clone()).build(),
));
self.subscriptions.insert(subscription_id, sender);
Ok((SessionState::Alive, Some(message_to_server)))
}
fn start_subscription_end_listener(
&self,
sender: UnboundedSender<MessageFrame>,
subscription: SubscriptionId,
) {
let client_event_sender = self.client_event_sender.clone();
spawn(async move {
sender.closed().await;
if let Err(err) = client_event_sender.send(SessionEvent::Unsubscribe(subscription)) {
log::error!("Unable to unsubscribe, event-loop dead? Error: {:?}", err);
}
});
}
fn unsubscribe(&mut self, subscription: SubscriptionId) -> EventResult {
match self.subscriptions.remove(&subscription) {
Some(_) => {
let message_to_server = MessageToServer::ClientFrame(ClientFrame::Unsubscribe(
UnsubscribeFrameBuilder::new(subscription.0.clone()).build(),
));
Ok((SessionState::Alive, Some(message_to_server)))
}
None => Err(StompClientError::new(format!(
"Tried to remove missing subscription {:?}",
subscription,
))),
}
}
fn send(&mut self, destination: DestinationId, content: Vec<u8>) -> EventResult {
let message_to_server = MessageToServer::ClientFrame(ClientFrame::Send(
SendFrameBuilder::new(destination.0).body(content).build(),
));
Ok((SessionState::Alive, Some(message_to_server)))
}
fn handle_server_frame(&mut self, server_frame: ServerFrame) -> EventResultFuture {
log::info!("Handling server frame.");
match server_frame {
ServerFrame::Message(message_frame) => ready(self.forward_message(message_frame))
.map_ok(|()| (SessionState::Alive, None))
.boxed(),
_ => todo!(),
}
}
fn forward_message(&mut self, message_frame: MessageFrame) -> Result<(), StompClientError> {
self.subscriptions
.get(&SubscriptionId(
message_frame.subscription.value().to_owned(),
))
.ok_or_else(|| {
StompClientError::new(format!(
"Received message for unknown subscription {}",
message_frame.subscription.value()
))
})
.and_then(|sender_for_sub| {
sender_for_sub.send(message_frame).map_err(|err| {
StompClientError::new(format!("error sending message to handler: {}", err))
})
})
}
fn handle_event(&mut self, event: SessionEvent) -> EventResultFuture {
match event {
SessionEvent::Subscribe(destination, message_sender) => {
ready(self.subscribe(destination, message_sender)).boxed()
}
SessionEvent::Unsubscribe(subscription_id) => {
ready(self.unsubscribe(subscription_id)).boxed()
}
SessionEvent::Send(destination, content) => {
ready(self.send(destination, content)).boxed()
}
SessionEvent::ServerFrame(Ok(server_frame)) => self.handle_server_frame(server_frame),
SessionEvent::ServerFrame(Err(error)) => {
log::error!("Error processing message from server: {:?}", error);
ready(Err(error)).boxed()
}
SessionEvent::Close => {
log::info!("Session closed by client.");
ready(Ok((SessionState::Dead, None))).boxed()
}
SessionEvent::Disconnected => {
log::error!("Connection dropped by server.");
ready(Ok((SessionState::Dead, None))).boxed()
}
ev => {
log::info!("Unknown event received: {:?}", ev);
todo!()
}
}
}
}
fn create_server_event_stream(raw_stream: BytesStream) -> impl Stream<Item = SessionEvent> {
// Closes this session; will be chained to client stream to run after that ends
let close_stream = once(async { SessionEvent::Disconnected }).boxed();
raw_stream
.and_then(|bytes| parse_server_message(bytes).boxed())
.map(|opt_frame| {
opt_frame
.transpose()
.map(SessionEvent::ServerFrame)
.unwrap_or(SessionEvent::ServerHeartBeat)
})
.chain(close_stream)
}
async fn parse_server_message(bytes: Vec<u8>) -> Result<Option<ServerFrame>, StompClientError> {
if is_heartbeat(&*bytes) {
Ok(None)
} else {
Some(ServerFrame::try_from(bytes).map_err(|err| err.into())).transpose()
}
}
fn is_heartbeat(bytes: &[u8]) -> bool {
matches!(bytes, b"\n" | b"\r\n")
}
fn validate_handshake(response: Option<Vec<u8>>) -> Result<(), StompClientError> {
match response {
None => Err(StompClientError::new("Expected Some bytes")),
Some(bytes) => match ServerFrame::try_from(bytes) {
Ok(ServerFrame::Connected(connected_frame)) => {
if let StompVersion::V1_2 = connected_frame.version.value() {
// Start the event loop, and return the session
//remainder.for_each(|_| async {});
Ok(())
} else {
Err(StompClientError::new(format!(
"Handshake failed, server replied with invalid StompVersion: {}",
connected_frame.version
)))
}
}
Ok(other_frame) => Err(StompClientError::new(format!(
"Handshake failed, expected CONNECTED Frame, received: {}",
other_frame
))),
Err(err) => Err(err.into()),
},
}
}
fn connect_frame(host_id: String) -> Vec<u8> {
ConnectFrameBuilder::new(host_id, StompVersions(vec![StompVersion::V1_2]))
.build()
.try_into()
.unwrap()
}
#[cfg(all(test, target_arch = "wasm32"))]
mod wasm_tests {
use futures::channel::mpsc::SendError;
use futures::future::join;
use wasm_bindgen_test::*;
use super::*;
use futures::sink::SinkExt;
use futures::stream::StreamExt;
use futures::TryFutureExt;
use sender_sink::wrappers::SinkError;
use sender_sink::wrappers::UnboundedSenderSink;
use std::convert::TryFrom;
use stomp_parser::client::*;
use stomp_parser::server::*;
use stomp_test_utils::*;
use tokio_stream::wrappers::UnboundedReceiverStream;
impl From<SendError> for StompClientError {
fn from(source: SendError) -> Self {
StompClientError::new(format!("{:?}", source))
}
}
#[wasm_bindgen_test]
async fn it_works() {
let (mut in_sender, in_receiver) = futures::channel::mpsc::unbounded();
let (out_sender, mut out_receiver) = futures::channel::mpsc::unbounded();
join(
SessionEventLoop::start(
"test".to_owned(),
in_receiver.boxed(),
Box::pin(out_sender.sink_err_into::<StompClientError>()),
),
async move {
let bytes = out_receiver.next().await.expect("receive failed");
if let Ok(ClientFrame::Connect(_)) = ClientFrame::try_from(bytes) {
in_sender.send(Ok(ConnectedFrameBuilder::new(StompVersion::V1_2)
.build()
.try_into()
.expect("serialize failed")));
} else {
panic!("Did not receive connect frame");
}
},
)
.await;
}
}
|
use openssl;
use std;
use serde_json;
use url;
use hyper;
error_chain! {
foreign_links {
OpenSSL(openssl::error::ErrorStack);
IOError(std::io::Error);
JsonError(serde_json::Error);
UrlParseError(url::ParseError);
UriError(hyper::error::UriError);
HTTPError(hyper::error::Error);
}
errors {
PrivateKeyError(path: String) {
description("Failed to read private key")
display("Failed to read private key at {}", path)
}
ListError {
description("Failed to interpret a list of items")
}
KeyMissingError(field: String) {
description("Failed to fetch field from JSON")
display("Failed to fetch {} from JSON", field)
}
UnparseableConfigError(path: String) {
description("Can't read config file")
display("Can't read config file at {}", path)
}
}
}
|
#[macro_use]
extern crate cluLog;
#[derive(Debug, Default)]
pub struct Point(u32, f32);
fn main() {
//init_clulog!();
cluLog::set_logger(cluLog::LogDefault::default());
let a = Point::default();
let b = Point(120, 1.345);
test(&a, &b);
}
fn test(point: &Point, point_2: &Point) {
if point.0 == 0 {
trace!("Unknown Behavior");
}
if point_2.0 > 100 {
trace!("Unknown Behavior, {:?}", point_2);
}
inf!("Point: {:?} == {:?}", point, point_2);
} |
#[doc = "Register `CSR46` reader"]
pub type R = crate::R<CSR46_SPEC>;
#[doc = "Register `CSR46` writer"]
pub type W = crate::W<CSR46_SPEC>;
#[doc = "Field `CS46` reader - Context swap x Refer to Section 24.7.7: HASH context swap registers introduction."]
pub type CS46_R = crate::FieldReader<u32>;
#[doc = "Field `CS46` writer - Context swap x Refer to Section 24.7.7: HASH context swap registers introduction."]
pub type CS46_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 32, O, u32>;
impl R {
#[doc = "Bits 0:31 - Context swap x Refer to Section 24.7.7: HASH context swap registers introduction."]
#[inline(always)]
pub fn cs46(&self) -> CS46_R {
CS46_R::new(self.bits)
}
}
impl W {
#[doc = "Bits 0:31 - Context swap x Refer to Section 24.7.7: HASH context swap registers introduction."]
#[inline(always)]
#[must_use]
pub fn cs46(&mut self) -> CS46_W<CSR46_SPEC, 0> {
CS46_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 = "HASH context swap register 46\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr46::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 [`csr46::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct CSR46_SPEC;
impl crate::RegisterSpec for CSR46_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`csr46::R`](R) reader structure"]
impl crate::Readable for CSR46_SPEC {}
#[doc = "`write(|w| ..)` method takes [`csr46::W`](W) writer structure"]
impl crate::Writable for CSR46_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets CSR46 to value 0"]
impl crate::Resettable for CSR46_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
// This module provides Randorst struct for generating
// sorted random numbers in constant space
// used to smoothly extract words from large file in random fashion
//
// Randorst is my rust implementation of the algorithm
// proposed in the following paper:
// Bentley, Jon & Saxe, James. (1980). Generating Sorted Lists of Random Numbers.
// ACM Trans. Math. Softw.. 6. 359-364. 10.1145/355900.355907.
use fastrand::Rng;
use std::ops::{Range, RangeInclusive};
// there is also std::ops::RangeBounds;
pub trait StartEndRange {
fn get_bounds(self) -> (usize, usize);
}
impl StartEndRange for Range<usize> {
fn get_bounds(self) -> (usize, usize) {
(self.start, self.end - 1)
}
}
impl StartEndRange for RangeInclusive<usize> {
fn get_bounds(self) -> (usize, usize) {
self.into_inner()
}
}
/// Struct for generating sorted random numbers
/// ```ignore
/// // generate 100 sorted random numbers from 0 to 255
/// use smokey::utils::randorst::Randorst;
/// Randorst::gen(100, 0..256);
/// Randorst::gen(100, 0..=255);
/// ```
// TODO shouldn't I use f64?
pub struct Randorst {
n: usize,
min: usize,
curmax: f32,
extent: f32,
rng: Rng,
}
impl Iterator for Randorst {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
if self.n <= 1 {
return None;
}
self.n -= 1;
self.curmax *= self.rng.f32().powf(1.0 / self.n as f32);
// self.curmax instead of (1. - self.curmax) for descending order
Some(self.min + ((1. - self.curmax) * self.extent) as usize)
}
}
impl Randorst {
/// Returns a generator of sorted random numbers
/// # Panics
///
/// Panics if range is invalid e.g. 0..0
///
/// # Examples
///
/// ```ignore
/// use smokey::utils::randorst::Randorst;
/// let mut last: usize = 0;
/// let (a, b) = (0, 256);
/// for i in Randorst::gen(100, a..b) {
/// assert!(last <= i);
/// assert!(i >= a && i < b);
/// last = i;
/// }
/// ```
///
pub fn gen<R>(n: usize, range: R) -> Self
where
R: StartEndRange,
{
let (start, end) = range.get_bounds();
Self {
min: start,
n: n + 1,
extent: ((end + 1) - start) as f32,
rng: Rng::new(),
curmax: 1.,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn randorst_test_helper(n: usize, a: usize, b: usize) {
let mut last_in: usize = 0;
let mut last_ex: usize = 0;
let exclusive = Randorst::gen(n, a..b);
let inclusive = Randorst::gen(n, a..=b);
for (eni, ini) in exclusive.zip(inclusive) {
// last item cannot be larger than the next
assert!(last_ex <= eni && last_in <= ini);
// exclusive bound testing
assert!(eni >= a && eni < b);
// inclusive bound testing
assert!(ini >= a && ini <= b);
last_in = ini;
last_ex = eni;
}
}
#[test]
fn test_randorst() {
randorst_test_helper(100, 10, 1000);
randorst_test_helper(100, 0, 1);
randorst_test_helper(999, 0, 78);
randorst_test_helper(1_000, 2121, 100_000_000);
}
}
|
use totsu::prelude::*;
use totsu::*;
use totsu_f64lapack::F64LAPACK;
use std::str::FromStr;
use plotters::prelude::*;
use intel_mkl_src as _;
use anyhow::Result;
type La = F64LAPACK;
type AMatBuild = MatBuild<La>;
type AProbQCQP = ProbQCQP<La>;
type ASolver = Solver<La>;
/// main
fn main() -> Result<()> {
env_logger::init();
//----- parameters
let t_cap = 30; // # of grids dividing time [0, 1)
let mut a_cap = 90.0; // limit acceleration magnitude
let x_s = (0., 0.); // start position
let x_m1 = (0.5, -1.5); // target position at time=1/3
let x_m2 = (0.25, 1.5); // target position at time=2/3
let x_t = (1., 1.); // terminal position
let args: Vec<String> = std::env::args().collect();
if args.len() >= 2 {
if let Ok(a) = f64::from_str(&args[1]) {
a_cap = a; // a_cap can be specified by 1st argument
}
}
//----- formulate path-planning as QCQP
let n = t_cap * 2;
let m = t_cap - 2;
let p = 6 * 2;
let mut syms_p = vec![AMatBuild::new(MatType::SymPack(n)); m + 1];
let vecs_q = vec![AMatBuild::new(MatType::General(n, 1)); m + 1];
let mut scls_r = vec![0.; m + 1];
let dt = 1. / t_cap as f64;
let mut mat_d = AMatBuild::new(MatType::General(n, n));
for i in 0 .. t_cap - 1 {
let ti = i;
mat_d[(ti, ti)] = -1. / dt;
mat_d[(ti, ti + 1)] = 1. / dt;
let ti = t_cap + i;
mat_d[(ti, ti)] = -1. / dt;
mat_d[(ti, ti + 1)] = 1. / dt;
}
// minimize total squared magnitude of velocity
syms_p[0].set_by_fn(|r, c| {
let mut v = 0.;
for i in 0.. n {
v += mat_d[(i, r)] * mat_d[(i, c)];
}
v
});
let dtdt = dt * dt;
for i in 0 .. t_cap - 2 {
let mut mat_d = AMatBuild::new(MatType::General(n, n));
let mi = i + 1;
let ti = i;
mat_d[(ti, ti)] = 1. / dtdt;
mat_d[(ti, ti + 1)] = -2. / dtdt;
mat_d[(ti, ti + 2)] = 1. / dtdt;
let ti = t_cap + i;
mat_d[(ti, ti)] = 1. / dtdt;
mat_d[(ti, ti + 1)] = -2. / dtdt;
mat_d[(ti, ti + 2)] = 1. / dtdt;
// limit acceleration magnitude
syms_p[mi].set_by_fn(|r, c| {
let mut v = 0.;
for i in 0.. n {
v += mat_d[(i, r)] * mat_d[(i, c)];
}
v
});
scls_r[mi] = -0.5 * a_cap * a_cap;
}
let mut mat_a = AMatBuild::new(MatType::General(p, n));
let mut vec_b = AMatBuild::new(MatType::General(p, 1));
// target point: x(0) = x_s, v(0) = 0
// x0
mat_a[(0, 0)] = 1.;
vec_b[(0, 0)] = x_s.0;
// x1
mat_a[(1, t_cap)] = 1.;
vec_b[(1, 0)] = x_s.0;
// v0
mat_a[(2, 0)] = -1.;
mat_a[(2, 1)] = 1.;
// v1
mat_a[(3, t_cap)] = -1.;
mat_a[(3, t_cap + 1)] = 1.;
// target point: x(1) = x_t, v(1) = 0
// x0
mat_a[(4, t_cap - 1)] = 1.;
vec_b[(4, 0)] = x_t.0;
// x1
mat_a[(5, t_cap * 2 - 1)] = 1.;
vec_b[(5, 0)] = x_t.1;
// v0
mat_a[(6, t_cap - 2)] = -1.;
mat_a[(6, t_cap - 1)] = 1.;
// v1
mat_a[(7, t_cap * 2 - 2)] = -1.;
mat_a[(7, t_cap * 2 - 1)] = 1.;
// target point: x(1/3) = x_m1
let t_m1 = t_cap / 3;
// x0
mat_a[(8, t_m1)] = 1.;
vec_b[(8, 0)] = x_m1.0;
// x1
mat_a[(9, t_cap + t_m1)] = 1.;
vec_b[(9, 0)] = x_m1.1;
// target point: x(2/3) = x_m2
let t_m2 = t_cap * 2 / 3;
// x0
mat_a[(10, t_m2)] = 1.;
vec_b[(10, 0)] = x_m2.0;
// x1
mat_a[(11, t_cap + t_m2)] = 1.;
vec_b[(11, 0)] = x_m2.1;
//----- solve QCQP
let s = ASolver::new().par(|p| {
p.eps_acc = 1e-3;
utils::set_par_by_env(p);
});
let mut qp = AProbQCQP::new(syms_p, vecs_q, scls_r, mat_a, vec_b, s.par.eps_zero);
let rslt = s.solve(qp.problem())?;
//println!("{:?}", rslt);
//----- graph plot 1
let root = SVGBackend::new("plot1.svg", (480, 360)).into_drawing_area();
root.fill(&WHITE)?;
let mut chart = ChartBuilder::on(&root)
.margin(30)
.x_label_area_size(35)
.y_label_area_size(45)
.build_cartesian_2d(
-0.1..1.1,
-1.7..1.7,
)?;
chart.configure_mesh()
.x_labels(6)
.y_labels(7)
.x_desc("x0")
.y_desc("x1")
.disable_mesh()
.draw()?;
chart.draw_series(
LineSeries::new(
(0..t_cap).map(|i| (rslt.0[i], rslt.0[t_cap + i])),
BLUE.stroke_width(2).filled()
).point_size(3)
)?;
chart.draw_series(
PointSeries::of_element(
[x_s, x_m1, x_m2, x_t],
7,
RED.mix(0.5).stroke_width(4),
&|coord, size, style| {
EmptyElement::at(coord)
+ Cross::new((0, 0), size, style)
}
)
)?;
//----- graph plot 2
let root = SVGBackend::new("plot2.svg", (480, 360)).into_drawing_area();
root.fill(&WHITE)?;
let (upper, lower) = root.split_vertically(360/2);
let mut chart = ChartBuilder::on(&upper)
.margin(20)
.margin_bottom(0)
.x_label_area_size(35)
.y_label_area_size(45)
.build_cartesian_2d(0.0..1.0, -1.0..12.0)?;
chart.configure_mesh()
.x_labels(6)
.y_labels(5)
.y_desc("velocity mag.")
.disable_mesh()
.draw()?;
chart.draw_series(
LineSeries::new(
(0..t_cap - 1).map(|i| {
let v0 = rslt.0[i + 1] - rslt.0[i];
let v1 = rslt.0[t_cap + i + 1] - rslt.0[t_cap + i];
let v = v0.hypot(v1) / dt;
(i as f64 * dt, v)
}),
BLUE.stroke_width(1).filled()
).point_size(2)
)?;
let mut chart = ChartBuilder::on(&lower)
.margin(20)
.margin_top(0)
.x_label_area_size(35)
.y_label_area_size(45)
.build_cartesian_2d(
0.0..1.0,
-5.0..95.0,
)?;
chart.configure_mesh()
.x_labels(6)
.y_labels(5)
.x_desc("time")
.y_desc("acceleration mag.")
.disable_mesh()
.draw()?;
chart.draw_series(
LineSeries::new(
(0..t_cap - 2).map(|i| {
let a0 = rslt.0[i + 2] - 2.0 * rslt.0[i + 1] + rslt.0[i];
let a1 = rslt.0[t_cap + i + 2] - 2.0 * rslt.0[t_cap + i + 1] + rslt.0[t_cap + i];
let a = a0.hypot(a1) / dt / dt;
(i as f64 * dt, a)
}),
BLUE.stroke_width(1).filled()
).point_size(2)
)?;
Ok(())
}
|
//! See [`Idx`].
#![deny(clippy::pedantic, missing_debug_implementations, missing_docs, rust_2018_idioms)]
/// An index type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Idx(u32);
impl Idx {
/// Returns a new `Idx` for the usize.
#[must_use]
pub fn new(n: usize) -> Self {
Self(n.try_into().expect("couldn't convert to Idx"))
}
#[doc(hidden)]
#[must_use]
pub const fn new_u32(n: u32) -> Self {
Self(n)
}
/// Converts this back into a usize.
#[must_use]
pub fn to_usize(self) -> usize {
self.0.try_into().expect("couldn't convert from Idx")
}
}
impl nohash_hasher::IsEnabled for Idx {}
|
#[doc = "Register `IOPSMENR` reader"]
pub type R = crate::R<IOPSMENR_SPEC>;
#[doc = "Register `IOPSMENR` writer"]
pub type W = crate::W<IOPSMENR_SPEC>;
#[doc = "Field `GPIOASMEN` reader - I/O port A clock enable during Sleep mode Set and cleared by software."]
pub type GPIOASMEN_R = crate::BitReader;
#[doc = "Field `GPIOASMEN` writer - I/O port A clock enable during Sleep mode Set and cleared by software."]
pub type GPIOASMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `GPIOBSMEN` reader - I/O port B clock enable during Sleep mode Set and cleared by software."]
pub type GPIOBSMEN_R = crate::BitReader;
#[doc = "Field `GPIOBSMEN` writer - I/O port B clock enable during Sleep mode Set and cleared by software."]
pub type GPIOBSMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `GPIOCSMEN` reader - I/O port C clock enable during Sleep mode Set and cleared by software."]
pub type GPIOCSMEN_R = crate::BitReader;
#[doc = "Field `GPIOCSMEN` writer - I/O port C clock enable during Sleep mode Set and cleared by software."]
pub type GPIOCSMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `GPIODSMEN` reader - I/O port D clock enable during Sleep mode Set and cleared by software."]
pub type GPIODSMEN_R = crate::BitReader;
#[doc = "Field `GPIODSMEN` writer - I/O port D clock enable during Sleep mode Set and cleared by software."]
pub type GPIODSMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `GPIOFSMEN` reader - I/O port F clock enable during Sleep mode Set and cleared by software."]
pub type GPIOFSMEN_R = crate::BitReader;
#[doc = "Field `GPIOFSMEN` writer - I/O port F clock enable during Sleep mode Set and cleared by software."]
pub type GPIOFSMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - I/O port A clock enable during Sleep mode Set and cleared by software."]
#[inline(always)]
pub fn gpioasmen(&self) -> GPIOASMEN_R {
GPIOASMEN_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - I/O port B clock enable during Sleep mode Set and cleared by software."]
#[inline(always)]
pub fn gpiobsmen(&self) -> GPIOBSMEN_R {
GPIOBSMEN_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - I/O port C clock enable during Sleep mode Set and cleared by software."]
#[inline(always)]
pub fn gpiocsmen(&self) -> GPIOCSMEN_R {
GPIOCSMEN_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - I/O port D clock enable during Sleep mode Set and cleared by software."]
#[inline(always)]
pub fn gpiodsmen(&self) -> GPIODSMEN_R {
GPIODSMEN_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 5 - I/O port F clock enable during Sleep mode Set and cleared by software."]
#[inline(always)]
pub fn gpiofsmen(&self) -> GPIOFSMEN_R {
GPIOFSMEN_R::new(((self.bits >> 5) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - I/O port A clock enable during Sleep mode Set and cleared by software."]
#[inline(always)]
#[must_use]
pub fn gpioasmen(&mut self) -> GPIOASMEN_W<IOPSMENR_SPEC, 0> {
GPIOASMEN_W::new(self)
}
#[doc = "Bit 1 - I/O port B clock enable during Sleep mode Set and cleared by software."]
#[inline(always)]
#[must_use]
pub fn gpiobsmen(&mut self) -> GPIOBSMEN_W<IOPSMENR_SPEC, 1> {
GPIOBSMEN_W::new(self)
}
#[doc = "Bit 2 - I/O port C clock enable during Sleep mode Set and cleared by software."]
#[inline(always)]
#[must_use]
pub fn gpiocsmen(&mut self) -> GPIOCSMEN_W<IOPSMENR_SPEC, 2> {
GPIOCSMEN_W::new(self)
}
#[doc = "Bit 3 - I/O port D clock enable during Sleep mode Set and cleared by software."]
#[inline(always)]
#[must_use]
pub fn gpiodsmen(&mut self) -> GPIODSMEN_W<IOPSMENR_SPEC, 3> {
GPIODSMEN_W::new(self)
}
#[doc = "Bit 5 - I/O port F clock enable during Sleep mode Set and cleared by software."]
#[inline(always)]
#[must_use]
pub fn gpiofsmen(&mut self) -> GPIOFSMEN_W<IOPSMENR_SPEC, 5> {
GPIOFSMEN_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 = "RCC I/O port in Sleep mode clock enable register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`iopsmenr::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 [`iopsmenr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct IOPSMENR_SPEC;
impl crate::RegisterSpec for IOPSMENR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`iopsmenr::R`](R) reader structure"]
impl crate::Readable for IOPSMENR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`iopsmenr::W`](W) writer structure"]
impl crate::Writable for IOPSMENR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets IOPSMENR to value 0x3f"]
impl crate::Resettable for IOPSMENR_SPEC {
const RESET_VALUE: Self::Ux = 0x3f;
}
|
use crate::nasdaq::gen;
#[derive(Default, Debug, Clone, PartialEq, serde_derive::Serialize, serde_derive::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InsidersRoot {
pub data: Data,
pub message: ::serde_json::Value,
pub status: gen::Status,
}
impl crate::HasRecs for InsidersRoot {
fn to_recs(&self) -> Vec<Vec<String>> {
return self.data
.transaction_table.rows
.iter()
.map(|x| x.to_rec())
.collect();
}
}
#[derive(Default, Debug, Clone, PartialEq, serde_derive::Serialize, serde_derive::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Data {
pub title: ::serde_json::Value,
pub number_of_trades: NumberOfTrades,
pub number_of_shares_traded: NumberOfSharesTraded,
pub transaction_table: TransactionTable,
pub filer_transaction_table: ::serde_json::Value,
}
#[derive(Default, Debug, Clone, PartialEq, serde_derive::Serialize, serde_derive::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NumberOfTrades {
pub headers: ::serde_json::Value,
pub rows: Vec<Row>,
}
#[derive(Default, Debug, Clone, PartialEq, serde_derive::Serialize, serde_derive::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Row {
pub insider_trade: String,
pub months3: String,
pub months12: String,
}
#[derive(Default, Debug, Clone, PartialEq, serde_derive::Serialize, serde_derive::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NumberOfSharesTraded {
pub headers: ::serde_json::Value,
pub rows: Vec<Row>,
}
#[derive(Default, Debug, Clone, PartialEq, serde_derive::Serialize, serde_derive::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TransactionTable {
pub headers: ::serde_json::Value,
pub rows: Vec<TransactionRow>,
}
#[derive(Default, Debug, Clone, PartialEq, serde_derive::Serialize, serde_derive::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TransactionRow {
pub insider: String,
pub relation: String,
pub last_date: String,
pub transaction_type: String,
pub own_type: String,
pub shares_traded: String,
pub last_price: String,
pub shares_held: String,
pub url: String,
}
impl TransactionRow {
pub fn to_rec(&self) -> Vec<String> {
return vec![
self.insider.to_string(),
self.relation.to_string(),
self.last_date.to_string(),
self.transaction_type.to_string(),
self.own_type.to_string(),
self.shares_traded.to_string(),
self.last_price.to_string(),
self.shares_held.to_string(),
self.url.to_string(),
];
}
}
pub const NDAQ_INSIDER_HEADER: [&'static str; 9] = [
"insider",
"relation",
"last_date",
"transaction_type",
"own_type",
"shares_traded",
"last_price",
"shares_held",
"url",
];
|
use std::fmt;
use std::fmt::Display;
use rand::Rng;
#[derive(Hash, Eq, PartialEq, Debug, PartialOrd, Ord, Clone, Copy)]
pub struct Pos(pub u64);
pub const START: Pos = Pos(0xfedcba9876543210);
impl Pos {
pub fn hole_index(&self) -> usize {
for i in 0..16 {
if (self.0 >> (4 * i)) & 15 == 15 {
return i;
}
}
unreachable!()
}
pub fn swap(mut self, from: usize, to: usize) -> Pos {
let to_mask = !(((!(self.0 >> (4 * to))) & 15) << (4 * from));
self.0 &= to_mask;
let from_mask = 15 << (4 * to);
self.0 |= from_mask;
self
}
pub fn manhattan(self, target: Pos) -> usize {
let mut res: i8 = 0;
let mut invers_target: u64 = 0;
for i in 0..16 {
invers_target |= i << (4 * ((target.0 >> (4 * i)) & 15));
}
for pos in 0..16 {
let curr_val = (self.0 >> (4 * pos)) & 15;
let pos_in_target = (invers_target >> (4 * curr_val)) & 15;
res += ((pos & 3) as i8 - (pos_in_target & 3) as i8).abs()
+ ((pos >> 2) as i8 - (pos_in_target >> 2) as i8).abs();
}
(res as usize) / 2
}
pub fn from_string(input: String) -> Pos {
let vec: Vec<u64> = input
.split_whitespace()
.map(|word| word.parse().unwrap())
.map(|num: u64| if num == 0 { 15 } else { num - 1 })
.collect();
Self::from_permutation(vec)
}
pub fn from_permutation(input: Vec<u64>) -> Pos {
let mut acc: Pos = Pos(0);
for i in 0..16 {
acc.0 |= input[i] << (4 * i);
}
acc
}
pub fn to_permutation(self) -> Vec<u64> {
let mut res = Vec::new();
for i in 0..16 {
let val = (self.0 >> (4 * i)) & 15;
res.push(if val == 15 { 0 } else { val + 1 });
}
res
}
pub fn apply(self, d: Dir) -> Pos {
let hole_ind = self.hole_index();
match d {
Dir::Down => {
if hole_ind >> 2 == 3 {
self
} else {
self.swap(hole_ind, hole_ind + 4)
}
}
Dir::Left => {
if hole_ind & 3 == 0 {
self
} else {
self.swap(hole_ind, hole_ind - 1)
}
}
Dir::Up => {
if hole_ind >> 2 == 0 {
self
} else {
self.swap(hole_ind, hole_ind - 4)
}
}
Dir::Right => {
if hole_ind & 3 == 3 {
self
} else {
self.swap(hole_ind, hole_ind + 1)
}
}
_ => self,
}
}
}
impl Display for Pos {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let perm = self.to_permutation();
for i in (0..16).step_by(4) {
write!(
f,
"{:0>2}|{:0>2}|{:0>2}|{:0>2}\n",
perm[i],
perm[i + 1],
perm[i + 2],
perm[i + 3]
)?;
if i + 4 < 16 {
write!(f, "--+--+--+--\n")?;
}
}
Ok(())
}
}
#[derive(Debug, Clone, Copy)]
pub enum Dir {
Up,
Right,
Down,
Left,
End,
}
impl Display for Dir {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Dir::Up => write!(f, "Up"),
Dir::Right => write!(f, "Righ"),
Dir::Down => write!(f, "Down"),
Dir::Left => write!(f, "Left"),
Dir::End => write!(f, "End"),
};
Ok(())
}
}
impl Dir {
fn from_num(n: u32) -> Dir {
match n % 4 {
0 => Dir::Up,
1 => Dir::Right,
2 => Dir::Down,
3 => Dir::Left,
_ => unreachable!(),
}
}
pub fn next(self) -> Self {
match self {
Dir::Up => Dir::Right,
Dir::Right => Dir::Down,
Dir::Down => Dir::Left,
Dir::Left => Dir::End,
Dir::End => Dir::End,
}
}
pub fn random_path(n: usize) -> Vec<Dir> {
let mut rng = rand::thread_rng();
(0..n)
.map(|_| rng.gen::<u32>())
.map(Dir::from_num)
.collect()
}
}
pub struct Neighbors {
center: Pos,
curr_dir: Dir,
}
impl Neighbors {
pub fn new(center: Pos, curr_dir: Dir) -> Neighbors {
Neighbors { center, curr_dir }
}
pub fn get_dir(&self) -> Dir {
match self.curr_dir {
Dir::Up => Dir::End,
Dir::Right => Dir::Up,
Dir::Down => Dir::Right,
Dir::Left => Dir::Down,
Dir::End => Dir::Left,
}
}
}
impl Iterator for Neighbors {
type Item = Pos;
fn next(&mut self) -> Option<Pos> {
if let Dir::End = self.curr_dir {
None
} else {
let res = self.center.apply(self.curr_dir);
self.curr_dir = self.curr_dir.next();
if self.center == res {
self.next()
} else {
Some(res)
}
}
}
}
pub fn neighbors(pos: Pos) -> Neighbors {
Neighbors::new(pos, Dir::Up)
}
pub fn maze() -> Pos {
Dir::random_path(200).into_iter().fold(START, Pos::apply)
}
#[cfg(test)]
mod tests {
use crate::position::{maze, neighbors, START};
#[test]
fn display_test() {
println!("{}", START);
println!("{}", maze());
}
#[test]
fn neighbors_test() {
for i in neighbors(START) {
println!("{}", i);
for j in neighbors(i) {
println!("{}", j);
}
}
}
}
|
// Keccak-f[800]
mod short_msg_kat_r288c512;
mod short_msg_kat_r544c256;
mod short_msg_kat_r640c160;
// Keccak-f[400]
mod short_msg_kat_r144c256;
mod short_msg_kat_r240c160;
// Keccak-f[200]
mod short_msg_kat_r40c160;
// Keccak{224, 256, 384, 512}
mod short_msg_kat_224;
mod short_msg_kat_256;
mod short_msg_kat_384;
mod short_msg_kat_512;
|
use std::{fs, collections::HashSet};
const ROPE_LENGTH: usize = 10;
type Instruction = (char, usize);
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
struct Point {
x: isize,
y: isize,
}
impl Point {
fn touching(&self, other: &Self) -> bool {
let x_distance = self.x - other.x;
let y_distance = self.y - other.y;
(-1..=1).contains(&x_distance) && (-1..=1).contains(&y_distance)
}
}
fn parse_instructions(input: &str) -> Vec<Instruction> {
input
.lines()
.map(|line| {
// split at 2, so we get the direction and a space in the first part
// since we use chars().next() for extracting the direction there which
// will trim the space
let (c, n) = line.split_at(2);
(c.chars().next().unwrap(), n.parse().unwrap())
})
.collect()
}
fn do_the_thing(input: &str) -> usize {
let instructions = parse_instructions(input);
let mut rope = [Point::default(); ROPE_LENGTH];
let mut tail_positions = HashSet::<Point>::new();
for (direction, distance) in instructions {
for _ in 0..distance {
match direction {
'U' => rope[0].y += 1,
'D' => rope[0].y -= 1,
'R' => rope[0].x += 1,
'L' => rope[0].x -= 1,
_ => panic!("Unknown direction"),
}
let mut previous_knot = None;
for current_knot in &mut rope {
if let Some(previous_knot) = previous_knot {
if !current_knot.touching(&previous_knot) {
match current_knot.x.cmp(&previous_knot.x) {
std::cmp::Ordering::Less => current_knot.x += 1,
std::cmp::Ordering::Greater => current_knot.x -= 1,
std::cmp::Ordering::Equal => (),
};
match current_knot.y.cmp(&previous_knot.y) {
std::cmp::Ordering::Less => current_knot.y += 1,
std::cmp::Ordering::Greater => current_knot.y -= 1,
std::cmp::Ordering::Equal => (),
};
}
}
previous_knot = Some(*current_knot);
}
tail_positions.insert(rope[ROPE_LENGTH - 1]);
}
}
tail_positions.len()
}
fn main() {
let input = fs::read_to_string("input.txt").unwrap();
println!("{:?}", do_the_thing(&input));
}
#[cfg(test)]
mod tests {
use super::*;
use test_case::test_case;
#[test_case("R 4
U 4
L 3
D 1
R 4
D 1
L 5
R 2
" => 1)]
#[test_case("R 5
U 8
L 8
D 3
R 17
D 10
L 25
U 20" => 36)]
fn test(input: &str) -> usize {
do_the_thing(&input)
}
}
|
use perseus::{define_app, ErrorPages, Template};
use std::rc::Rc;
use sycamore::template;
define_app! {
templates: [
Template::<G>::new("index").template(Rc::new(|_| {
template! {
p { "Hello World!" }
}
}))
],
error_pages: ErrorPages::new(Rc::new(|url, status, err, _| {
template! {
p { (format!("An error with HTTP code {} occurred at '{}': '{}'.", status, url, err)) }
}
}))
}
|
//! This module defines the `System.Core` namespace, imported by default in every binder.
use binder::Binder;
use symbols::Sym;
use vm::{Vm, VirtualMachine};
use std::mem;
lazy_static! {
static ref SYSCORE_SYMBOL: Sym = {
Sym::from("System.Prelude")
};
}
/// Imports all core parsers in the given virtual machine.
pub fn import_parsers(_vm: &mut VirtualMachine) {
}
/// Imports all core types in the given virtual machine.
pub fn import_types(_vm: &mut VirtualMachine) {
}
/// Imports all core functions in the given virtual machine.
pub fn import_functions(vm: &mut VirtualMachine) {
let core = &*SYSCORE_SYMBOL;
mkfun!(fun, vm, core, $);
fun!("System.Void" "__Import", ("System.String" _namespace), _builder => {
unimplemented!()
});
}
/// Initializes the given binder, importing the `System.Prelude` namespace.
pub fn initialize<'cx, 'vm: 'cx>(binder: &mut Binder<'cx, 'vm>, vm: Vm<'vm>) {
let vm = vm.read();
let ctx = vm.context();
unsafe {
binder.import_tree(mem::transmute(ctx.members().lookup(&Sym::from("System")).unwrap()));
binder.import_tree(mem::transmute(ctx.members().lookup(&*SYSCORE_SYMBOL).unwrap()));
}
}
|
use std::sync::{Mutex, Arc};
use std::thread;
use std::rc::Rc;
fn hello_mutex() {
let m = Mutex::new(5);
{
let mut num = m.lock().unwrap();
*num = 6;
}
println!("hello mutex: {:?}", m);
}
// won't work - closure takes ownership on first iteration
fn shared_mutex_broken() {
let counter = Mutex::new(0);
// let mut handles = vec![];
// We have a loop here; and the closure takes ownership of values used
// inside it. We have one closure per iteration; this means that the first
// closure will take ownership of `counter`, and the following ones are
// unable to use it - resulting in an error. Commenting out the whole thing,
// because Rust will not compile such code, even if it's not invoked.
// for _ in 0..10 {
// let handle = thread::spawn(move || {
// let mut num = counter.lock().unwrap();
// *num += 1;
// });
// handles.push(handle);
// }
// for handle in handles {
// handle.join().unwrap();
// }
println!("Result: {}", *counter.lock().unwrap());
}
// won't work - Rc is not thread-safe
fn shared_mutex_also_broken() {
// let counter = Rc::new(Mutex::new(0));
// let mut handles = vec![];
// for _ in 0..10 {
// let counter = Rc::clone(&counter);
// // Fails with E0277 - required trait not implemented. The unimplemented
// // trait is `std::marker::Send`:
// // https://doc.rust-lang.org/std/marker/trait.Send.html "Types that can
// // be transferred across thread boundaries." Each thread gets a clone,
// // which works around the previous issue - but, all clones point to the
// // same underlying value; it is a pointer, after all. This is not safe,
// // because Rc doesn't use atomic operations.
// let handle = thread::spawn(move || {
// let mut num = counter.lock().unwrap();
// *num += 1;
// });
// handles.push(handle);
// }
// for handle in handles {
// handle.join().unwrap();
// }
// println!("Result: {}", *counter.lock().unwrap());
}
fn shared_mutex() {
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..10 {
let counter = Arc::clone(&counter);
let handle = thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Shared mutex result: {}", *counter.lock().unwrap());
}
fn main() {
hello_mutex();
shared_mutex();
}
|
pub fn a_echo() {
println!("a_echo");
}
|
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT license.
*/
use log::{debug, info, log_enabled, warn, Level};
use logger::trace_logger::TraceLogger;
// cargo run --example trace_example
fn main() {
static LOGGER: TraceLogger = TraceLogger {};
log::set_logger(&LOGGER)
.map(|()| log::set_max_level(log::LevelFilter::Trace))
.unwrap();
info!("Rust logging n = {}", 42);
warn!("This is too much fun!");
debug!("Maybe we can make this code work");
let error_is_enabled = log_enabled!(Level::Error);
let warn_is_enabled = log_enabled!(Level::Warn);
let info_is_enabled = log_enabled!(Level::Info);
let debug_is_enabled = log_enabled!(Level::Debug);
let trace_is_enabled = log_enabled!(Level::Trace);
println!(
"is_enabled? error: {:5?}, warn: {:5?}, info: {:5?}, debug: {:5?}, trace: {:5?}",
error_is_enabled, warn_is_enabled, info_is_enabled, debug_is_enabled, trace_is_enabled,
);
}
|
extern crate project_euler;
fn main() {
println!(
"Problem 1: {}",
project_euler::multiples_of_3_and_5::solve(1000)
);
println!(
"Problem 2: {}",
project_euler::even_fibonacci::solve(4_000_000)
);
println!(
"Problem 3: {}",
project_euler::largest_prime_factor::largest_prime_factor(&mut 600851475143)
);
}
|
extern crate ted_net_client;
extern crate ted_gui;
use ted_net_client as tedn;
use std::thread;
fn main(){
let mut args: Vec<String>=std::env::args().collect();
let address=if args.len()>1 {args.remove(1)} else {"127.0.0.1".to_string()};
let connection=tedn::connect(address);
let tcp_stream=connection.tcp_stream;
let frame_sender=connection.frame_sender;
let command_receiver=connection.command_receiver;
let frame_receiver=connection.frame_receiver;
let command_sender=connection.command_sender;
let handshake=connection.handshake;
thread::spawn(||tedn::net_thread(tcp_stream, frame_sender, command_receiver));
ted_gui::gui_thread(frame_receiver, command_sender, handshake);
}
|
use anyhow::Result;
use itertools::Itertools;
use std::fs;
fn do_the_thing(input: &str) -> Result<usize> {
let mut joltages = input
.lines()
.map(|n| n.parse::<usize>().unwrap())
.sorted()
.collect::<Vec<_>>();
joltages.insert(0, 0);
joltages.push(joltages.last().unwrap() + 3);
let (ones, threes, _) =
joltages
.into_iter()
.fold((0, 0, 0), |(mut ones, mut threes, previous), current| {
match current - previous {
1 => ones += 1,
3 => threes += 1,
_ => (),
}
(ones, threes, current)
});
Ok(ones * threes)
}
fn main() -> Result<()> {
let input = fs::read_to_string("input.txt")?;
println!("{:?}", do_the_thing(&input)?);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use test_case::test_case;
#[test_case("16
10
15
5
1
11
7
19
6
12
4" => 35; "short example")]
#[test_case("28
33
18
42
31
14
46
20
48
47
24
23
49
45
19
38
39
11
1
32
25
35
8
17
7
9
4
2
34
10
3" => 220; "long example")]
fn first(input: &str) -> usize {
do_the_thing(&input).unwrap()
}
}
|
#[macro_use]
extern crate log;
extern crate wasi_common;
extern crate wasmtime;
extern crate wasmtime_wasi;
extern crate websocket;
use std::io::Cursor;
use std::sync::mpsc;
use std::sync::{Arc, Mutex, RwLock};
use std::thread;
use std::vec::Vec;
use wasi_common::virtfs::pipe::{ReadPipe, WritePipe};
use wasmtime::*;
use wasmtime_wasi::{Wasi, WasiCtxBuilder};
use websocket::sync::Server;
use websocket::OwnedMessage;
fn main() {
env_logger::init();
let (dispatcher_tx, dispatcher_rx) = mpsc::channel::<String>();
let client_senders: Arc<Mutex<Vec<mpsc::Sender<websocket::OwnedMessage>>>> =
Arc::new(Mutex::new(vec![]));
// bind to the server
let server = Server::bind("127.0.0.1:2794").unwrap();
// Dispatcher thread
{
let client_senders = client_senders.clone();
thread::spawn(move || {
let pipe_stdout = Arc::new(RwLock::new(Cursor::new(vec![])));
let pipe_stdin = Arc::new(RwLock::new(Cursor::new(vec![])));
let store = Store::default();
let mut linker = Linker::new(&store);
let wasi_ctx = WasiCtxBuilder::new()
.inherit_args()
.inherit_env()
.stdin(ReadPipe::from_shared(pipe_stdin.clone()))
.stdout(WritePipe::from_shared(pipe_stdout.clone()))
.inherit_stderr()
.build()
.expect("Unable to build WasiCtx");
let wasi = Wasi::new(&store, wasi_ctx);
wasi.add_to_linker(&mut linker)
.expect("Unable to add linker");
// Instantiate our module with the imports we've created, and run it.
let module = Module::from_file(store.engine(), "plugin.wasm")
.expect("Unable to load plugin.wasm");
linker.module("", &module).unwrap();
let add_emoji = linker
.get_one_by_name("", "add_emoji")
.expect("Unable to find symbol")
.into_func()
.expect("Unable to convert into a function")
.get0::<()>()
.expect("Unable to specify the signature");
while let Ok(msg) = dispatcher_rx.recv() {
debug!("Dispatcher thread receive message: {}", msg);
{
let mut guard = pipe_stdin.write().expect("Unable to get lock");
guard.get_mut().clear();
guard.get_mut().extend_from_slice(msg.as_bytes());
guard.set_position(0);
}
add_emoji().expect("Unable to call add_emoji");
let new_msg = {
let mut guard = pipe_stdout.write().expect("Unable to get lock");
let msg = String::from_utf8(guard.get_ref().to_vec())
.expect("Unable to create a string");
guard.get_mut().clear();
guard.set_position(0);
msg
};
for sender in client_senders.lock().expect("Unable to get lock").iter() {
let message = OwnedMessage::Text(new_msg.clone());
let _ = sender.send(message);
}
}
});
}
for request in server.filter_map(Result::ok) {
let dispatcher = dispatcher_tx.clone();
let (client_tx, client_rx) = mpsc::channel();
client_senders.lock().unwrap().push(client_tx.clone());
// Spawn a new thread for each connection.
thread::spawn(move || {
if !request.protocols().contains(&"rust-websocket".to_string()) {
request.reject().unwrap();
return;
}
let client = request.use_protocol("rust-websocket").accept().unwrap();
let ip = client.peer_addr().unwrap();
debug!("Establish connection to {}", ip);
let (mut receiver, mut sender) = client.split().unwrap();
// thread to handle all outgoing messages
thread::spawn(move || {
while let Ok(msg) = client_rx.recv() {
if sender.send_message(&msg).is_err() {
return;
}
}
});
for message in receiver.incoming_messages() {
let message = message.unwrap();
match message {
OwnedMessage::Close(_) => {
let message = OwnedMessage::Close(None);
client_tx.send(message).unwrap();
debug!("Client {} disconnected", ip);
return;
}
OwnedMessage::Ping(ping) => {
let message = OwnedMessage::Pong(ping);
client_tx.send(message).unwrap();
}
OwnedMessage::Text(msg) => {
dispatcher.send(msg).unwrap();
}
_ => {}
}
}
});
}
}
|
use std;
use meow;
/*
Function: all
Return true if a predicate matches all characters
If the string contains no characters
*/
fn all(ss: str, ff: fn&(char) -> bool) -> bool {
str::loop_chars(ss, ff)
}
/*
Function: map
Apply a function to each character
*/
fn map(ss: str, ff: fn&(char) -> char) -> str {
let result = "";
str::iter_chars(ss, {|cc|
str::push_char(result, ff(cc));
});
ret result;
}
fn map_reserve(ss: str, ff: fn&(char) -> char) -> str {
let result = "";
str::reserve(result, str::byte_len(ss));
str::iter_chars(ss, {|cc|
str::push_char(result, ff(cc));
});
ret result;
}
#[test]
fn test_map () {
assert "" == map("", char::to_upper);
assert "YMCA" == map("ymca", char::to_upper);
}
#[test]
fn test_all () {
assert true == all("", char::is_uppercase);
assert false == all("ymca", char::is_uppercase);
assert true == all("YMCA", char::is_uppercase);
assert false == all("yMCA", char::is_uppercase);
assert false == all("YMCy", char::is_uppercase);
}
fn main () {
let ff = bind map(_,char::to_upper);
let gg = bind map_reserve(_,char::to_upper);
fn ff_ () { map(meow::sample_string(), char::to_upper); }
fn gg_ () { map_reserve(meow::sample_string(), char::to_upper); }
meow::compare("map vs. map_reserve", ff_, gg_);
meow::compare_several("map vs. map_reserve", ff_, gg_);
meow::compare_sweep_strings("map vs. map_reserve", ff, gg, 0u, 500000u);
/* EXAMPLE RUN:
$ rustc -O meow.rc
$ rustc -L . -O mapping.rs
$ ./mapping
meow: map vs. map_reserve: 0.939 ms, 0.952 ms
meow: map vs. map_reserve (avg): 0.707 ms, 0.730 ms
meow: Sweeping across strings of 0 to 500000 (5 tests per step)...
meow: map vs. map_reserve (0): 0.001 ms, 0.001 ms
meow: map vs. map_reserve (50000): 12.584 ms, 12.204 ms
meow: map vs. map_reserve (100000): 25.159 ms, 24.888 ms
meow: map vs. map_reserve (150000): 37.548 ms, 37.828 ms
meow: map vs. map_reserve (200000): 50.871 ms, 50.242 ms
meow: map vs. map_reserve (250000): 62.277 ms, 62.541 ms
meow: map vs. map_reserve (300000): 74.354 ms, 74.836 ms
meow: map vs. map_reserve (350000): 87.435 ms, 87.176 ms
meow: map vs. map_reserve (400000): 100.788 ms, 100.492 ms
meow: map vs. map_reserve (450000): 110.858 ms, 111.869 ms
meow: map vs. map_reserve (500000): 125.730 ms, 125.049 ms
*/
}
|
fn main() {
let mut x = 100;
let r1 = &x;
let r2 = &x; // ok: multiple shared borrows permitted
x += 10; // error: cannot assign to x because it's borrowed
let m = &mut x; // error: cannot borrow x as mutable because it's already borrowed as immutable
let mut y = 100;
let s1 = &mut y;
let s2 = &mut y; // error: cannot borrow mutable more than once
let z = y; // error: cannot use because it's mutably borrowed
let mut t = (1, 2);
let t1 = &t;
let t0 = &t.0; // ok: reborrowing shared as shared
let t2 = &mut t.1; // error: cant reborrow shared as mutable
let mut u = (1, 2);
let u1 = &u;
let u0 = &mut u.0; // ok: reborrowing mutable from mutable
*u0 = 11;
let ux = &u1.1; // ok: reborrow shared from mutable and doesnt overlap with u0
u.1; // error: access through other paths is forbidden
}
|
use structopt::StructOpt;
use std::{process::{Command, Stdio, Child}};
use std::fs::{self, File, DirEntry};
use std::io::{self, BufReader, Read};
use std::path::{Path, PathBuf};
use serde::Deserialize;
use notify::{Watcher, RecursiveMode, watcher, DebouncedEvent };
use std::sync::mpsc::{channel, Receiver, Sender};
use std::time::Duration;
use std::time::{SystemTime, UNIX_EPOCH};
use std::thread::{self, JoinHandle};
use uuid::Uuid;
use rcgen::{Certificate, CertificateParams};
use std::env;
use brotli::{BrotliCompress, enc::backward_references::BrotliEncoderParams};
use flate2::Compression;
use flate2::bufread::GzEncoder;
#[derive(Debug, StructOpt)]
enum Opt {
New { project_name: String },
Start {
#[structopt(short, long)]
release: bool,
// #[structopt(short, long)]
// open: bool
},
Build {
#[structopt(short, long)]
release: bool,
},
}
// Run from example: cargo run --manifest-path "../../crates/mzoon/Cargo.toml" start
fn main() {
let (frontend_sender, frontend_receiver) = channel();
let (backend_sender, backend_receiver) = channel();
ctrlc::set_handler({
let frontend_sender = frontend_sender.clone();
let backend_sender = backend_sender.clone();
move || {
println!("Shut down MoonZoon CLI");
let event = || DebouncedEvent::Error(notify::Error::Generic("ctrl-c".to_owned()), None);
frontend_sender.send(event()).unwrap();
backend_sender.send(event()).unwrap();
}
}).unwrap();
let opt = Opt::from_args();
println!("{:?}", opt);
match opt {
Opt::New { .. } => {},
Opt::Start { release } => {
let config = load_config();
set_env_vars(&config, release);
check_wasm_pack();
if config.https {
generate_certificate();
}
let (frontend_build_finished_sender, frontend_build_finished_receiver) = channel();
let frontend_watcher_handle = start_frontend_watcher(
config.watch.frontend.clone(),
release,
frontend_sender,
frontend_receiver,
frontend_build_finished_sender,
&config,
);
// @TODO parallel build instead of waiting (server has to be started after FE build!)
// `recv` fails if the sender is dropped because of fail in `start_frontend_watcher`
let _ = frontend_build_finished_receiver.recv();
let backend_watcher_handle = start_backend_watcher(
config.watch.backend.clone(),
release,
// open,
backend_sender,
backend_receiver,
);
frontend_watcher_handle.join().unwrap();
backend_watcher_handle.join().unwrap();
},
Opt::Build { release } => {
let config = load_config();
set_env_vars(&config, release);
check_wasm_pack();
if config.https {
generate_certificate();
}
if !build_frontend(release, config.cache_busting) {
panic!("Build frontend failed!");
}
if !build_backend(release) {
panic!("Build backend failed!");
}
},
}
}
fn load_config() -> Config {
let toml = fs::read_to_string("MoonZoon.toml").unwrap();
toml::from_str(&toml).unwrap()
}
fn set_env_vars(config: &Config, release: bool) {
// port = 8443
env::set_var("PORT", config.port.to_string());
// https = true
env::set_var("HTTPS", config.https.to_string());
// [redirect_server]
// port = 8080
env::set_var("REDIRECT_SERVER__PORT", config.redirect_server.port.to_string());
// enabled = true
env::set_var("REDIRECT_SERVER__ENABLED", config.redirect_server.enabled.to_string());
env::set_var("COMPRESSED_PKG", release.to_string());
}
#[derive(Debug, Deserialize)]
struct Config {
port: u16,
https: bool,
cache_busting: bool,
redirect_server: RedirectServer,
watch: Watch,
}
#[derive(Debug, Deserialize)]
struct RedirectServer {
port: u16,
enabled: bool,
}
#[derive(Debug, Deserialize)]
struct Watch {
frontend: Vec<String>,
backend: Vec<String>,
}
fn check_wasm_pack() {
let status = Command::new("wasm-pack")
.args(&["-V"])
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
match status {
Ok(status) if status.success() => (),
_ => panic!("Cannot find `wasm-pack`! Please install it by `cargo install wasm-pack` or download/install pre-built binaries into a globally available directory."),
}
}
fn generate_certificate() {
let public_pem_path = Path::new("backend/private/public.pem");
let private_pem_path = Path::new("backend/private/private.pem");
if public_pem_path.is_file() && private_pem_path.is_file() {
return;
}
println!("Generate TLS certificate");
let domains = vec!["localhost".to_owned()];
let mut params = CertificateParams::new(domains);
// https://support.mozilla.org/en-US/kb/Certificate-contains-the-same-serial-number-as-another-certificate
let since_the_epoch = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();
params.serial_number = Some(since_the_epoch);
let certificate = Certificate::from_params(params).unwrap();
let public_pem = certificate.serialize_pem().unwrap();
let private_pem = certificate.serialize_private_key_pem();
fs::write(public_pem_path, public_pem).unwrap();
fs::write(private_pem_path, private_pem).unwrap();
}
fn start_frontend_watcher(
paths: Vec<String>,
release: bool,
sender: Sender<DebouncedEvent>,
receiver: Receiver<DebouncedEvent>,
frontend_build_finished_sender: Sender<()>,
config: &Config,
) -> JoinHandle<()> {
let reload_url = format!(
"{protocol}://localhost:{port}/api/reload",
protocol = if config.https { "https" } else { "http" },
port = config.port
);
let cache_busting = config.cache_busting;
thread::spawn(move || {
let mut watcher = watcher(sender, Duration::from_millis(100)).unwrap();
for path in paths {
watcher.watch(&path, RecursiveMode::Recursive).unwrap();
}
build_frontend(release, cache_busting);
frontend_build_finished_sender.send(()).unwrap();
loop {
match receiver.recv() {
Ok(event) => match event {
DebouncedEvent::NoticeWrite(_) | DebouncedEvent:: NoticeRemove(_) => (),
DebouncedEvent::Error(notify::Error::Generic(error), _) if error == "ctrl-c" => break,
_ => {
println!("Build frontend");
if build_frontend(release, cache_busting) {
println!("Reload frontend");
attohttpc::post(&reload_url)
.danger_accept_invalid_certs(true)
.send()
.unwrap();
}
}
},
Err(error) => panic!("watch frontend error: {:?}", error),
}
}
})
}
enum BackendCommand {
Rebuild,
Stop,
}
fn start_backend_watcher(
paths: Vec<String>,
release: bool,
// open: bool,
sender: Sender<DebouncedEvent>,
receiver: Receiver<DebouncedEvent>
) -> JoinHandle<()> {
thread::spawn(move || {
let mut watcher = watcher(sender, Duration::from_millis(100)).unwrap();
for path in paths {
watcher.watch(&path, RecursiveMode::Recursive).unwrap();
}
let (server_rebuild_run_sender, server_rebuild_run_receiver) = channel();
let backend_handle = thread::spawn(move || {
// let mut open = open;
loop {
// @TODO only on successful build
generate_backend_build_id();
let mut cargo_and_server_process = build_and_run_backend(release);
// @TODO wait for (successful) build
// if open {
// open = false;
// let address = "https://127.0.0.1:8443";
// println!("Open {} in your default web browser", "https://127.0.0.1:8443");
// open::that(address).unwrap();
// }
let command = server_rebuild_run_receiver.recv();
match command {
Ok(BackendCommand::Rebuild) => {
let _ = cargo_and_server_process.kill();
},
Ok(BackendCommand::Stop) => {
cargo_and_server_process.wait().unwrap();
break
},
Err(error) => {
println!("watch backend error: {:?}", error);
break
}
}
}
});
loop {
match receiver.recv() {
Ok(event) => match event {
DebouncedEvent::NoticeWrite(_) | DebouncedEvent:: NoticeRemove(_) => (),
DebouncedEvent::Error(notify::Error::Generic(error), _) if error == "ctrl-c" => {
let _ = server_rebuild_run_sender.send(BackendCommand::Stop);
backend_handle.join().unwrap();
return
},
_ => {
println!("Build backend");
if server_rebuild_run_sender.send(BackendCommand::Rebuild).is_err() {
return
}
}
},
Err(error) => {
println!("watch backend error: {:?}", error);
return
},
}
}
})
}
fn generate_backend_build_id() {
fs::write("backend/private/build_id", Uuid::new_v4().as_u128().to_string()).unwrap();
}
fn build_frontend(release: bool, cache_busting: bool) -> bool {
let old_build_id = fs::read_to_string("frontend/pkg/build_id")
.ok()
.map(|uuid| {
uuid.parse::<u128>().map(|uuid| uuid).unwrap_or_default()
});
if let Some(old_build_id) = old_build_id {
let old_wasm = format!("frontend/pkg/frontend_bg_{}.wasm", old_build_id);
let old_js = format!("frontend/pkg/frontend_{}.js", old_build_id);
let _ = fs::remove_file(&old_wasm);
let _ = fs::remove_file(&old_js);
let _ = fs::remove_file(format!("{}.br", &old_wasm));
let _ = fs::remove_file(format!("{}.br", &old_js));
let _ = fs::remove_file(format!("{}.gz", &old_wasm));
let _ = fs::remove_file(format!("{}.gz", &old_js));
// @TODO replace with the crate with more reliable removing on Windows?
let _ = fs::remove_dir_all("frontend/pkg/snippets");
}
let mut args = vec![
"--log-level", "warn", "build", "frontend", "--target", "web", "--no-typescript",
];
if !release {
args.push("--dev");
}
let success = Command::new("wasm-pack")
.args(&args)
.status()
.unwrap()
.success();
if success {
let build_id = cache_busting
.then(|| Uuid::new_v4().as_u128())
.unwrap_or_default();
let wasm_file_path = Path::new("frontend/pkg/frontend_bg.wasm");
let new_wasm_file_path = PathBuf::from(format!("frontend/pkg/frontend_bg_{}.wasm", build_id));
let js_file_path = Path::new("frontend/pkg/frontend.js");
let new_js_file_path = PathBuf::from(format!("frontend/pkg/frontend_{}.js", build_id));
fs::rename(wasm_file_path, &new_wasm_file_path).unwrap();
fs::rename(js_file_path, &new_js_file_path).unwrap();
fs::write("frontend/pkg/build_id", build_id.to_string()).unwrap();
if release {
compress_pkg(&new_wasm_file_path, &new_js_file_path);
}
}
success
}
fn compress_pkg(wasm_file_path: &Path, js_file_path: &Path) {
compress_file(wasm_file_path);
compress_file(js_file_path);
visit_dirs(Path::new("frontend/pkg/snippets"), &mut |entry: &DirEntry| {
compress_file(&entry.path());
}).unwrap();
}
// @TODO refactor with https://crates.io/crates/async-compression
fn compress_file(file_path: &Path) {
BrotliCompress(
&mut File::open(&file_path).unwrap(),
&mut File::create(&format!("{}.br", file_path.to_str().unwrap())).unwrap(),
&BrotliEncoderParams::default()
).unwrap();
let file_reader = BufReader::new(File::open(&file_path).unwrap());
let mut gzip_encoder = GzEncoder::new(file_reader, Compression::best());
let mut buffer = Vec::new();
gzip_encoder.read_to_end(&mut buffer).unwrap();
fs::write(&format!("{}.gz", file_path.to_str().unwrap()), buffer).unwrap();
}
fn visit_dirs(dir: &Path, cb: &mut dyn FnMut(&DirEntry)) -> io::Result<()> {
if dir.is_dir() {
for entry in fs::read_dir(dir)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
visit_dirs(&path, cb)?;
} else {
cb(&entry);
}
}
}
Ok(())
}
fn build_and_run_backend(release: bool) -> Child {
let mut args = vec![
"run", "--package", "backend",
];
if release {
args.push("--release");
}
Command::new("cargo")
.args(&args)
.spawn()
.unwrap()
}
fn build_backend(release: bool) -> bool {
let mut args = vec![
"build", "--package", "backend",
];
if release {
args.push("--release");
}
let success = Command::new("cargo")
.args(&args)
.status()
.unwrap()
.success();
if success {
generate_backend_build_id();
}
success
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct HC {
#[doc = "0x00 - OTG_FS host channel-0 characteristics register (OTG_FS_HCCHAR0)"]
pub char: CHAR,
_reserved1: [u8; 0x04],
#[doc = "0x08 - OTG_FS host channel-0 interrupt register (OTG_FS_HCINT0)"]
pub int: INT,
#[doc = "0x0c - OTG_FS host channel-0 mask register (OTG_FS_HCINTMSK0)"]
pub intmsk: INTMSK,
#[doc = "0x10 - OTG_FS host channel-0 transfer size register"]
pub tsiz: TSIZ,
_reserved_end: [u8; 0x0c],
}
#[doc = "CHAR (rw) register accessor: OTG_FS host channel-0 characteristics register (OTG_FS_HCCHAR0)\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`char::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 [`char::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`char`]
module"]
pub type CHAR = crate::Reg<char::CHAR_SPEC>;
#[doc = "OTG_FS host channel-0 characteristics register (OTG_FS_HCCHAR0)"]
pub mod char;
#[doc = "INT (rw) register accessor: OTG_FS host channel-0 interrupt register (OTG_FS_HCINT0)\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`int::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 [`int::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`int`]
module"]
pub type INT = crate::Reg<int::INT_SPEC>;
#[doc = "OTG_FS host channel-0 interrupt register (OTG_FS_HCINT0)"]
pub mod int;
#[doc = "INTMSK (rw) register accessor: OTG_FS host channel-0 mask register (OTG_FS_HCINTMSK0)\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`intmsk::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 [`intmsk::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`intmsk`]
module"]
pub type INTMSK = crate::Reg<intmsk::INTMSK_SPEC>;
#[doc = "OTG_FS host channel-0 mask register (OTG_FS_HCINTMSK0)"]
pub mod intmsk;
#[doc = "TSIZ (rw) register accessor: OTG_FS host channel-0 transfer size register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tsiz::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 [`tsiz::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tsiz`]
module"]
pub type TSIZ = crate::Reg<tsiz::TSIZ_SPEC>;
#[doc = "OTG_FS host channel-0 transfer size register"]
pub mod tsiz;
|
#[cfg(test)]
#[path = "../../../../tests/unit/solver/mutation/ruin/route_removal_test.rs"]
mod route_removal_test;
use super::*;
use crate::construction::heuristics::{group_routes_by_proximity, InsertionContext, RouteContext, SolutionContext};
use crate::models::problem::Job;
use crate::solver::RefinementContext;
/// A ruin strategy which removes random route from solution.
pub struct RandomRouteRemoval {
/// Specifies minimum amount of removed routes.
min: f64,
/// Specifies maximum amount of removed routes.
max: f64,
/// Specifies threshold ratio of maximum removed routes.
threshold: f64,
}
impl RandomRouteRemoval {
/// Creates a new instance of `RandomRouteRemoval`.
pub fn new(rmin: usize, rmax: usize, threshold: f64) -> Self {
Self { min: rmin as f64, max: rmax as f64, threshold }
}
}
impl Default for RandomRouteRemoval {
fn default() -> Self {
Self::new(1, 4, 0.1)
}
}
impl Ruin for RandomRouteRemoval {
fn run(&self, _refinement_ctx: &RefinementContext, mut insertion_ctx: InsertionContext) -> InsertionContext {
let random = insertion_ctx.environment.random.clone();
let max = (insertion_ctx.solution.routes.len() as f64 * self.threshold).max(self.min).round() as usize;
let affected = random
.uniform_int(self.min as i32, self.max as i32)
.min(insertion_ctx.solution.routes.len().min(max) as i32) as usize;
(0..affected).for_each(|_| {
let route_index = random.uniform_int(0, (insertion_ctx.solution.routes.len() - 1) as i32) as usize;
let solution = &mut insertion_ctx.solution;
let route_ctx = &mut solution.routes.get(route_index).unwrap().clone();
remove_route(solution, route_ctx)
});
insertion_ctx
}
}
/// Removes two random, close to each other, routes from solution.
pub struct CloseRouteRemoval {}
impl Default for CloseRouteRemoval {
fn default() -> Self {
Self {}
}
}
impl Ruin for CloseRouteRemoval {
// NOTE clippy's false positive in route_groups_distances loop
#[allow(clippy::needless_collect)]
fn run(&self, _refinement_ctx: &RefinementContext, mut insertion_ctx: InsertionContext) -> InsertionContext {
if let Some(route_groups_distances) = group_routes_by_proximity(&insertion_ctx) {
let random = &insertion_ctx.environment.random;
let stale_routes = insertion_ctx
.solution
.routes
.iter()
.enumerate()
.filter_map(|(idx, route)| if route.is_stale() { Some(idx) } else { None })
.collect::<Vec<_>>();
let route_index = if !stale_routes.is_empty() && random.is_head_not_tails() {
stale_routes[random.uniform_int(0, (stale_routes.len() - 1) as i32) as usize]
} else {
random.uniform_int(0, (route_groups_distances.len() - 1) as i32) as usize
};
let routes = route_groups_distances[route_index]
.iter()
.take(2)
.filter_map(|(idx, _)| insertion_ctx.solution.routes.get(*idx).cloned())
.collect::<Vec<_>>();
routes.into_iter().for_each(|mut route_ctx| {
remove_route(&mut insertion_ctx.solution, &mut route_ctx);
});
}
insertion_ctx
}
}
fn remove_route(solution: &mut SolutionContext, route_ctx: &mut RouteContext) {
if solution.locked.is_empty() {
remove_whole_route(solution, route_ctx);
} else {
remove_part_route(solution, route_ctx);
}
}
fn remove_whole_route(solution: &mut SolutionContext, route_ctx: &RouteContext) {
solution.routes.retain(|rc| rc != route_ctx);
solution.registry.free_route(&route_ctx);
solution.required.extend(route_ctx.route.tour.jobs());
}
fn remove_part_route(solution: &mut SolutionContext, route_ctx: &mut RouteContext) {
let locked = solution.locked.clone();
let can_remove_full_route = route_ctx.route.tour.jobs().all(|job| !locked.contains(&job));
if can_remove_full_route {
remove_whole_route(solution, route_ctx);
} else {
{
let jobs: Vec<Job> = route_ctx.route.tour.jobs().filter(|job| !locked.contains(job)).collect();
jobs.iter().for_each(|job| {
route_ctx.route_mut().tour.remove(job);
});
solution.required.extend(jobs);
}
}
}
|
/*
* 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
*/
/// SloType : The type of the service level objective.
/// The type of the service level objective.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
pub enum SloType {
#[serde(rename = "metric")]
METRIC,
#[serde(rename = "monitor")]
MONITOR,
}
impl ToString for SloType {
fn to_string(&self) -> String {
match self {
Self::METRIC => String::from("metric"),
Self::MONITOR => String::from("monitor"),
}
}
}
|
use core::*;
use graphics::*;
use math::*;
use rand::*;
use std::collections::*;
use std::any::*;
struct Component1(f32);
struct Component2(i32, f64);
struct Component3(String, f64, f64, String);
struct NotRegistered(usize);
/// Checks the creation of a simple 3d world and respectively the add/get functionality.
/// Registers three components for two different entities.
#[test]
fn create_world() {
let mut w = World::new();
w.register::<Component1>();
w.register::<Component2>();
w.register_rare::<Component3>();
let entity1 = w.add_entity();
let entity2 = w.add_entity();
let c1 = Component1(4.5f32);
let c2 = Component2(5i32, 6f64);
let c3 = Component3("Test".to_string(), 0.3f64, 122f64, "End".to_string());
let nr = NotRegistered(5);
// should work
assert!(w.add_component(entity1, c1));
assert!(w.add_component(entity2, c2));
assert!(w.add_component(entity2, c3));
// should fail because nr is not registered
assert!(!w.add_component(entity2, nr));
// get components of each type, component 1-3 should be 1 in size
let cc1 = w.get_components::<Component1>();
let cc2 = w.get_components::<Component2>();
let cc3 = w.get_components::<Component3>();
let cnr = w.get_components::<NotRegistered>();
assert!(cc1.is_some() && cc2.is_some() && cc3.is_some() && cnr.is_none());
// component nr should give a failure on get
let cc1 = cc1.unwrap();
let cc2 = cc2.unwrap();
let cc3 = cc3.unwrap();
assert!(cc1.read().unwrap().len() == 1);
assert!(cc2.read().unwrap().len() == 1);
assert!(cc3.read().unwrap().len() == 1);
// add 2 components and mutate the first component
// check if all are dirty (3 in dirty list)
let entity3 = w.add_entity();
{
let mut cc1_write = cc1.write().unwrap();
cc1_write.get_dirty_mut().clear();
cc1_write.push(vec![(entity2, Component1(700f32)), (entity3, Component1(10f32))]);
let mut c1_guard: DirtyGuard<Component1> = cc1_write.get_mut(entity1).unwrap();
c1_guard.update(|ref mut c1| {
c1.0 = 42f32;
true
});
}
// test whether len is 3 here and at bottom to ensure that entities are not added a second time
assert!(cc1.read().unwrap().get_dirty().len() == 3);
assert!(cc1.read().unwrap().get(entity2).unwrap().0 == 700f32);
// try to override the Component1 of Entity2
cc1.write().unwrap().push(vec![(entity2, Component1(500.65f32))]);
assert!(cc1.read().unwrap().get(entity2).unwrap().0 == 500.65f32);
assert!(cc1.read().unwrap().get_dirty().len() == 3);
assert!(cc1.read().unwrap().get(entity1).unwrap().0 == 42f32);
}
/// Creates transform components, adds them to the world, manipulates them and
/// finally updates them by the TransformSystem.
#[test]
fn transform() {
let mut rng = thread_rng();
let mut w = World::new();
w.register::<Transform<f64>>();
let entities = w.add_entities(10);
// create a transform for each entity and parent a random entity to it
let mut components: Vec<(Entity, Transform<f64>)> = Vec::new();
for e in entities.clone().into_iter() {
let p = entities[rng.gen_range(0, entities.len()-1)];
let t = Transform::with_parent(Vector3::rand(), Quaternion::new(&Vector3::rand(), 5.0f64), Vector3::rand(), p);
components.push((e, t));
}
// ensure that the first entity has no parent and is the root
{
let (entity, ref mut transform) = components[0];
transform.clear_parent();
}
// shuffle in order to check the sorting algorithm
rng.shuffle(&mut components);
w.add_components(components);
w.add_system::<TransformSystem<f64>>();
w.run(5.0f64);
} |
// ===============================================================================
// Authors: AFRL/RQQA
// Organization: Air Force Research Laboratory, Aerospace Systems Directorate, Power and Control Division
//
// Copyright (c) 2017 Government of the United State of America, as represented by
// the Secretary of the Air Force. No copyright is claimed in the United States under
// Title 17, U.S. Code. All Other Rights Reserved.
// ===============================================================================
// This file was auto-created by LmcpGen. Modifications will be overwritten.
pub mod video_record;
pub mod startup_complete;
pub mod create_new_service;
pub mod kill_service;
pub mod increment_waypoint;
pub mod safe_heading_action;
pub mod entity_location;
pub mod bandwidth_test;
pub mod bandwidth_receive_report;
pub mod sub_task_execution;
pub mod sub_task_assignment;
pub mod autopilot_keep_alive;
pub mod onboard_status_report;
pub mod entity_join;
pub mod entity_exit;
pub mod simulation_time_step_acknowledgement;
pub mod speed_override_action;
|
use nanorand::RNG;
use pyo3::prelude::*;
#[pyclass]
#[derive(Default)]
pub struct ChaCha {
inner: nanorand::ChaCha,
}
#[pymethods]
impl ChaCha {
#[new]
pub fn new(rounds: u8) -> Self {
Self {
inner: nanorand::ChaCha::new(rounds),
}
}
#[staticmethod]
pub fn new_key(rounds: u8, key: [u8; 32], nonce: [u8; 8]) -> Self {
Self {
inner: nanorand::ChaCha::new_key(rounds, key, nonce),
}
}
#[staticmethod]
pub fn new_chacha8() -> Self {
Self {
inner: nanorand::ChaCha::new(8),
}
}
#[staticmethod]
pub fn new_chacha8_key(key: [u8; 32], nonce: [u8; 8]) -> Self {
Self {
inner: nanorand::ChaCha::new_key(8, key, nonce),
}
}
#[staticmethod]
pub fn new_chacha12() -> Self {
Self {
inner: nanorand::ChaCha::new(12),
}
}
#[staticmethod]
pub fn new_chacha12_key(key: [u8; 32], nonce: [u8; 8]) -> Self {
Self {
inner: nanorand::ChaCha::new_key(12, key, nonce),
}
}
#[staticmethod]
pub fn new_chacha20() -> Self {
Self {
inner: nanorand::ChaCha::new(20),
}
}
#[staticmethod]
pub fn new_chacha20_key(key: [u8; 32], nonce: [u8; 8]) -> Self {
Self {
inner: nanorand::ChaCha::new_key(20, key, nonce),
}
}
pub fn next_bytes(&mut self) -> Vec<u8> {
self.inner.rand().to_vec()
}
pub fn next_u8(&mut self) -> u8 {
self.inner.generate()
}
pub fn next_u16(&mut self) -> u16 {
self.inner.generate()
}
pub fn next_u32(&mut self) -> u32 {
self.inner.generate()
}
pub fn next_u64(&mut self) -> u64 {
self.inner.generate()
}
pub fn next_usize(&mut self) -> usize {
self.inner.generate()
}
pub fn next_bool(&mut self) -> bool {
self.inner.generate()
}
pub fn range_u8(&mut self, lower: u8, upper: u8) -> u8 {
self.inner.generate_range(lower, upper)
}
pub fn range_u16(&mut self, lower: u16, upper: u16) -> u16 {
self.inner.generate_range(lower, upper)
}
pub fn range_u32(&mut self, lower: u32, upper: u32) -> u32 {
self.inner.generate_range(lower, upper)
}
pub fn range_u64(&mut self, lower: u64, upper: u64) -> u64 {
self.inner.generate_range(lower, upper)
}
}
|
#[doc = "Reader of register RCC_CPERCKSELR"]
pub type R = crate::R<u32, super::RCC_CPERCKSELR>;
#[doc = "Writer for register RCC_CPERCKSELR"]
pub type W = crate::W<u32, super::RCC_CPERCKSELR>;
#[doc = "Register RCC_CPERCKSELR `reset()`'s with value 0"]
impl crate::ResetValue for super::RCC_CPERCKSELR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "CKPERSRC\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum CKPERSRC_A {
#[doc = "0: hsi_ker_ck clock selected (default\r\n after reset)"]
B_0X0 = 0,
#[doc = "1: csi_ker_ck clock\r\n selected"]
B_0X1 = 1,
#[doc = "2: hse_ker_ck clock\r\n selected"]
B_0X2 = 2,
#[doc = "3: Clock disabled"]
B_0X3 = 3,
}
impl From<CKPERSRC_A> for u8 {
#[inline(always)]
fn from(variant: CKPERSRC_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `CKPERSRC`"]
pub type CKPERSRC_R = crate::R<u8, CKPERSRC_A>;
impl CKPERSRC_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> CKPERSRC_A {
match self.bits {
0 => CKPERSRC_A::B_0X0,
1 => CKPERSRC_A::B_0X1,
2 => CKPERSRC_A::B_0X2,
3 => CKPERSRC_A::B_0X3,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `B_0X0`"]
#[inline(always)]
pub fn is_b_0x0(&self) -> bool {
*self == CKPERSRC_A::B_0X0
}
#[doc = "Checks if the value of the field is `B_0X1`"]
#[inline(always)]
pub fn is_b_0x1(&self) -> bool {
*self == CKPERSRC_A::B_0X1
}
#[doc = "Checks if the value of the field is `B_0X2`"]
#[inline(always)]
pub fn is_b_0x2(&self) -> bool {
*self == CKPERSRC_A::B_0X2
}
#[doc = "Checks if the value of the field is `B_0X3`"]
#[inline(always)]
pub fn is_b_0x3(&self) -> bool {
*self == CKPERSRC_A::B_0X3
}
}
#[doc = "Write proxy for field `CKPERSRC`"]
pub struct CKPERSRC_W<'a> {
w: &'a mut W,
}
impl<'a> CKPERSRC_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CKPERSRC_A) -> &'a mut W {
{
self.bits(variant.into())
}
}
#[doc = "hsi_ker_ck clock selected (default after reset)"]
#[inline(always)]
pub fn b_0x0(self) -> &'a mut W {
self.variant(CKPERSRC_A::B_0X0)
}
#[doc = "csi_ker_ck clock selected"]
#[inline(always)]
pub fn b_0x1(self) -> &'a mut W {
self.variant(CKPERSRC_A::B_0X1)
}
#[doc = "hse_ker_ck clock selected"]
#[inline(always)]
pub fn b_0x2(self) -> &'a mut W {
self.variant(CKPERSRC_A::B_0X2)
}
#[doc = "Clock disabled"]
#[inline(always)]
pub fn b_0x3(self) -> &'a mut W {
self.variant(CKPERSRC_A::B_0X3)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x03) | ((value as u32) & 0x03);
self.w
}
}
impl R {
#[doc = "Bits 0:1 - CKPERSRC"]
#[inline(always)]
pub fn ckpersrc(&self) -> CKPERSRC_R {
CKPERSRC_R::new((self.bits & 0x03) as u8)
}
}
impl W {
#[doc = "Bits 0:1 - CKPERSRC"]
#[inline(always)]
pub fn ckpersrc(&mut self) -> CKPERSRC_W {
CKPERSRC_W { w: self }
}
}
|
use std::fmt;
use std::fmt::Display;
const DEFAULT_HEIGHT: f32 = 14.0;
pub enum FontUnit {
Pixel,
Point,
}
impl Display for FontUnit {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self {
FontUnit::Pixel => write!(fmt, "px"),
FontUnit::Point => write!(fmt, "pt"),
}
}
}
#[derive(Clone, Debug)]
pub struct Font {
name: String,
pub height: f32,
}
impl Font {
/// Parses nvim `guifont` option.
///
/// If invalid height is specified, defaults to `DEFAULT_HEIGHT`.
pub fn from_guifont(guifont: &str) -> Result<Self, ()> {
let mut parts = guifont.split(':');
let name = parts.next().ok_or(())?;
if name.is_empty() {
return Err(());
}
let mut font = Font {
name: name.to_string(),
height: DEFAULT_HEIGHT,
};
for part in parts {
let mut chars = part.chars();
if let Some(ch) = chars.next() {
match ch {
'h' => {
let rest = chars.collect::<String>();
let h = rest.parse::<f32>().or(Err(()))?;
if h <= 0.0 {
// Ignore zero sized font.
continue;
}
font.height = h;
}
_ => {
println!("Not supported guifont option: {}", part);
}
}
}
}
Ok(font)
}
/// Returns a CSS representation of self for a wild (`*`) CSS selector.
/// On gtk version below 3.20 unit needs to be `FontUnit::Pixel` and
/// with version 3.20 and up, unit needs to be `FontUnit::Point`. This is
/// to work around some gtk issues on versions before 3.20.
pub fn as_wild_css(&self, unit: FontUnit) -> String {
format!(
"* {{ \
font-family: \"{font_family}\"; \
font-size: {font_size}{font_unit}; \
}}",
font_family = self.name,
font_size = self.height,
font_unit = unit,
)
}
/// Returns a pango::FontDescription version of self.
pub fn as_pango_font(&self) -> pango::FontDescription {
let mut font_desc = pango::FontDescription::from_string(&format!(
"{} {}",
self.name, self.height
));
// Make sure we dont have a font with size of 0, otherwise we'll
// have problems later.
if font_desc.get_size() == 0 {
font_desc.set_size(DEFAULT_HEIGHT as i32 * pango::SCALE);
}
font_desc
}
}
impl Default for Font {
fn default() -> Self {
Font {
name: String::from("Monospace"),
height: DEFAULT_HEIGHT,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_as_wild_css() {
let font = Font {
name: "foo".to_string(),
height: 10.0,
};
assert_eq!(
font.as_wild_css(FontUnit::Point),
"* { \
font-family: \"foo\"; \
font-size: 10pt; \
}"
);
assert_eq!(
font.as_wild_css(FontUnit::Pixel),
"* { \
font-family: \"foo\"; \
font-size: 10px; \
}"
);
}
#[test]
fn test_from_guifont() {
// Font with proper height.
let f = Font::from_guifont("monospace:h11").unwrap();
assert_eq!(f.name, "monospace");
assert_eq!(f.height, 11.0);
// Font with invalid height.
let f = Font::from_guifont("font:h");
assert_eq!(f.is_err(), true);
let f = Font::from_guifont("font:hn");
assert_eq!(f.is_err(), true);
// Font with height zero.
let f = Font::from_guifont("foo:h0").unwrap();
assert_eq!(f.name, "foo");
assert_eq!(f.height, DEFAULT_HEIGHT);
// Font with negative height.
let f = Font::from_guifont("font:h-1").unwrap();
assert_eq!(f.name, "font");
assert_eq!(f.height, DEFAULT_HEIGHT);
// Font with no height.
let f = Font::from_guifont("bar").unwrap();
assert_eq!(f.name, "bar");
assert_eq!(f.height, DEFAULT_HEIGHT);
}
}
|
use crate::models::{User};
use crate::data::{ContextBuilder, Context};
use crate::sql_mapper::{user_mapper};
use waiter_di::*;
use tokio_postgres::{Row, Error};
use async_trait::async_trait;
#[async_trait] // Interface
pub trait IDaoUser: Send{
async fn get_user(&mut self, email: String)->Result<User, ()>;
async fn create_user(&mut self, user: User) -> Result<(), ()>;
async fn delete_user(&mut self, email: &String)->Result<(),()>;
}
#[component]
pub struct DaoUser{}
#[provides]
#[async_trait]
impl IDaoUser for DaoUser{
async fn get_user(&mut self, email: String)->Result<User, ()>{
let context = ContextBuilder::new().await.unwrap();
let selection = context.client
.query("SELECT * FROM guids_users WHERE email = $1",
&[&email.as_str()]).await.unwrap();
if !selection.len() == 1 {
return Result::Err(())
}
Result::Ok(user_mapper(&selection[0]))
}
async fn create_user(&mut self, user: User) -> Result<(), ()> {
let context = ContextBuilder::new().await.unwrap();
let create = context.client
.query("INSERT INTO guids_users (UUID, login, pass, email, phone, name, notvalid)\
VALUES($1, $2, $3, $4, $5, $6, $7) RETURNING true",
&[&user.uuid, &user.login.as_str(),
&user.pass.as_str(),&user.email.as_str(),
&user.phone.as_str(), &user.name.as_str(), &user.notvalid]).await.unwrap();
if !create.is_empty() {
return Result::Ok(())
}
Result::Err(())
}
async fn delete_user(&mut self, email: &String)->Result<(),()>{
let context = ContextBuilder::new().await.unwrap();
let result = context.client
.query("DELETE FROM guids_users WHERE email = $1 RETURNING true",
&[email]).await.unwrap();
if !result.is_empty() {
return Result::Ok(())
}
Result::Err(())
}
}
|
use protoc_rust::Customize;
use std::path::Path;
fn main() {
let a = Path::new("src/proto").join("A").join("a.proto");
let b = Path::new("src/proto").join("B").join("b.proto");
protoc_rust::run(protoc_rust::Args {
out_dir: "src",
input: &[a.to_str().unwrap(),b.to_str().unwrap()],
includes: &["src/proto"],
customize: Customize {
..Default::default()
},
}).expect("protoc");
} |
use serenity::client::{Context, EventHandler};
use serenity::model::channel::Message;
use serenity::framework::standard::macros::{command, group};
use serenity::framework::standard::CommandResult;
use serenity::async_trait;
#[group]
#[commands(start, play_again, result, status)]
struct Sequence;
pub struct Handler;
#[async_trait]
impl EventHandler for Handler {
async fn message(&self, ctx: Context, msg: Message) {
if msg.author.bot || !msg.is_private() {
return
}
msg.channel_id.say(&ctx.http, "pong!").await.expect("aaa");
}
}
#[command]
async fn start(ctx: &Context, msg: &Message) -> CommandResult {
msg.channel_id.say(&ctx.http, "pong!").await?;
Ok(())
}
#[command]
async fn play_again(ctx: &Context, msg: &Message) -> CommandResult {
msg.channel_id.say(&ctx.http, "pong!").await?;
Ok(())
}
#[command]
async fn result(ctx: &Context, msg: &Message) -> CommandResult {
msg.channel_id.say(&ctx.http, "pong!").await?;
Ok(())
}
#[command]
async fn status(ctx: &Context, msg: &Message) -> CommandResult {
msg.channel_id.say(&ctx.http, "pong!").await?;
Ok(())
}
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under both the MIT license found in the
* LICENSE-MIT file in the root directory of this source tree and the Apache
* License, Version 2.0 found in the LICENSE-APACHE file in the root directory
* of this source tree.
*/
use std::mem;
use std::sync::{Arc, Weak};
use std::time::Instant;
use chrome_trace::{Args, Event, Phase};
use crate::context::TraceContextInner;
/// An RAII guard that logs a synchronous trace event when it goes out of scope.
/// Useful for scoped synchronous tracing of functions and blocks.
#[derive(Debug)]
pub struct TraceGuard {
context: Weak<TraceContextInner>,
name: String,
args: Args,
start: Instant,
}
impl TraceGuard {
pub(crate) fn new(context: &Arc<TraceContextInner>, name: String, args: Args) -> Self {
TraceGuard {
context: Arc::downgrade(context),
name,
args,
start: Instant::now(),
}
}
/// Get a reference to the trace arguments associated with this guard. Allows the code
/// being traced to manipulate the arguments that will be logged once this guard goes
/// out of scope.
pub fn args(&mut self) -> &mut Args {
&mut self.args
}
}
impl Drop for TraceGuard {
fn drop(&mut self) {
// Has the context that produced this guard already been dropped?
let context = match self.context.upgrade() {
Some(ctx) => ctx,
None => return,
};
let dur = self.start.elapsed();
let name = mem::replace(&mut self.name, Default::default());
let args = mem::replace(&mut self.args, Default::default());
let event = Event::new(name, Phase::Complete)
.args(args)
.ts(self.start.duration_since(context.epoch))
.dur(dur);
context.add_event(event);
}
}
|
use crate::game::utils::*;
use crate::game::Drawable;
use std::io::{Error, Write};
pub struct Snake {
head: Coord,
body: Vec<Direction>,
max_length: u16,
}
impl Snake {
pub fn new(start_pos: Coord, len: u16) -> Snake {
let head = start_pos;
let body = vec![Direction::Right; len.into()];
let max_length = len;
Snake {
head,
body,
max_length,
}
}
pub fn move_step(&mut self, d: Direction) {
self.head = self.head.r#move(&d);
self.body.insert(0, d);
if self.body.len() > self.max_length.into() {
self.body.pop();
}
}
pub fn eat(&mut self) {
self.max_length += 1;
}
pub fn is_overlapping(&self, c: Coord) -> bool {
let mut pos = self.head.clone();
self.body
.iter()
.filter(|s| {
pos = pos.r#move(s.to_owned());
c == pos
})
.count()
.gt(&0)
}
pub fn get_head(&self) -> Coord {
self.head.clone()
}
pub fn get_length(&self) -> u16 {
self.max_length
}
}
impl Drawable for Snake {
fn draw(&mut self, buffer: &mut impl Write) -> Result<(), Error> {
let mut pos = self.head;
write!(
buffer,
"{}{}[]{}",
termion::cursor::Goto((pos.x * 2) as u16, pos.y as u16),
termion::style::Bold,
termion::style::Reset,
)?;
for n in 0..self.body.len() {
pos = pos.move_reverse(self.body.get(n as usize).unwrap());
write!(
buffer,
"{}{}[]{}",
termion::cursor::Goto((pos.x * 2) as u16, pos.y as u16),
termion::style::Bold,
termion::style::Reset,
)?;
}
Ok(())
}
}
|
use phasicj_jmm::JmmEvent;
|
extern crate chrono;
extern crate rustc_serialize;
use self::chrono::{DateTime, UTC};
use rustc_serialize::json::{ToJson, Json};
use std::collections::BTreeMap;
#[derive(Debug, Clone)]
pub struct Period {
pub started_at: chrono::DateTime<UTC>,
pub finished_at: chrono::DateTime<UTC>
}
#[derive(Debug, Clone, RustcDecodable)]
pub struct Request {
pub id: String,
pub command: String,
pub cwd: String
}
#[derive(Debug, Clone)]
pub struct Response {
pub status: i32,
pub stderr: String,
pub stdout: String,
pub period: Period
}
#[derive(Debug, Clone)]
pub struct Item {
pub request: Request,
pub response: Response
}
impl Item {
pub fn to_record (&self) -> Record {
Record {
id: self.request.id.clone(),
command: self.request.command.clone(),
cwd: self.request.cwd.clone(),
status: self.response.status.clone(),
stderr: self.response.stderr.clone(),
stdout: self.response.stdout.clone(),
started_at: self.response.period.started_at.clone(),
finished_at: self.response.period.finished_at.clone()
}
}
}
#[derive(Debug, Clone)]
pub struct Record {
pub id: String,
pub command: String,
pub cwd: String,
pub status: i32,
pub stderr: String,
pub stdout: String,
pub started_at: chrono::DateTime<UTC>,
pub finished_at: chrono::DateTime<UTC>
}
impl ToJson for Record {
fn to_json(&self) -> Json {
let mut data = BTreeMap::new();
data.insert("id".to_string(), self.id.to_json());
data.insert("command".to_string(), self.command.to_json());
data.insert("cwd".to_string(), self.cwd.to_json());
data.insert("status".to_string(), self.status.to_json());
data.insert("stderr".to_string(), self.stderr.to_json());
data.insert("stdout".to_string(), self.stdout.to_json());
data.insert("startedAt".to_string(), self.started_at.to_rfc3339().to_json());
data.insert("finishedAt".to_string(), self.finished_at.to_rfc3339().to_json());
Json::Object(data)
}
} |
use common::*;
use glw::gl_buffer::{GLArray, GLBuffer, Triangles};
use glw::gl_context::GLContext;
use glw::shader::Shader;
use glw::vertex;
use nalgebra::Vec3;
use state::App;
use state::EntityId;
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
// N.B.: Behaviors are unsafe because they take both a mutable and immutable
// reference to a mob (the mob is also inside the main::App).
pub type Behavior = unsafe fn(&App, &mut Mob);
pub struct Mob {
pub speed: Vec3<f32>,
pub behavior: Behavior,
pub id: EntityId,
}
pub struct MobBuffers {
id_to_index: HashMap<EntityId, uint>,
index_to_id: Vec<EntityId>,
triangles: GLArray<vertex::ColoredVertex>,
}
impl MobBuffers {
pub fn new(gl: &GLContext, color_shader: Rc<RefCell<Shader>>) -> MobBuffers {
MobBuffers {
id_to_index: HashMap::new(),
index_to_id: Vec::new(),
triangles: GLArray::new(
gl,
color_shader.clone(),
[ vertex::AttribData { name: "position", size: 3, unit: vertex::Float },
vertex::AttribData { name: "in_color", size: 4, unit: vertex::Float },
],
Triangles,
GLBuffer::new(32 * TRIANGLE_VERTICES_PER_BOX),
),
}
}
pub fn push(
&mut self,
id: EntityId,
triangles: &[vertex::ColoredVertex]
) {
self.id_to_index.insert(id, self.index_to_id.len());
self.index_to_id.push(id);
self.triangles.push(triangles);
}
pub fn update(
&mut self,
id: EntityId,
triangles: &[vertex::ColoredVertex]
) {
let idx = *self.id_to_index.find(&id).unwrap();
self.triangles.buffer.update(idx, triangles);
}
pub fn draw(&self, gl: &GLContext) {
self.triangles.draw(gl);
}
}
|
use std::cmp::Ordering;
use std::ops::Add;
fn two_sum<T>(arr: &[T], sum: T) -> Option<(usize, usize)>
where
T: Add<Output = T> + Ord + Copy,
{
if arr.len() == 0 {
return None;
}
let mut i = 0;
let mut j = arr.len() - 1;
while i < j {
match (arr[i] + arr[j]).cmp(&sum) {
Ordering::Equal => return Some((i, j)),
Ordering::Less => i += 1,
Ordering::Greater => j -= 1,
}
}
None
}
fn main() {
let arr = [0, 2, 11, 19, 90];
let sum = 21;
println!("{:?}", two_sum(&arr, sum));
} |
pub fn lsp(series: &str, n: usize) -> Result<u32, &str> {
if series.len() < n {
return Err("The series is not long enough.");
}
if n == 0 {
return Ok(1);
}
let mut num_vec: Vec<u32> = Vec::new();
let mut char_iter = series.chars();
while let Some(c) = char_iter.next() {
if let Some(i) = c.to_digit(10) {
num_vec.push(i);
} else {
return Err("There was a non digit.");
}
}
let num_slice = &num_vec[..];
if let Some(i) = num_slice.windows(n).map(|x| x.iter().product::<u32>()).max() {
Ok(i)
} else {
Err("Could not calculate max.")
}
} |
// Find number of negative values in sorted matrix (descending order along both axis).
// https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix/
//-----------------------------------------------------------------------------------
// Ω(n) O(n log m) | O(1)
pub mod count_negatives {
pub fn run(grid: Vec<Vec<i32>>) -> u32 {
let (height,width) = (grid.len(),grid[0].len());
let mut neg_space = 0usize;
for y in 0..grid.len() {
println!("{:.?}",bin_search_smallest_negative(&grid[y]));
if let Some(index) = bin_search_smallest_negative(&grid[y]) {
neg_space += width-index;
println!("{}",width-index);
}
}
println!("neg_space:{}",neg_space);
return neg_space as u32;
// Inner logic seems bit excessive here
// Returns index of smallest positive number from descending order vector
fn bin_search_smallest_negative(vec:&Vec<i32>) -> Option<usize> {
let (mut left, mut right) = (0usize,vec.len()-1);
let mut index = usize::default();
while left != right {
index = left + (right-left) / 2;
if vec[index] < 0 {
if index == 0 { return Some(0); }
if vec[index-1] > 0 { return Some(index); }
//if vec[index-1] >= 0 { return Some(index); }
right = index - 1;
}
else {
left = index + 1;
}
}
if vec[left] < 0 { return Some(left); }
return None;
}
}
}
// Given 2 equal length strings s,t composed of lowercase english characters,
// find the minimum number of steps to make t an anagram of s.
// A step is changing a letter in t.
// https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram/
//-----------------------------------------------------------------------------------
// I am certain this can be improved (Perhaps not Onotationally, but practically).
// O(n+k) | O(k)
// where k=26 (number of lowercase englsih characters) and n = length of s and t.
pub mod min_steps_to_make_strings_anagram {
// O(n) | O(k)
// Where k = number of different values in `nums`.
pub fn run(s:String,t:String) -> u32 {
let s_chars:&[u8] = s.as_bytes();
let t_chars:&[u8] = t.as_bytes();
// O(n) | O(k)
let mut counts:Vec<i32> = vec!(0i32;26usize);
for i in 0..s_chars.len() {
counts[s_chars[i] as usize - 97usize] += 1;
counts[t_chars[i] as usize - 97usize] -= 1;
}
// O(26) | O(1)
let mut count = 0u32;
for i in 0..counts.len() {
if counts[i] > 0 {
count += counts[i] as u32;
}
}
return count;
}
}
// Get indicies of 2 integers which sum to `target`
// https://leetcode.com/problems/two-sum/
//-----------------------------------------------------------------------------------
pub mod two_sum {
use std::collections::HashMap;
// O(n) | O(k)
// Where k = number of different values in `nums`.
pub fn unordered(nums: &[i16], target: i16) -> Option<(usize,usize)> {
let mut values:HashMap<i16,usize> = HashMap::new();
for i in 0..nums.len() {
if let Some(lookup) = target.checked_sub(nums[i]) {
if let Some(value) = values.get(&lookup) {
return Some((*value,i));
}
}
values.insert(nums[i],i);
}
return None; // Cannot find 2 values which equal `target`
}
// `nums` is assumed ordered.
// O(n) | O(2)
pub fn ordered(nums: &[i16], target: i16) -> Option<(usize,usize)> {
// O(n) | O(2)
let mut low:usize = 0usize;
let mut high:usize = nums.len()-1usize;
while high != low {
if let Some(val) = nums[low].checked_add(nums[high]) {
if val == target { return Some((low,high)); }
else if val > target { high -= 1; }
else { low += 1; } // val < target
}
}
return None; // Cannot find 2 values which equal `target`
}
}
// (god this question is badly formed, and the marking for Rust doesn't even work on Leetcode)
// Allows tweets to be added with a time specified in seconds.
// Allow the user to retrieve the number of tweets in each interval (intervals can be minutes/hours/days)
// from a start time until an end time.
// An example output: [3,4,5]:
// 3 tweets in 1st interval (start time -> interval period),
// 4 tweets in 2nd interval,
// 5 tweets in 3rd interval (this last interval will likely be less than the set interval period, since it ends at `end_time` regardless of interval)
// https://leetcode.com/problems/tweet-counts-per-frequency/
//-----------------------------------------------------------------------------------
// We could insert tweets inorder O(log n) (binary search) for each insertion,
// or we can sort tweets when `get_tweet_counts_per_frequency` called O(n log n),
// presuming tweets will be inserted vastly more (more than n) than `get_tweet_counts_per_frequency` is called,
// I have chosen the 2nd approach. (n refers to the number of recordings under each tweet)
pub mod tweet_counts {
use std::collections::HashMap;
pub enum Frequency {
Minute,Hour,Day
}
pub struct TweetCounts {
tweet_times:HashMap<String,Vec<u32>>,
}
impl TweetCounts {
// O(1)
pub fn new() -> Self {
TweetCounts { tweet_times:HashMap::new() }
}
// O(1)
pub fn record_tweet(&mut self,tweet_name:String,time:u32) {
if let Some(recordings) = self.tweet_times.get_mut(&tweet_name) {
recordings.push(time);
}
else {
self.tweet_times.insert(tweet_name,vec![time]);
}
}
// O(n lon n + n) | O(n/2)
pub fn get_tweet_counts_per_frequency(&mut self,freq:Frequency,tweet_name:&str,start_time:u32,end_time:u32) -> Option<Vec<u32>> {
if let Some(recordings) = self.tweet_times.get_mut(tweet_name) {
// If so `sec_frequency` can be u32 and we can adjust some casts.
let sec_frequency:u32 = match freq {
Frequency::Minute => 60,
Frequency::Hour => 3600,
Frequency::Day => 86400,
};
// O(n log n) | O(n/2)
recordings.sort();
// TODO This could be improved. Firstly don't do the interval calculation every element.
// O(n)
let mut start_element = 0usize;
while start_time > recordings[start_element] {
start_element += 1;
if start_element == recordings.len() { break; }
}
let intervals = ((end_time-start_time) / sec_frequency) as usize + 1;
let mut frequencies = vec!(0u32;intervals);
for i in start_element..recordings.len() {
let interval = ((recordings[i] - start_time) / sec_frequency) as usize;
if interval >= intervals { break; }
frequencies[interval] += 1;
}
return Some(frequencies);
}
else {
return None;
}
}
}
}
// Check if there exists 2 integers N,M where N = 2 * M
// https://leetcode.com/problems/check-if-n-and-its-double-exist/
//-----------------------------------------------------------------------------------
// O(n) | O(n)
pub mod double_exists {
use std::collections::HashMap;
// O(n) | O(k)
// Where k = number of different values in `nums`.
pub fn run(arr:Vec<i16>) -> bool {
let mut doubles:HashMap<i16,usize> = HashMap::new();
for i in 0..arr.len() {
if let Some(val) = arr[i].checked_mul(2i16) {
doubles.insert(val,i);
}
}
// O(n)
for i in 0..arr.len() {
if let Some(index) = doubles.get(&arr[i]) {
// Accounts for 0, value cannot be double of itself, but a 0 can be double of another 0.
if *index != i { return true; }
}
}
return false;
}
}
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under both the MIT license found in the
* LICENSE-MIT file in the root directory of this source tree and the Apache
* License, Version 2.0 found in the LICENSE-APACHE file in the root directory
* of this source tree.
*/
use anyhow::Error;
use futures::{future::FutureExt as _, future::TryFutureExt};
use futures_ext::{BoxFuture, FutureExt};
use futures_old::{
future::{ok, Future as OldFuture},
sync::oneshot,
};
use mysql_async::{prelude::FromRow, FromRowError};
use super::{BoxMysqlConnection, BoxMysqlTransaction, QueryProcess, QueryResult};
use crate::error::from_failure;
use crate::WriteResult;
type MyBoxFuture<T> = BoxFuture<T, Error>;
/// An extension trait that provides useful methods for Boxed version of
/// [crate::deprecated_mysql::MysqlConnection]. Cannot be provided directly
/// on the trait, because the usage of generics in the methods would prevent
/// from creating a trait object.
pub trait MysqlConnectionExt {
/// Perform the string query and collect the result.
/// See [::mysql_async::QueryResult::collect]
fn read_query<R: FromRow + Send + 'static>(&self, query: String) -> MyBoxFuture<Vec<R>>;
/// Perform the string query and try to collect the result.
/// See [::mysql_async::QueryResult::try_collect]
fn try_read_query<R: FromRow + Send + 'static>(
&self,
query: String,
) -> MyBoxFuture<Vec<Result<R, FromRowError>>>;
/// Perform the string query and return some metadata.
fn write_query(&self, query: String) -> MyBoxFuture<WriteResult>;
}
impl MysqlConnectionExt for BoxMysqlConnection {
fn read_query<R: FromRow + Send + 'static>(&self, query: String) -> MyBoxFuture<Vec<R>> {
helper_query_process(
|process| self.query(query, process),
|query_result| {
query_result
.collect()
.boxed()
.compat()
.map_err(from_failure)
},
)
.map(|((), result)| result)
.boxify()
}
fn try_read_query<R: FromRow + Send + 'static>(
&self,
query: String,
) -> MyBoxFuture<Vec<Result<R, FromRowError>>> {
helper_query_process(
|process| self.query(query, process),
|query_result| {
query_result
.try_collect()
.boxed()
.compat()
.map_err(from_failure)
},
)
.map(|((), result)| result)
.boxify()
}
fn write_query(&self, query: String) -> MyBoxFuture<WriteResult> {
helper_query_process(
|process| self.query(query, process),
|query_result| {
let write_result =
WriteResult::new(query_result.last_insert_id(), query_result.affected_rows());
ok((query_result, write_result))
},
)
.map(|((), result)| result)
.boxify()
}
}
/// An extension trait that provides useful methods for Boxed version of
/// [crate::deprecated_mysql::MysqlTransaction]. Cannot be provided directly
/// on the trait, because the usage of generics in the methods would prevent
/// from creating a trait object.
pub trait MysqlTransactionExt {
/// Perform the string query and collect the result.
/// See [::mysql_async::QueryResult::collect]
fn read_query<R: FromRow + Send + 'static>(
self,
query: String,
) -> MyBoxFuture<(BoxMysqlTransaction, Vec<R>)>;
/// Perform the string query and try to collect the result.
/// See [::mysql_async::QueryResult::try_collect]
fn try_read_query<R: FromRow + Send + 'static>(
self,
query: String,
) -> MyBoxFuture<(BoxMysqlTransaction, Vec<Result<R, FromRowError>>)>;
/// Perform the string query and return some metadata.
fn write_query(self, query: String) -> MyBoxFuture<(BoxMysqlTransaction, WriteResult)>;
}
impl MysqlTransactionExt for BoxMysqlTransaction {
fn read_query<R: FromRow + Send + 'static>(
self,
query: String,
) -> MyBoxFuture<(BoxMysqlTransaction, Vec<R>)> {
helper_query_process(
|process| self.query(query, process),
|query_result| {
query_result
.collect()
.boxed()
.compat()
.map_err(from_failure)
},
)
}
fn try_read_query<R: FromRow + Send + 'static>(
self,
query: String,
) -> MyBoxFuture<(BoxMysqlTransaction, Vec<Result<R, FromRowError>>)> {
helper_query_process(
|process| self.query(query, process),
|query_result| {
query_result
.try_collect()
.boxed()
.compat()
.map_err(from_failure)
},
)
}
fn write_query(self, query: String) -> MyBoxFuture<(BoxMysqlTransaction, WriteResult)> {
helper_query_process(
|process| self.query(query, process),
|query_result| {
let write_result =
WriteResult::new(query_result.last_insert_id(), query_result.affected_rows());
ok((query_result, write_result))
},
)
}
}
fn helper_query_process<TQueryable, TProcess, TProcessFut, TProcessResult, TQueryResult>(
query: impl FnOnce(QueryProcess<TQueryable>) -> MyBoxFuture<TProcessResult>,
process: TProcess,
) -> MyBoxFuture<(TProcessResult, TQueryResult)>
where
TQueryable: Send + 'static,
TProcess: FnOnce(QueryResult<TQueryable>) -> TProcessFut + Send + 'static,
TProcessFut:
OldFuture<Item = (QueryResult<TQueryable>, TQueryResult), Error = Error> + Send + 'static,
TProcessResult: Send + 'static,
TQueryResult: Send + 'static,
{
let (tx, rx) = oneshot::channel();
query(Box::new(move |query_result| {
process(query_result)
.map(|(query_result, result)| {
let _ = tx.send(result);
query_result
})
.boxify()
}))
.and_then(|process_result| {
rx.map(|result| (process_result, result))
.map_err(|err| err.into())
})
.boxify()
}
|
mod intcode_machine;
mod util;
use intcode_machine::{run_all, Machine, State};
use std::collections::{HashMap, HashSet};
use std::io::{stdin, BufRead};
use util::error_exit;
const C_NORTH: i64 = 1;
const C_SOUTH: i64 = 2;
const C_WEST: i64 = 3;
const C_EAST: i64 = 4;
const S_STILL: i64 = 0;
const S_MOVED: i64 = 1;
const S_FOUND: i64 = 2;
fn move_dir(cur_pos: &(i64, i64), dir: i64) -> (i64, i64) {
match dir {
C_NORTH => (cur_pos.0, cur_pos.1 - 1),
C_SOUTH => (cur_pos.0, cur_pos.1 + 1),
C_WEST => (cur_pos.0 - 1, cur_pos.1),
C_EAST => (cur_pos.0 + 1, cur_pos.1),
_ => error_exit("Wrong Direction"),
}
}
struct WorldMap {
machine: Machine,
prev: HashMap<(i64, i64), i64>,
wall: HashSet<(i64, i64)>,
visited: HashSet<(i64, i64, i64)>,
target: Option<(i64, i64)>,
}
impl WorldMap {
fn new() -> WorldMap {
let program = stdin()
.lock()
.split(',' as u8)
.map(|chunk| String::from_utf8(chunk.ok()?).ok()?.parse().ok())
.map(|result| result.expect("Failed to get next input"))
.collect();
WorldMap {
machine: Machine::new(&program),
prev: HashMap::new(),
wall: HashSet::new(),
target: None,
}
}
fn step(&mut self, dir: i64) -> i64 {
run_all(&mut self.machine, yield_iter![dir,]);
self.machine.pop_output()
}
}
fn visit(curr: (i64, i64), map: &mut WorldMap) {
for &dir in &[C_NORTH, C_SOUTH, C_EAST, C_WEST] {
let next = move_dir(&curr, dir);
if map.wall.contains(&next) {
continue;
}
}
}
fn main() {
let mut my_world = WorldMap::new();
visit((0, 0), &mut my_world);
}
|
mod line;
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
#[no_mangle]
pub struct TextEditor {
lines: Vec<line::Line>, // Holds all lines
mode: String, // Language mode, i.e. Java or Python
cur_line: u32, // Current line the editor is on
is_newline: bool, // If the next inserted line is a new line
}
#[no_mangle]
impl TextEditor {
fn get_line(&self, index: u32) -> &String {
// Get the line at the specific index
match self.lines.get(index as usize) {
Some(x) => x.get_text(),
None => panic!("Index out of bounds"), // panic for now
}
}
fn get_mode(&self) -> &String {
&self.mode
}
fn insert_line(&mut self, text: String, index: u32) {
// Inserts line at specified index
self.lines.insert(index as usize, line::Line::new(text, self.cur_line))
}
fn handle_text(&mut self, text: String) {
// Handles inputted text
if self.is_newline {
// If a newline, then create a new line in the vector
self.lines.push(line::Line::new(text, self.cur_line));
self.is_newline = false;
}
else {
// Otherwise add the text to the current line's text
self.lines[(self.cur_line - 1) as usize].append_text(&text);
}
}
fn handle_backspace(&mut self) {
// Remove the last character on the current line
// TODO - update to handle middle of line deletions
if self.lines.len() != 0 {
self.lines[(self.cur_line - 1) as usize].remove_char();
}
}
fn handle_delete(&mut self) {
// TODO - Get cursor location, then find char associated with that
}
}
#[wasm_bindgen]
#[no_mangle]
impl TextEditor {
pub fn new(mode: String) -> TextEditor {
// Create an empty Text Editor
TextEditor {
lines: Vec::new(),
mode: mode,
cur_line: 1,
is_newline: true
}
}
pub fn new_from_string(text: String, mode: String) -> TextEditor {
// Create a Text Editor from a string
let mut te = TextEditor {
lines: Vec::new(),
mode: mode,
cur_line: 1,
is_newline: true
};
let mut prev_i = 0;
for (i, c) in text.chars().enumerate() {
if c == '\n' {
// Upon encountering a newline, push the previous contents to the vector
te.append_line(text[prev_i..i].to_string());
prev_i = i;
}
}
te
}
pub fn render(&self) -> String {
// Get the HTML of all the lines in the vector
let mut s = String::from("");
for x in &self.lines {
s.push_str(&x.get_html());
}
s
}
pub fn append_line(&mut self, text: String) {
// Adds a line to the end
self.lines.push(line::Line::new(text, self.cur_line));
self.cur_line += 1;
}
pub fn get_last_line(&self) -> String {
self.lines.last().clone().unwrap().get_text().to_string()
}
pub fn get_input(&mut self, input_type: String, text: String) {
// Handle input event based on type of input
match input_type.as_str() {
"insertText" => self.handle_text(text), // Handle text input event
"insertLineBreak" => {self.cur_line += 1; self.is_newline = true}, // Handle newline event
"deleteContentBackward" => self.handle_backspace(), // Handle backspace event
"deleteContentForward" => self.handle_delete(), // Handle delete event
_ => (), // Do nothing on unrecognized event
};
}
} |
//! This is the uncleaned result of XML deserialization. You probably want the objects and methods
//! in the `geom::graph` module instead.
extern crate serde;
//use serde::{de::Error, Deserialize, Deserializer};
use serde::Deserialize;
use crate::Error;
/// A `Mesh` is the top-level structure representing a GEOM object graph.
///
/// The mesh contains objects from various classes, called "geoms." `Geom`s represent things like
/// disks, or disk partitions, or device nodes under `/dev` on FreeBSD systems. They are related
/// by references called "consumers" and "providers."
#[derive(Debug, Deserialize, PartialEq)]
pub struct Mesh {
#[serde(rename = "class", default)]
pub classes: Vec<Class>,
}
/// `Class` contains all of the objects ("geoms") and associated relationships ("consumers" and
/// "providers") associated with the class.
#[derive(Debug, Deserialize, PartialEq)]
pub struct Class {
// Ideally, deserialize directly to u64. However, neither of these works:
//#[serde(with = "SerHex::<CompactPfx>")]
//#[serde(borrow, deserialize_with = "from_hex")]
pub id: String, // uintptr_t
pub name: String,
#[serde(rename = "geom", default)]
pub geoms: Vec<Geom>,
// libgeom(3) thinks Classes have config sections, but I don't see any.
}
/// A `Geom` is the essential object in a GEOM graph.
///
/// It can represent a disk (under the "DISK" class), or partition (under "PART"), or `/dev` device
/// node (under "DEV"), as well as several other classes.
///
/// A geom is related to other geoms in a directed graph. `Consumer` edges indicate that this geom
/// depends on a lower-level (lower "`rank`") geom. `Provider` edges indicate that this geom
/// exposes an object to a higher-level object. For example, a PART geom might "consume" a DISK
/// geom ("ada0") and "provide" logical partition objects ("ada0p1", "ada0p2", etc.).
#[derive(Debug, Deserialize, PartialEq)]
pub struct Geom {
pub id: String, // uintptr_t
#[serde(rename = "class")]
pub class_ref: ClassRef,
pub name: String,
pub rank: u64,
pub config: Option<GeomConfig>,
#[serde(rename = "consumer", default)]
pub consumers: Vec<Consumer>,
#[serde(rename = "provider", default)]
pub providers: Vec<Provider>,
}
/// A `ClassRef` is just a logical pointer to a `Class`.
///
/// `ClassRef::ref_` references the same namespace as `Class::id`.
#[derive(Debug, Deserialize, PartialEq)]
pub struct ClassRef {
#[serde(rename = "ref")]
pub ref_: String, // uintptr_t
}
/// A set of key-value metadata associated with a specific `Geom`.
///
/// The semantics and available values vary depending on the class.
#[derive(Debug, Deserialize, PartialEq)]
pub struct GeomConfig {
// PART
pub scheme: Option<String>,
pub entries: Option<u64>,
pub first: Option<u64>,
pub last: Option<u64>,
pub fwsectors: Option<u64>,
pub fwheads: Option<u64>,
pub state: Option<String>, // "OK"
pub modified: Option<bool>,
}
/// A pointer from one geom to a `Provider` of a lower-level geom.
///
/// In the logical directed graph, it is an out-edge.
///
/// It is associated with the `Geom` with `id` equal to `geom_ref.ref_`, and points to the
/// `Provider` with `id` equal to `provider_ref.ref_`.
#[derive(Debug, Deserialize, PartialEq)]
pub struct Consumer {
pub id: String, // uintptr_t
#[serde(rename = "geom")]
pub geom_ref: GeomRef,
#[serde(rename = "provider")]
pub provider_ref: ProviderRef,
pub mode: String,
}
/// A pointer into a geom from the `Consumer` of a higher-level geom.
///
/// In the logical directed graph, it is an in-edge.
///
/// It is associated with the `Geom` with `id` equal to `geom_ref.ref_`.
#[derive(Debug, Deserialize, PartialEq)]
pub struct Provider {
pub id: String, // uintptr_t
#[serde(rename = "geom")]
pub geom_ref: GeomRef,
pub mode: String,
pub name: String,
pub mediasize: u64,
pub sectorsize: u64,
pub stripesize: u64,
pub stripeoffset: u64,
pub config: ProviderConfig,
}
// Ideally this would be some enum type based on the Class, but, ya know. (serde(flatten) / enum
// interaction doesn't seem flawless at this time.)
/// A set of key-value metadata associated with a specific `Provider`.
///
/// The semantics and available values vary depending on the class.
#[derive(Debug, Deserialize, PartialEq)]
pub struct ProviderConfig {
// DISK
pub fwheads: Option<u64>,
pub fwsectors: Option<u64>,
pub rotationrate: Option<String>,
pub ident: Option<String>,
pub lunid: Option<String>,
pub descr: Option<String>,
// PART
pub start: Option<u64>,
pub end: Option<u64>,
pub index: Option<u64>,
#[serde(rename = "type")]
pub type_: Option<String>,
pub offset: Option<u64>,
pub length: Option<u64>,
pub label: Option<String>,
pub rawtype: Option<String>,
pub rawuuid: Option<String>,
pub efimedia: Option<String>,
// LABEL
// index, length, offset shared with PART above
pub seclength: Option<u64>,
pub secoffset: Option<u64>,
}
/// A `GeomRef` is just a logical pointer to a `Geom`.
///
/// `GeomRef::ref_` references the same namespace as `Geom::id`.
#[derive(Debug, Deserialize, PartialEq)]
pub struct GeomRef {
#[serde(rename = "ref")]
pub ref_: String, // uintptr_t
}
/// A `ProviderRef` is just a logical pointer to a `Provider`.
///
/// `ProviderRef::ref_` references the same namespace as `Provider::id`.
#[derive(Debug, Deserialize, PartialEq)]
pub struct ProviderRef {
#[serde(rename = "ref")]
pub ref_: String, // uintptr_t
}
/// Parse a GEOM XML string configuration into a geom::raw::Mesh structure.
///
/// # Arguments
///
/// * `xml` - A string slice of the contents of the `kern.geom.confxml` `sysctl` node from a
/// FreeBSD system.
///
/// # Examples
///
/// ```
/// use freebsd_geom as geom;
///
/// let mesh = geom::raw::parse_xml(r#"<mesh> ... </mesh>"#).unwrap();
/// println!("The mesh has {} classes.", mesh.classes.len());
/// ```
pub fn parse_xml(xml: &str) -> Result<Mesh, Error> {
return Ok(quick_xml::de::from_str::<Mesh>(xml)?);
}
/// Returns a structure representing the raw GEOM mesh on the running system.
///
/// # Examples
///
/// ```
/// use freebsd_geom as geom;
/// use std::collections::BTreeMap;
///
/// fn myfoo() -> Result<(), geom::Error> {
/// let mesh = geom::raw::get_mesh()?;
///
/// let mut count = BTreeMap::new();
/// for g_class in &mesh.classes {
/// count.insert(&g_class.name, g_class.geoms.len());
/// }
/// for (class_name, count) in &count {
/// println!("class {}: {} geoms", class_name, count);
/// }
/// Ok(())
/// }
/// ```
#[cfg(target_os = "freebsd")]
pub fn get_mesh() -> Result<Mesh, Error> {
let xml = crate::get_confxml()?;
return Ok(parse_xml(&xml)?);
}
#[cfg(test)]
mod tests {
use crate::structs;
#[test]
fn xml_mesh_basic() {
let xml = "<mesh></mesh>";
quick_xml::de::from_str::<structs::Mesh>(xml).unwrap();
}
#[test]
fn xml_class_basic() {
let xml = "<class id=\"0xffffffff81234567\"><name>FD</name></class>";
let cls = quick_xml::de::from_str::<structs::Class>(xml).unwrap();
assert_eq!(cls.id, "0xffffffff81234567");
assert_eq!(cls.name, "FD");
}
#[test]
fn xml_references() {
let xml = "<class ref=\"0x123\"/>";
let cls = quick_xml::de::from_str::<structs::ClassRef>(xml).unwrap();
assert_eq!(cls.ref_, "0x123");
let xml = "<provider ref=\"0x123\"/>";
let p = quick_xml::de::from_str::<structs::ProviderRef>(xml).unwrap();
assert_eq!(p.ref_, "0x123");
let xml = "<geom ref=\"0x123\"/>";
let p = quick_xml::de::from_str::<structs::GeomRef>(xml).unwrap();
assert_eq!(p.ref_, "0x123");
}
#[test]
fn xml_geom_config() {
let xml = r#"<config><scheme>GPT</scheme></config>"#;
let p = quick_xml::de::from_str::<structs::GeomConfig>(xml).unwrap();
assert_eq!(p.scheme.unwrap(), "GPT");
}
#[test]
fn xml_consumer() {
let xml = r#"<consumer id="0x123">
<geom ref="0x456"/>
<provider ref="0x789"/>
<mode>r0w0e0</mode>
</consumer>"#;
let p = quick_xml::de::from_str::<structs::Consumer>(xml).unwrap();
assert_eq!(
p,
structs::Consumer {
id: "0x123".into(),
geom_ref: structs::GeomRef {
ref_: "0x456".into()
},
provider_ref: structs::ProviderRef {
ref_: "0x789".into()
},
mode: "r0w0e0".into(),
}
);
}
#[test]
fn xml_provider_config() {
// DISK class
let xml = r#"<config>
<fwheads>1</fwheads>
<fwsectors>2</fwsectors>
<rotationrate>0</rotationrate>
<ident>S3Z</ident>
<lunid>00123abcd</lunid>
<descr>Samsung SSD</descr>
</config>"#;
let p = quick_xml::de::from_str::<structs::ProviderConfig>(xml).unwrap();
assert_eq!(
p,
structs::ProviderConfig {
fwheads: Some(1),
fwsectors: Some(2),
rotationrate: Some("0".into()),
ident: Some("S3Z".into()),
lunid: Some("00123abcd".into()),
descr: Some("Samsung SSD".into()),
// PART fields
start: None,
end: None,
index: None,
type_: None,
offset: None,
length: None,
label: None,
rawtype: None,
rawuuid: None,
efimedia: None,
// LABEL fields
seclength: None,
secoffset: None,
}
);
}
#[test]
fn xml_provider() {
let xml = r#"<provider id="0x123">
<geom ref="0x456"/>
<mode>r1w1e3</mode>
<name>ada0</name>
<mediasize>10</mediasize>
<sectorsize>2</sectorsize>
<stripesize>0</stripesize>
<stripeoffset>123</stripeoffset>
<config>
<fwheads>1</fwheads>
<fwsectors>2</fwsectors>
<rotationrate>0</rotationrate>
<ident>S3Z</ident>
<lunid>00123abcd</lunid>
<descr>Samsung SSD</descr>
</config>
</provider>"#;
let p = quick_xml::de::from_str::<structs::Provider>(xml).unwrap();
assert_eq!(p.id, "0x123");
assert_eq!(
p.geom_ref,
structs::GeomRef {
ref_: "0x456".into()
}
);
assert_eq!(p.mode, "r1w1e3");
assert_eq!(p.name, "ada0");
assert_eq!(p.mediasize, 10);
assert_eq!(p.sectorsize, 2);
assert_eq!(p.stripesize, 0);
assert_eq!(p.stripeoffset, 123);
}
#[test]
fn xml_geom_basic() {
let xml = r#"<geom id="0x123">
<class ref="0x456"/>
<name>ada0</name>
<rank>1</rank>
<config>
</config>
</geom>"#;
let p = quick_xml::de::from_str::<structs::Geom>(xml).unwrap();
assert_eq!(
p,
structs::Geom {
id: "0x123".into(),
class_ref: structs::ClassRef {
ref_: "0x456".into()
},
name: "ada0".into(),
rank: 1,
config: Some(structs::GeomConfig {
scheme: None,
entries: None,
first: None,
last: None,
fwsectors: None,
fwheads: None,
state: None,
modified: None,
}),
consumers: vec![],
providers: vec![],
}
);
}
#[test]
fn xml_full_sample() {
let xml = include_str!("test/fullsample.xml");
let p = quick_xml::de::from_str::<structs::Mesh>(xml).unwrap();
// Some arbitrarily chosen doc queries
assert_eq!(p.classes[0].name, "FD");
assert_eq!(p.classes[1].name, "RAID");
assert_eq!(p.classes[2].name, "DISK");
assert_eq!(p.classes[2].id, p.classes[2].geoms[0].class_ref.ref_);
assert_eq!(
p.classes[2].geoms[0].id,
p.classes[2].geoms[0].providers[0].geom_ref.ref_
);
assert_eq!(p.classes[2].geoms[0].providers[0].mediasize, 1000204886016);
assert_eq!(
p.classes[2].geoms[0].providers[0]
.config
.lunid
.as_ref()
.unwrap(),
"YYYYYYYYYYYYYYYY"
);
assert_eq!(p.classes[2].geoms[1].name, "nvd1");
assert_eq!(p.classes[3].name, "DEV");
assert_eq!(p.classes[3].id, p.classes[3].geoms[0].class_ref.ref_);
assert_eq!(p.classes[3].geoms[1].name, "ada0p1");
// DEV consumer -> PART provider
assert_eq!(
p.classes[3].geoms[1].consumers[0].provider_ref.ref_,
p.classes[4].geoms[0].providers[0].id
);
assert_eq!(p.classes[4].name, "PART");
assert_eq!(p.classes[5].name, "LABEL");
assert_eq!(p.classes[6].name, "VFS");
assert_eq!(p.classes[7].name, "SWAP");
assert_eq!(p.classes[8].name, "Flashmap");
assert_eq!(p.classes[9].name, "MD");
}
}
|
#[doc = "Reader of register PCF1"]
pub type R = crate::R<u32, super::PCF1>;
#[doc = "Writer for register PCF1"]
pub type W = crate::W<u32, super::PCF1>;
#[doc = "Register PCF1 `reset()`'s with value 0"]
impl crate::ResetValue for super::PCF1 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `CTC_REMAP`"]
pub type CTC_REMAP_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `CTC_REMAP`"]
pub struct CTC_REMAP_W<'a> {
w: &'a mut W,
}
impl<'a> CTC_REMAP_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 11)) | (((value as u32) & 0x03) << 11);
self.w
}
}
#[doc = "Reader of field `FSMC_NADV`"]
pub type FSMC_NADV_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `FSMC_NADV`"]
pub struct FSMC_NADV_W<'a> {
w: &'a mut W,
}
impl<'a> FSMC_NADV_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 << 10)) | (((value as u32) & 0x01) << 10);
self.w
}
}
#[doc = "Reader of field `TIMER13_REMAP`"]
pub type TIMER13_REMAP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TIMER13_REMAP`"]
pub struct TIMER13_REMAP_W<'a> {
w: &'a mut W,
}
impl<'a> TIMER13_REMAP_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 << 9)) | (((value as u32) & 0x01) << 9);
self.w
}
}
#[doc = "Reader of field `TIMER12_REMAP`"]
pub type TIMER12_REMAP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TIMER12_REMAP`"]
pub struct TIMER12_REMAP_W<'a> {
w: &'a mut W,
}
impl<'a> TIMER12_REMAP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8);
self.w
}
}
#[doc = "Reader of field `TIMER10_REMAP`"]
pub type TIMER10_REMAP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TIMER10_REMAP`"]
pub struct TIMER10_REMAP_W<'a> {
w: &'a mut W,
}
impl<'a> TIMER10_REMAP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7);
self.w
}
}
#[doc = "Reader of field `TIMER9_REMAP`"]
pub type TIMER9_REMAP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TIMER9_REMAP`"]
pub struct TIMER9_REMAP_W<'a> {
w: &'a mut W,
}
impl<'a> TIMER9_REMAP_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 << 6)) | (((value as u32) & 0x01) << 6);
self.w
}
}
#[doc = "Reader of field `TIMER8_REMAP`"]
pub type TIMER8_REMAP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TIMER8_REMAP`"]
pub struct TIMER8_REMAP_W<'a> {
w: &'a mut W,
}
impl<'a> TIMER8_REMAP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5);
self.w
}
}
impl R {
#[doc = "Bits 11:12 - CTC remapping"]
#[inline(always)]
pub fn ctc_remap(&self) -> CTC_REMAP_R {
CTC_REMAP_R::new(((self.bits >> 11) & 0x03) as u8)
}
#[doc = "Bit 10 - FSMC_NADV connect/disconnect"]
#[inline(always)]
pub fn fsmc_nadv(&self) -> FSMC_NADV_R {
FSMC_NADV_R::new(((self.bits >> 10) & 0x01) != 0)
}
#[doc = "Bit 9 - TIMER13 remapping"]
#[inline(always)]
pub fn timer13_remap(&self) -> TIMER13_REMAP_R {
TIMER13_REMAP_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 8 - TIMER12 remapping"]
#[inline(always)]
pub fn timer12_remap(&self) -> TIMER12_REMAP_R {
TIMER12_REMAP_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 7 - TIMER10 remapping"]
#[inline(always)]
pub fn timer10_remap(&self) -> TIMER10_REMAP_R {
TIMER10_REMAP_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 6 - TIMER9 remapping"]
#[inline(always)]
pub fn timer9_remap(&self) -> TIMER9_REMAP_R {
TIMER9_REMAP_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 5 - TIMER8 remapping"]
#[inline(always)]
pub fn timer8_remap(&self) -> TIMER8_REMAP_R {
TIMER8_REMAP_R::new(((self.bits >> 5) & 0x01) != 0)
}
}
impl W {
#[doc = "Bits 11:12 - CTC remapping"]
#[inline(always)]
pub fn ctc_remap(&mut self) -> CTC_REMAP_W {
CTC_REMAP_W { w: self }
}
#[doc = "Bit 10 - FSMC_NADV connect/disconnect"]
#[inline(always)]
pub fn fsmc_nadv(&mut self) -> FSMC_NADV_W {
FSMC_NADV_W { w: self }
}
#[doc = "Bit 9 - TIMER13 remapping"]
#[inline(always)]
pub fn timer13_remap(&mut self) -> TIMER13_REMAP_W {
TIMER13_REMAP_W { w: self }
}
#[doc = "Bit 8 - TIMER12 remapping"]
#[inline(always)]
pub fn timer12_remap(&mut self) -> TIMER12_REMAP_W {
TIMER12_REMAP_W { w: self }
}
#[doc = "Bit 7 - TIMER10 remapping"]
#[inline(always)]
pub fn timer10_remap(&mut self) -> TIMER10_REMAP_W {
TIMER10_REMAP_W { w: self }
}
#[doc = "Bit 6 - TIMER9 remapping"]
#[inline(always)]
pub fn timer9_remap(&mut self) -> TIMER9_REMAP_W {
TIMER9_REMAP_W { w: self }
}
#[doc = "Bit 5 - TIMER8 remapping"]
#[inline(always)]
pub fn timer8_remap(&mut self) -> TIMER8_REMAP_W {
TIMER8_REMAP_W { w: self }
}
}
|
use lazy_static::lazy_static;
use std::collections::HashMap;
use crate::{parser::Square, BoardPosition, Castling, DenseBoard, PacoError, PlayerColor};
use lazy_regex::regex_captures;
/// This module implements an extension of X-Fen that can represent settled Paco
/// Ŝako boards (i.e. boards without an active chain) together with most state.
///
/// It should be mostly compatible with <https://vchess.club/#/variants/Pacosako>
/// where I got the union notation. There are somewhat different pawn rules on the
/// vchess.club version, which explains the difference.
///
/// Fen looks like this:
///
/// > bqnrkb1r/pppppppp/5n2/8/3P4/8/PPP1PPPP/NRBKRBNQ w 2 bedh - -
/// > <pieces on board> <controlling player> <move count> <castling> <en passant> <union move>
///
/// The extension by vchess are:
///
/// - A bit string with 16 entries, one for each pawn column and color if the player
/// already moved their pawn in this column. (Only allowed once on vchess)
/// - The last pair move (if any), as undoing the same move directly is forbidden.
///
/// For compatibility we also include the <union move> as our fen could not be read
/// by the vchess page otherwise - even though we don't implement the ko rule.
// This needs its own method or rustfmt gets unhappy.
fn regex(input: &str) -> Option<(&str, &str, &str, &str, &str, &str)> {
regex_captures!(
"((?:(?:[a-zA-Z1-8]+)/?){8}) ([wb]) ([0-9]+) ([A-H]{0,2}[a-h]{0,2}|-) ([a-h][1-8]|-) -",
input
)
}
lazy_static! {
static ref CHAR_TO_SQUARE: HashMap<char, Square> = {
let mut map = lowercase_char_to_square();
// Now we put everything in again, but for uppercase keys and flipped values.
map.clone().iter().for_each(|(k, v)| {
map.insert(k.to_ascii_uppercase(), v.flip());
});
map
};
static ref SQUARE_TO_CHAR: HashMap<Square, char> = {
let reverse = lowercase_char_to_square();
let mut map: HashMap<Square, char> = HashMap::new();
reverse.iter().for_each(|(c, square)| {
map.insert(square.clone(), *c);
});
// By going over lower case characters first, we make sure those get preferred.
reverse.iter().for_each(|(c, square)| {
map.entry(square.flip()).or_insert_with(|| c.to_ascii_uppercase());
});
map
};
}
pub fn parse_fen(input: &str) -> Result<DenseBoard, PacoError> {
if let Some((_, pieces, player, move_count, castling, en_passant)) = regex(input) {
let mut result = DenseBoard::empty();
// Iterate over all the rows and insert pieces.
for (v, row) in pieces.split('/').enumerate() {
let mut h = 0;
for char in row.chars() {
if let Some(square) = CHAR_TO_SQUARE.get(&char) {
let position = 56 + h - 8 * v;
if position >= 64 {
panic!("Position too large: {}", position);
}
*result.white.get_mut(position).unwrap() = square.white;
*result.black.get_mut(position).unwrap() = square.black;
h += 1;
}
// Or look at a number and do many empty squares
else if let Some(n) = char.to_digit(10) {
h += n as usize;
}
}
// Check if we are done.
if h != 8 {
return Err(PacoError::InputFenMalformed(format!(
"Line {} has length {}",
v, h
)));
}
}
// Set other metadata
result.controlling_player = match player {
"w" => PlayerColor::White,
"b" => PlayerColor::Black,
_ => unreachable!("Regex restricts input to 'w' and 'b'."),
};
result.draw_state.no_progress_half_moves = move_count.parse().unwrap();
result.castling = Castling::from_string(castling);
result.en_passant = BoardPosition::try_from(en_passant).ok();
Ok(result)
} else {
Err(PacoError::InputFenMalformed(
"Regex didn't match fen string.".to_string(),
))
}
}
pub fn write_fen(input: &DenseBoard) -> String {
use std::fmt::Write as _;
let mut result = String::new();
for v in 0..=7 {
let mut running_empty_spaces = 0;
for h in 0..=7 {
let position = 56 + h - 8 * v;
let square = Square {
white: *input.white.get(position).unwrap(),
black: *input.black.get(position).unwrap(),
};
if square.is_empty() {
running_empty_spaces += 1;
} else if let Some(char) = SQUARE_TO_CHAR.get(&square) {
if running_empty_spaces > 0 {
write!(result, "{}", running_empty_spaces).unwrap();
running_empty_spaces = 0;
}
result.push(*char);
} else {
panic!("Can't encode square: {:?}", square);
}
}
if running_empty_spaces > 0 {
write!(result, "{}", running_empty_spaces).unwrap();
}
if v != 7 {
write!(result, "/").unwrap();
}
}
write!(
result,
" {} {} {} {} -",
if input.controlling_player == PlayerColor::White {
'w'
} else {
'b'
},
input.draw_state.no_progress_half_moves,
input.castling,
input
.en_passant
.map(|sq| sq.to_string())
.unwrap_or_else(|| "-".to_owned()),
)
.unwrap();
result
}
/// Build the map that contains mappings like 'a' -> (Pawn, Pawn)
#[rustfmt::skip]
fn lowercase_char_to_square() -> HashMap<char, Square> {
use crate::PieceType::*;
let mut result = HashMap::new();
result.insert('p', Square { white: None, black: Some(Pawn)});
result.insert('r', Square { white: None, black: Some(Rook)});
result.insert('n', Square { white: None, black: Some(Knight)});
result.insert('b', Square { white: None, black: Some(Bishop)});
result.insert('q', Square { white: None, black: Some(Queen)});
result.insert('k', Square { white: None, black: Some(King)});
result.insert('a', Square { black: Some(Pawn), white: Some(Pawn)});
result.insert('c', Square { black: Some(Pawn), white: Some(Rook)});
result.insert('d', Square { black: Some(Pawn), white: Some(Knight)});
result.insert('e', Square { black: Some(Pawn), white: Some(Bishop)});
result.insert('f', Square { black: Some(Pawn), white: Some(Queen)});
result.insert('g', Square { black: Some(Pawn), white: Some(King)});
result.insert('h', Square { black: Some(Rook), white: Some(Rook)});
result.insert('i', Square { black: Some(Rook), white: Some(Knight)});
result.insert('j', Square { black: Some(Rook), white: Some(Bishop)});
result.insert('l', Square { black: Some(Rook), white: Some(Queen)});
result.insert('m', Square { black: Some(Rook), white: Some(King)});
result.insert('o', Square { black: Some(Knight), white: Some(Knight)});
result.insert('s', Square { black: Some(Knight), white: Some(Bishop)});
result.insert('t', Square { black: Some(Knight), white: Some(Queen)});
result.insert('u', Square { black: Some(Knight), white: Some(King)});
result.insert('v', Square { black: Some(Bishop), white: Some(Bishop)});
result.insert('w', Square { black: Some(Bishop), white: Some(Queen)});
result.insert('x', Square { black: Some(Bishop), white: Some(King)});
result.insert('y', Square { black: Some(Queen), white: Some(Queen)});
result.insert('z', Square { black: Some(Queen), white: Some(King)});
result.insert('_', Square { black: Some(King), white: Some(King)});
result
}
#[cfg(test)]
mod tests {
use super::*;
use crate::DenseBoard;
use crate::PacoAction;
use crate::PacoBoard;
/// Helper macro to execute moves in unit tests.
macro_rules! execute_action {
($board:expr, lift, $square:expr) => {{
$board
.execute_trusted(PacoAction::Lift($square.try_into().unwrap()))
.unwrap();
}};
($board:expr, place, $square:expr) => {{
$board
.execute_trusted(PacoAction::Place($square.try_into().unwrap()))
.unwrap();
}};
($board:expr, promote, $pieceType:expr) => {{
$board
.execute_trusted(PacoAction::Promote($pieceType))
.unwrap();
}};
}
/// Test that the new empty is properly serialized and deserialized.
#[test]
fn empty_board() {
let fen_string = "8/8/8/8/8/8/8/8 w 0 AHah - -";
let board = parse_fen(fen_string).unwrap();
assert_eq!(board, DenseBoard::empty());
assert_eq!(write_fen(&board), fen_string);
}
/// Test that the new board is properly serialized and deserialized.
#[test]
fn new_board() {
let fen_string = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0 AHah - -";
let board = parse_fen(fen_string).unwrap();
assert_eq!(board, DenseBoard::new());
assert_eq!(write_fen(&board), fen_string);
}
#[test]
fn en_passant() {
let mut board = DenseBoard::new();
// Advance a white pawn.
execute_action!(board, lift, "d2");
execute_action!(board, place, "d4");
assert_eq!(board.en_passant.unwrap().to_string(), "d3");
let fen_string = "rnbqkbnr/pppppppp/8/8/3P4/8/PPP1PPPP/RNBQKBNR b 1 AHah d3 -";
assert_eq!(write_fen(&board), fen_string);
assert_eq!(board, parse_fen(fen_string).unwrap());
// Advance a black pawn.
execute_action!(board, lift, "f7");
execute_action!(board, place, "f5");
assert_eq!(board.en_passant.unwrap().to_string(), "f6");
let fen_string = "rnbqkbnr/ppppp1pp/8/5p2/3P4/8/PPP1PPPP/RNBQKBNR w 2 AHah f6 -";
assert_eq!(write_fen(&board), fen_string);
assert_eq!(board, parse_fen(fen_string).unwrap());
}
/// Generate some random boards and roundtrip them through the serialization
#[test]
fn roundtrip() {
use rand::{thread_rng, Rng};
let mut rng = thread_rng();
for _ in 0..1000 {
let board: DenseBoard = rng.gen();
let fen = write_fen(&board);
println!("Fen: {}", fen);
let board_after_roundtrip = parse_fen(&fen).unwrap();
assert_eq!(board, board_after_roundtrip);
}
}
}
|
/*
Copyright (c) 2023 Uber Technologies, Inc.
<p>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
<p>http://www.apache.org/licenses/LICENSE-2.0
<p>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 getset::Getters;
use std::collections::HashMap;
use std::hash::Hash;
/// Trait for states (sigma), which store the states of the analysis at each program point
pub trait Sigma: Clone + Eq + PartialEq {
type Node;
/// Merges two sigma into a new one (join operator).
fn join(&self, other: &Self) -> Self;
}
/// The direction of the analysis (forwards or backwards)
pub trait Direction {
type Node: Hash + Eq + Clone;
type Sigma: Sigma<Node = Self::Node>;
fn successors(&self, node: &Self::Node) -> Vec<Self::Node>;
/// Initial abstract value for all other nodes.
fn initial_value(&self) -> Self::Sigma;
/// Initial abstract value for the entry point (e.g., first rule).
fn entry_value(&self) -> Self::Sigma;
/// Transforms the sigma based on the direction of the analysis.
/// For now we don't consider instructions, since our analysis is straightforward.
fn flow(&self, node: &Self::Node, input: &Self::Sigma) -> Self::Sigma;
}
// The results of a dataflow analysis is a mapping from program points to states (sigma)
pub type DfResults<N, S> = HashMap<N, S>;
// Struct for a dataflow analysis
#[derive(Debug, Getters)]
pub struct DataflowAnalysis<D: Direction> {
direction: D,
#[get = "pub"]
sigma_in: DfResults<D::Node, D::Sigma>,
#[get = "pub"]
sigma_out: DfResults<D::Node, D::Sigma>,
}
impl<D: Direction> DataflowAnalysis<D> {
pub fn new(direction: D) -> Self {
DataflowAnalysis {
direction,
sigma_in: DfResults::new(),
sigma_out: DfResults::new(),
}
}
/// This function performs a dataflow analysis over a control flow graph represented by blocks
/// and entry_points. It iteratively propagates the dataflow facts (sigma) through the graph
/// until it reaches a fixed point, i.e., when no new information can be obtained.
/// This function implements the Worklist algorithm, for computing the fixed points in a dataflow analysis.
/// It converges if the lattice is finite and the flow function is monotone.
///
/// # Arguments
///
/// * `blocks`: The set of all nodes in the control flow graph.
/// * `entry_points`: The entry point nodes of the control flow graph. The analysis starts from these nodes.
///
pub fn run_analysis(&mut self, blocks: Vec<D::Node>, entry_points: Vec<D::Node>) {
// Create a copy of the blocks to use as a work list. The work list keeps track of nodes
// that need to be processed because their sigma might have changed.
let mut work_list = blocks.clone();
// Initialize the sigma_in map with the initial value for all blocks.
blocks.iter().for_each(|block| {
self
.sigma_in
.insert(block.clone(), self.direction.initial_value());
});
// For entry points, we initialize them with the entry_value.
entry_points.iter().for_each(|entry| {
self
.sigma_in
.insert(entry.clone(), self.direction.entry_value());
});
// While there are still nodes to process in the work list
while let Some(cur_node) = work_list.pop() {
// Get a node from the work list, and apply the flow function to it.
if let Some(sigma_in) = self.sigma_in.get(&cur_node) {
let transferred_sigma = self.direction.flow(&cur_node, sigma_in);
self.sigma_out.insert(cur_node.clone(), transferred_sigma);
}
let cur_sigma_out = self.sigma_out.get(&cur_node).unwrap();
// For each successor of the current node
let successors = self.direction.successors(&cur_node);
successors.iter().for_each(|succ| {
// Join the currents sigma with the sigma_in of the successor.
let sigma_in = self.sigma_in.get(succ).unwrap();
let new_sigma_in = sigma_in.join(cur_sigma_out);
// If the sigma_in of the successor has changed, then it might affect its successors.
// Therefore we add it back to the list
if !sigma_in.eq(&new_sigma_in) {
self.sigma_in.insert(succ.clone(), new_sigma_in);
work_list.push(succ.clone());
}
});
}
}
}
|
#[macro_use]
extern crate microstate;
microstate!{
MicroMachine { New }
states { New, Confirmed, Ignored }
confirm {
New => Confirmed
}
ignore {
New => Ignored
}
reset {
Confirmed => New
Ignored => New
}
}
fn main() {
let mut machine = MicroMachine::new();
println!("{:?}", machine.confirm());
println!("{:?}", machine.state());
println!("{:?}", machine.ignore());
println!("{:?}", machine.state());
println!("{:?}", machine.reset());
println!("{:?}", machine.state());
println!("{:?}", machine.ignore());
println!("{:?}", machine.state());
}
|
use crate::precise::expression::Expr;
pub struct Complex {
pub real: Expr,
pub imaginary: Expr,
}
|
use crate::{
command::CommandError,
domain::{model::Favorite, repository::IRepository, service::search},
interface::presenter::suggest,
};
pub fn ls_at_favorite<T: IRepository>(repo: &T, key: String) -> anyhow::Result<Favorite> {
let target = repo.get(&key);
match target {
Ok(Some(favorite)) => Ok(favorite),
_ => {
let favorites = repo.get_all()?;
suggest(&key, search(&key, favorites));
Err(CommandError::GivenKeyNotFound.into())
}
}
}
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under both the MIT license found in the
* LICENSE-MIT file in the root directory of this source tree and the Apache
* License, Version 2.0 found in the LICENSE-APACHE file in the root directory
* of this source tree.
*/
use quote::quote;
use syn::{parse_macro_input, DeriveInput};
pub fn derive_copy_(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
let name = &input.ident;
let gen = quote! {
impl #impl_generics ::std::marker::Copy for #name #ty_generics #where_clause {
}
};
gen.into()
}
|
#[doc = "Register `OFR1` reader"]
pub type R = crate::R<OFR1_SPEC>;
#[doc = "Register `OFR1` writer"]
pub type W = crate::W<OFR1_SPEC>;
#[doc = "Field `OFFSET1` reader - ADC offset number 1 offset level"]
pub type OFFSET1_R = crate::FieldReader<u16>;
#[doc = "Field `OFFSET1` writer - ADC offset number 1 offset level"]
pub type OFFSET1_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 12, O, u16>;
#[doc = "Field `OFFSET1_CH` reader - ADC offset number 1 channel selection"]
pub type OFFSET1_CH_R = crate::FieldReader;
#[doc = "Field `OFFSET1_CH` writer - ADC offset number 1 channel selection"]
pub type OFFSET1_CH_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 5, O>;
#[doc = "Field `OFFSET1_EN` reader - ADC offset number 1 enable"]
pub type OFFSET1_EN_R = crate::BitReader;
#[doc = "Field `OFFSET1_EN` writer - ADC offset number 1 enable"]
pub type OFFSET1_EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bits 0:11 - ADC offset number 1 offset level"]
#[inline(always)]
pub fn offset1(&self) -> OFFSET1_R {
OFFSET1_R::new((self.bits & 0x0fff) as u16)
}
#[doc = "Bits 26:30 - ADC offset number 1 channel selection"]
#[inline(always)]
pub fn offset1_ch(&self) -> OFFSET1_CH_R {
OFFSET1_CH_R::new(((self.bits >> 26) & 0x1f) as u8)
}
#[doc = "Bit 31 - ADC offset number 1 enable"]
#[inline(always)]
pub fn offset1_en(&self) -> OFFSET1_EN_R {
OFFSET1_EN_R::new(((self.bits >> 31) & 1) != 0)
}
}
impl W {
#[doc = "Bits 0:11 - ADC offset number 1 offset level"]
#[inline(always)]
#[must_use]
pub fn offset1(&mut self) -> OFFSET1_W<OFR1_SPEC, 0> {
OFFSET1_W::new(self)
}
#[doc = "Bits 26:30 - ADC offset number 1 channel selection"]
#[inline(always)]
#[must_use]
pub fn offset1_ch(&mut self) -> OFFSET1_CH_W<OFR1_SPEC, 26> {
OFFSET1_CH_W::new(self)
}
#[doc = "Bit 31 - ADC offset number 1 enable"]
#[inline(always)]
#[must_use]
pub fn offset1_en(&mut self) -> OFFSET1_EN_W<OFR1_SPEC, 31> {
OFFSET1_EN_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 = "ADC offset number 1 register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ofr1::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 [`ofr1::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct OFR1_SPEC;
impl crate::RegisterSpec for OFR1_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`ofr1::R`](R) reader structure"]
impl crate::Readable for OFR1_SPEC {}
#[doc = "`write(|w| ..)` method takes [`ofr1::W`](W) writer structure"]
impl crate::Writable for OFR1_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets OFR1 to value 0"]
impl crate::Resettable for OFR1_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use rtm::UserProfile;
/// Retrieves a user's profile information.
///
/// Wraps https://api.slack.com/methods/users.profile.get
#[derive(Clone, Debug, Serialize, new)]
pub struct GetRequest {
/// User to retrieve profile info for
#[new(default)]
pub user: Option<::UserId>,
/// Include labels for each ID in custom profile fields
#[new(default)]
pub include_labels: Option<bool>,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct GetResponse {
ok: bool,
pub profile: Option<UserProfile>,
}
/// Set the profile information for a user.
///
/// Wraps https://api.slack.com/methods/users.profile.set
#[derive(Clone, Debug, Serialize, new)]
pub struct SetRequest<'a> {
/// ID of user to change. This argument may only be specified by team admins on paid teams.
#[new(default)]
pub user: Option<::UserId>,
/// Collection of key:value pairs presented as a URL-encoded JSON hash.
#[new(default)]
pub profile: Option<&'a str>,
/// Name of a single key to set. Usable only if profile is not passed.
#[new(default)]
pub name: Option<&'a str>,
/// Value to set a single key to. Usable only if profile is not passed.
#[new(default)]
pub value: Option<&'a str>,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SetResponse {
ok: bool,
pub profile: Option<UserProfile>,
}
|
// Copyright 2020 The RustABC Authors.
//
// Code is licensed under Apache License, Version 2.0.
pub mod compare_functions;
|
use std::cmp::Ordering;
use std::collections::{BinaryHeap, HashMap};
use crate::util::lines_from_file;
pub fn day15() {
println!("== Day 15 ==");
let input = lines_from_file("src/day15/input.txt");
let a = part_a(&input);
println!("Part A: {}", a);
let b = part_b(&input);
println!("Part B: {}", b);
}
#[derive(Copy, Clone, Hash, Eq, PartialEq, Debug)]
struct Node {
row: usize,
col: usize,
}
impl Ord for Node {
fn cmp(&self, other: &Self) -> Ordering {
self.row.cmp(&other.row)
.then_with(|| self.col.cmp(&other.col))
}
}
impl PartialOrd for Node {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
#[derive(Copy, Clone, Hash, Eq, PartialEq, Debug)]
struct Edge {
node: Node,
cost: u32,
}
#[derive(Copy, Clone, Hash, Eq, PartialEq, Debug)]
struct State {
cost: u32,
position: Node,
}
impl Ord for State {
fn cmp(&self, other: &Self) -> Ordering {
// Flip to make min-heap
other.cost.cmp(&self.cost)
.then_with(|| self.position.cmp(&other.position))
}
}
impl PartialOrd for State {
// Same as for ord
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
fn part_a(input: &Vec<String>) -> u32 {
let cavern: Vec<Vec<u32>> = input.iter()
.map(|l| l.chars().collect::<Vec<char>>())
.map(|ca| ca.iter().map(|c| c.to_digit(10).unwrap()).collect::<Vec<u32>>())
.collect();
let edges = to_edges(&cavern, 1);
let option = shortest_path(&edges, Node { row: 0, col: 0 }, Node { row: cavern.len() - 1, col: cavern.iter().next().unwrap().len() - 1 });
option.unwrap()
}
fn part_b(input: &Vec<String>) -> u32 {
let cavern: Vec<Vec<u32>> = input.iter()
.map(|l| l.chars().collect::<Vec<char>>())
.map(|ca| ca.iter().map(|c| c.to_digit(10).unwrap()).collect::<Vec<u32>>())
.collect();
let edges = to_edges(&cavern, 5);
let option = shortest_path(&edges, Node { row: 0, col: 0 }, Node { row: cavern.len() * 5 - 1, col: cavern.iter().next().unwrap().len() * 5 - 1 });
option.unwrap()
}
fn to_edges(cavern: &Vec<Vec<u32>>, num_tile: u32) -> HashMap<Node, Vec<Edge>> {
let rd = [-1, 0, 1, 0];
let cd = [0, -1, 0, 1];
let mut edges: HashMap<Node, Vec<Edge>> = HashMap::new();
let orig_max_rows = cavern.len();
let orig_max_cols = cavern.iter().next().unwrap().len();
let max_rows = orig_max_rows * num_tile as usize;
let max_cols = orig_max_cols * num_tile as usize;
for r in 0..max_rows {
for c in 0..max_cols {
let this_node = Node { row: r, col: c };
let mut adjacent: Vec<Edge> = Vec::new();
for i in 0..rd.len() {
let rr = r as i32 + rd[i];
let cc = c as i32 + cd[i];
if rr >= 0 && rr < max_rows as i32 && cc >= 0 && cc < max_cols as i32 {
let other_node = Node { row: rr as usize, col: cc as usize };
let rrr = rr as usize % orig_max_rows;
let ccc = cc as usize % orig_max_cols;
let orig_cost = cavern.get(rrr).unwrap().get(ccc).unwrap();
let add_for_row = (rr as usize / orig_max_rows) as u32;
let add_for_col = (cc as usize / orig_max_cols) as u32;
let mut cost = *orig_cost + add_for_row + add_for_col;
while cost > 9 {
cost -= 9;
}
adjacent.push(Edge { node: other_node, cost });
}
}
edges.insert(this_node, adjacent);
}
}
edges
}
fn shortest_path(edges: &HashMap<Node, Vec<Edge>>, start: Node, end: Node) -> Option<u32> {
let mut dist: HashMap<Node, u32> = HashMap::from_iter(edges.iter().map(|(k, _v)| (*k, u32::MAX)));
let mut heap = BinaryHeap::new();
*dist.entry(start).or_default() = 0;
heap.push(State { cost: 0, position: start });
while let Some(State { cost, position }) = heap.pop() {
if position == end {
return Some(cost);
}
if cost > *dist.get(&position).unwrap() {
continue;
}
for edge in edges.get(&position).unwrap() {
let next = State { cost: cost + edge.cost, position: edge.node };
if next.cost < *dist.get(&next.position).unwrap() {
heap.push(next);
*dist.entry(next.position).or_default() = next.cost;
}
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn part_a_test_input() {
let filename = "src/day15/test-input.txt";
let input = lines_from_file(filename);
let result = part_a(&input);
assert_eq!(40, result)
}
#[test]
fn part_a_real() {
let filename = "src/day15/input.txt";
let input = lines_from_file(filename);
let result = part_a(&input);
assert_eq!(790, result)
}
#[test]
fn to_edges_t_1() {
let input = vec![
vec![1, 2],
vec![3, 4],
];
let expected: HashMap<Node, Vec<Edge>> = HashMap::from([
(Node { row: 0, col: 0 }, vec![
Edge { node: Node { row: 0, col: 1 }, cost: 2 },
Edge { node: Node { row: 1, col: 0 }, cost: 3 }]
),
(Node { row: 0, col: 1 }, vec![
Edge { node: Node { row: 0, col: 0 }, cost: 1 },
Edge { node: Node { row: 1, col: 1 }, cost: 4 }]
),
(Node { row: 1, col: 0 }, vec![
Edge { node: Node { row: 0, col: 0 }, cost: 1 },
Edge { node: Node { row: 1, col: 1 }, cost: 4 }]
),
(Node { row: 1, col: 1 }, vec![
Edge { node: Node { row: 0, col: 1 }, cost: 2 },
Edge { node: Node { row: 1, col: 0 }, cost: 3 }]
)
]);
let result = to_edges(&input, 1);
println!("{:?}", result);
for (k, v) in expected.iter() {
let rv = result.get(k).unwrap();
println!("{:?}", v);
println!("{:?}", rv);
assert!(rv.iter().all(|item| v.contains(item)));
assert!(v.iter().all(|item| rv.contains(item)));
}
}
#[test]
fn to_edges_t_2() {
let input = vec![
vec![1, 2],
vec![3, 4],
];
let input_like = vec![
vec![1, 2, 2, 3],
vec![3, 4, 4, 5],
vec![2, 3, 3, 4],
vec![4, 5, 5, 6],
];
let result = to_edges(&input, 2);
let result_like = to_edges(&input_like, 1);
for (k, v) in result_like.iter() {
let rv = result.get(k).unwrap();
assert!(rv.iter().all(|item| v.contains(item)));
assert!(v.iter().all(|item| rv.contains(item)));
}
}
#[test]
fn part_b_test_input() {
let filename = "src/day15/test-input.txt";
let input = lines_from_file(filename);
let result = part_b(&input);
assert_eq!(315, result)
}
#[test]
fn part_b_real() {
let filename = "src/day15/input.txt";
let input = lines_from_file(filename);
let result = part_b(&input);
assert_eq!(2998, result)
}
}
|
use std::path::PathBuf;
use log::*;
use crate::agent;
use crate::conf::*;
pub struct PlayArgs {
pub path: PathBuf,
}
pub async fn play(args: &PlayArgs) -> Option<bool> {
// Attempt to parse configuration.
let file = std::fs::File::open(&args.path).expect("Could not open file");
let conf: Conf = serde_json::from_reader(&file).expect("Could not read file");
let number_of_children = conf.children.len();
let (tcollect, mut rcollect) = tokio::sync::mpsc::channel(32);
// Collect responses.
let collector = tokio::spawn(async move {
let mut yeas = 0usize;
let mut nays = 0usize;
let mut result = None;
debug!(target: "collector", "Starting");
while let Some(msg) = rcollect.recv().await {
debug!(target: "collector", "Treating {}", msg);
if msg {
yeas += 1;
if yeas >= number_of_children / 2 {
// We have a quorum, no need to proceed.
result = Some(true);
break;
}
} else {
nays += 1;
if nays >= number_of_children / 2 {
// We have a quorum, no need to proceed.
result = Some(false);
break;
}
}
debug!(target: "play",
"Collector: yeas {}, nays {}, we should continue",
yeas, nays
);
}
debug!(target: "collector", "Done");
return result;
});
// Talk to each agent.
let tasks: Vec<_> = {
// Make sure that `tcollect` is fully dropped once all tasks are complete.
let tcollect = tcollect;
conf.children.iter().cloned().map(|child| {
let remote = agent::RemoteAgent::new(child.clone());
let mut tcollect = tcollect.clone();
tokio::spawn(async move {
match remote.call(&agent::Message::GetValue).await {
Ok(agent::Response::Certificate(agent::Certificate { value, .. })) => {
debug!(target: "play", "Play: Received value {} from remote agent", value);
// Ignore errors: the collector may have finished already.
let _ = tcollect.send(value).await;
}
Ok(other) => {
debug!(target: "play", "Bad response from child {pid} on port {port}: {response:?}",
pid = child.pid,
port = child.socket,
response = other
);
}
Err(error) => {
debug!(target: "play", "Could not communicate with child {pid} on port {port}: {error:?}, skipping child.",
pid = child.pid,
port = child.socket,
error = error
);
}
}
})
}).collect()
};
for task in tasks.into_iter() {
task.await.unwrap();
}
let result = collector.await.unwrap();
match result {
Some(true) => debug!(target: "play", "The value was 'true'"),
Some(false) => debug!(target: "play", "The value was 'false'"),
None => debug!(target: "play", "Not enough participants to determine value"),
};
result
}
|
use crate::audio_decoder::AudioDecoder;
use crate::filter_graph::FilterGraph;
use crate::format_context::FormatContext;
use crate::order::input::Input;
use crate::stream::Stream;
use crate::subtitle_decoder::SubtitleDecoder;
use crate::tools;
use crate::video_decoder::VideoDecoder;
use ffmpeg_sys_next::AVMediaType;
#[derive(Debug)]
pub struct DecoderFormat {
pub context: FormatContext,
pub audio_decoders: Vec<AudioDecoder>,
pub subtitle_decoders: Vec<SubtitleDecoder>,
pub video_decoders: Vec<VideoDecoder>,
}
impl DecoderFormat {
pub fn new(graph: &mut FilterGraph, input: &Input) -> Result<Self, String> {
match input {
Input::VideoFrames {
path,
frames,
label,
codec,
width,
height,
..
} => {
let audio_decoders = vec![];
let subtitle_decoders = vec![];
let mut video_decoders = vec![];
let mut context = FormatContext::new(path)?;
context.open_input()?;
context.set_frames_addresses(frames);
let identifier = if let Some(ref identifier) = label {
identifier.clone()
} else {
tools::random_string(8)
};
let video_decoder =
VideoDecoder::new_with_codec(identifier.clone(), codec, *width, *height, 0)?;
let video_stream = Stream::new(context.get_stream(0))?;
graph.add_input_from_video_decoder(&identifier, &video_decoder, video_stream)?;
video_decoders.push(video_decoder);
Ok(DecoderFormat {
context,
audio_decoders,
subtitle_decoders,
video_decoders,
})
}
Input::Streams { path, streams, .. } => {
let mut audio_decoders = vec![];
let mut subtitle_decoders = vec![];
let mut video_decoders = vec![];
let mut context = FormatContext::new(path)?;
context.open_input()?;
for stream in streams {
let identifier = if let Some(ref identifier) = stream.label {
identifier.clone()
} else {
tools::random_string(8)
};
match context.get_stream_type(stream.index as isize) {
AVMediaType::AVMEDIA_TYPE_VIDEO => {
let video_decoder =
VideoDecoder::new(identifier.clone(), &context, stream.index as isize)?;
let video_stream = Stream::new(context.get_stream(stream.index as isize))?;
graph.add_input_from_video_decoder(&identifier, &video_decoder, video_stream)?;
video_decoders.push(video_decoder);
}
AVMediaType::AVMEDIA_TYPE_AUDIO => {
let audio_decoder =
AudioDecoder::new(identifier.clone(), &context, stream.index as isize)?;
graph.add_input_from_audio_decoder(&identifier, &audio_decoder)?;
audio_decoders.push(audio_decoder);
}
AVMediaType::AVMEDIA_TYPE_SUBTITLE => {
let subtitle_decoder =
SubtitleDecoder::new(identifier.clone(), &context, stream.index as isize)?;
subtitle_decoders.push(subtitle_decoder);
}
_ => {}
}
}
Ok(DecoderFormat {
context,
audio_decoders,
subtitle_decoders,
video_decoders,
})
}
}
}
}
|
use std::error::Error;
use std::fs::File;
use std::io::{Read, Write};
use std::process::Command;
use syn::visit_mut::VisitMut;
use syn::{Block, Expr, Type};
/// TODO
/// * string literals
/// * Slices should be translated into raw pointers?
/// * Slice indexing does not work
/// * Alloc interface
fn main() -> Result<(), Box<dyn Error>> {
env_logger::init();
if std::env::var_os("AMARGO_RUSTC").is_some() {
main_rustc()
} else {
let exit = Command::new("cargo")
// We don't respect existing RUSTC_WRAPPER
.env("RUSTC_WRAPPER", "amargo")
.env("AMARGO_RUSTC", "on")
.args(std::env::args().skip(1))
.spawn()?
.wait()?;
if !exit.success() {
std::process::exit(exit.code().unwrap_or(1));
}
Ok(())
}
}
fn main_rustc() -> Result<(), Box<dyn Error>> {
let mut args: Vec<_> = std::env::args().skip(2).collect();
let _any = transform_args(&mut args)?;
let exit = Command::new("rustc").args(&args).spawn()?.wait()?;
if exit.success() {
Ok(())
} else {
Err(StringError("rustc invocation failed".into()))?
}
}
fn transform_args(args: &mut [String]) -> Result<impl std::any::Any, Box<dyn Error>> {
let (index, input_file_name) = match find_input_file(args) {
None => return Ok(None),
Some(res) => res,
};
let source = {
let mut s = String::new();
let mut file = File::open(input_file_name)?;
file.read_to_string(&mut s)?;
s
};
let code = transform_source(&source)?;
let mut out_file = tempfile::NamedTempFile::new()?;
out_file.write(format!("{}", code).as_bytes())?;
let new_path = out_file.into_temp_path();
// Best-effort only
let _ = Command::new("rustfmt").arg(&new_path).spawn()?.wait()?;
args[index] = new_path.to_string_lossy().to_string();
Ok(Some(new_path))
}
fn find_input_file(args: &[String]) -> Option<(usize, &String)> {
let mut skip = false;
for (i, arg) in args.iter().enumerate() {
if arg == "-" {
return None;
} else if arg.starts_with("-") {
skip = true;
continue;
} else if skip {
skip = false;
continue;
}
if arg.ends_with(".rs") {
return Some((i, arg));
}
}
return None;
}
#[derive(Debug)]
struct StringError(String);
impl std::fmt::Display for StringError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::Display::fmt(&format!("Error: {}", self.0), f)
}
}
impl Error for StringError {}
fn transform_source(source: &str) -> Result<String, Box<dyn Error>> {
let mut ast = syn::parse_file(&source)?;
let mut marker = MarkerVisitor;
marker.visit_file_mut(&mut ast);
log::debug!("{}", quote::quote! {#ast});
let mut replacer = ReplacerVisitor;
replacer.visit_file_mut(&mut ast);
let code = quote::quote! {
#![allow(unused_mut)]
#![allow(unused_unsafe)]
#ast
};
log::debug!("{}", code);
Ok(format!("{}", code))
}
struct MarkerVisitor;
impl VisitMut for MarkerVisitor {
fn visit_expr_mut(&mut self, expr: &mut Expr) {
match expr {
Expr::Reference(reference) => {
let inner = &reference.expr;
let quoted: Expr = syn::parse_quote! {
__make_unsafe![#inner]
};
*expr = quoted;
}
Expr::Unary(syn::ExprUnary {
op: syn::UnOp::Deref(..),
expr: inner,
..
}) => {
let quoted: Expr = syn::parse_quote! {
__make_unsafe_deref![#inner]
};
*expr = quoted;
}
Expr::Assign(syn::ExprAssign { left, right, .. }) => {
if let Expr::Unary(syn::ExprUnary {
op: syn::UnOp::Deref(..),
expr: ref inner,
..
}) = **left
{
let quoted: Expr = syn::parse_quote! {
__make_unsafe_assign_deref![{#inner} {#right}]
};
*expr = quoted;
}
}
_ => {}
}
syn::visit_mut::visit_expr_mut(self, expr);
}
}
struct ReplacerVisitor;
impl VisitMut for ReplacerVisitor {
fn visit_expr_mut(&mut self, expr: &mut Expr) {
if let Expr::Macro(exprmacro) = expr {
if exprmacro.mac.path.is_ident("__make_unsafe") {
let inner_expr: Expr =
syn::parse2(exprmacro.mac.tokens.clone()).expect("Unexpected parsing error");
let new_expr: Expr = syn::parse_quote! {
&#inner_expr as *const _ as *mut _
};
*expr = new_expr;
} else if exprmacro.mac.path.is_ident("__make_unsafe_deref") {
let inner_expr: Expr =
syn::parse2(exprmacro.mac.tokens.clone()).expect("Unexpected parsing error");
let new_expr: Expr = syn::parse_quote! {
unsafe { *#inner_expr }
};
*expr = new_expr;
} else if exprmacro.mac.path.is_ident("__make_unsafe_assign_deref") {
let mut tokens = exprmacro.mac.tokens.clone().into_iter();
let left = expr_from_tree(tokens.next().expect("Unexpected empty tokens"));
let right = expr_from_tree(tokens.next().expect("Unexpected empty tokens"));
let new_expr: Expr = syn::parse_quote! {
unsafe { *#left = #right }
};
*expr = new_expr;
}
}
syn::visit_mut::visit_expr_mut(self, expr);
}
fn visit_type_mut(&mut self, ty: &mut Type) {
if let Type::Reference(reference) = ty {
let inner = reference.elem.clone();
let quoted: Type = syn::parse_quote! {
*mut #inner
};
*ty = quoted;
}
syn::visit_mut::visit_type_mut(self, ty);
}
fn visit_item_fn_mut(&mut self, fun: &mut syn::ItemFn) {
let inner = &fun.block;
let block: Block = syn::parse_quote! {
{ unsafe #inner }
};
*fun.block = block;
syn::visit_mut::visit_item_fn_mut(self, fun);
}
fn visit_impl_item_method_mut(&mut self, method: &mut syn::ImplItemMethod) {
let inner = &method.block;
let block: Block = syn::parse_quote! {
{ unsafe #inner }
};
method.block = block;
syn::visit_mut::visit_impl_item_method_mut(self, method);
}
fn visit_trait_item_method_mut(&mut self, method: &mut syn::TraitItemMethod) {
let default: Option<Block> = method.default.as_mut().map(|inner| {
syn::parse_quote! {
{ unsafe #inner }
}
});
method.default = default;
syn::visit_mut::visit_trait_item_method_mut(self, method);
}
}
fn expr_from_tree(tree: proc_macro2::TokenTree) -> proc_macro2::TokenStream {
match tree {
proc_macro2::TokenTree::Group(group) => group.stream(),
_ => unreachable!(),
}
}
|
use std::collections::HashMap;
pub mod part1;
pub mod part2;
pub fn default_input() -> &'static str {
include_str!("input")
}
pub fn run() {
part1::run();
part2::run();
}
pub fn parse_input(input : &str) -> Vec<HashMap<String, String>> {
input.split("\n\n")
.map(|p| {
let map : HashMap<String, String> = p.split(&['\n', ' '][..])
.map(|l| {
let split : Vec<_> = l.split(":").collect();
(String::from(split[0].trim()), String::from(split[1]))})
.collect();
map
})
.collect()
} |
use super::error::ProtocolError;
pub mod blink;
pub mod breathe;
pub mod neon;
pub mod steady;
#[derive(Debug, Clone, Copy)]
pub enum Effect {
Respiration(breathe::Speed),
Steady(steady::Brightnes),
Neon(neon::Speed),
}
impl Default for Effect {
fn default() -> Self {
Self::Respiration(breathe::Speed::default())
}
}
#[derive(Debug, Clone, Copy)]
pub enum Config {
Steady(steady::Brightnes),
Breathe(breathe::Speed),
BlinkEffect(blink::Frequency, blink::Times, Effect),
SteadyEffect(steady::EffectTime, Effect),
}
impl Default for Config {
fn default() -> Self {
Self::Breathe(breathe::Speed::default())
}
}
impl Config {
pub fn from_raw(
led_mode: u8,
led_arg1: u8,
led_arg2: u8,
led_arg3: u8,
) -> Result<Self, ProtocolError> {
Ok(match led_mode {
0x28 => Config::Steady(steady::Brightnes::from_raw(led_arg3)?),
0x22 => Config::Breathe(breathe::Speed::from_raw(led_arg3)?),
0x42 | 0x44 | 0x48 => {
let frequency = blink::Frequency::from_raw(led_arg1)?;
let times = blink::Times::from_raw(led_arg2)?;
let effect = match led_mode {
0x42 => Effect::Respiration(breathe::Speed::from_raw(led_arg3)?),
0x44 => Effect::Neon(neon::Speed::from_raw(led_arg3)?),
0x48 => Effect::Steady(steady::Brightnes::from_raw(led_arg3)?),
_ => return Err(ProtocolError::InvalidRawInput),
};
Config::BlinkEffect(frequency, times, effect)
}
0x82 | 0x84 | 0x88 => {
let time = steady::EffectTime::from_raw(led_arg1)?;
let effect = match led_mode {
0x82 => Effect::Respiration(breathe::Speed::from_raw(led_arg3)?),
0x84 => Effect::Neon(neon::Speed::from_raw(led_arg3)?),
0x88 => Effect::Steady(steady::Brightnes::from_raw(led_arg3)?),
_ => return Err(ProtocolError::InvalidRawInput),
};
Config::SteadyEffect(time, effect)
}
_ => return Err(ProtocolError::InvalidRawInput),
})
}
pub fn to_raw(&self) -> (u8, u8, u8, u8) {
let (led_mode, led_arg1, led_arg2, led_arg3) = match self {
Config::Steady(b) => (0x28, 0x0, 0x0, b.to_raw()),
Config::Breathe(s) => (0x22, 0x0, 0x0, s.to_raw()),
Config::BlinkEffect(f, t, e) => {
let f = f.to_raw();
let t = t.to_raw();
let (led_mode, led_arg3) = match e {
Effect::Respiration(s) => (0x42, s.to_raw()),
Effect::Neon(s) => (0x44, s.to_raw()),
Effect::Steady(b) => (0x48, b.to_raw()),
};
(led_mode, f, t, led_arg3)
}
Config::SteadyEffect(t, e) => {
let t = t.to_raw();
let (led_mode, led_arg3) = match e {
Effect::Respiration(s) => (0x82, s.to_raw()),
Effect::Neon(s) => (0x84, s.to_raw()),
Effect::Steady(b) => (0x88, b.to_raw()),
};
(led_mode, t, 0x0, led_arg3)
}
};
(led_mode, led_arg1, led_arg2, led_arg3)
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.