text stringlengths 8 4.13M |
|---|
#[doc = "Reader of register CH9_DBG_CTDREQ"]
pub type R = crate::R<u32, super::CH9_DBG_CTDREQ>;
#[doc = "Reader of field `CH9_DBG_CTDREQ`"]
pub type CH9_DBG_CTDREQ_R = crate::R<u8, u8>;
impl R {
#[doc = "Bits 0:5"]
#[inline(always)]
pub fn ch9_dbg_ctdreq(&self) -> CH9_DBG_CTDREQ_R {
CH9_DBG_CTDREQ_R::new((self.bits & 0x3f) as u8)
}
}
|
#[doc = "Reader of register WL_ENABLE"]
pub type R = crate::R<u32, super::WL_ENABLE>;
#[doc = "Writer for register WL_ENABLE"]
pub type W = crate::W<u32, super::WL_ENABLE>;
#[doc = "Register WL_ENABLE `reset()`'s with value 0"]
impl crate::ResetValue for super::WL_ENABLE {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `WL_ENABLE`"]
pub type WL_ENABLE_R = crate::R<u16, u16>;
#[doc = "Write proxy for field `WL_ENABLE`"]
pub struct WL_ENABLE_W<'a> {
w: &'a mut W,
}
impl<'a> WL_ENABLE_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u16) -> &'a mut W {
self.w.bits = (self.w.bits & !0xffff) | ((value as u32) & 0xffff);
self.w
}
}
impl R {
#[doc = "Bits 0:15 - Stores the valid entry bit corresponding to each of the eight device address stored in the whitelist. 1 - White list entry is Valid 0 - White list entry is Invalid"]
#[inline(always)]
pub fn wl_enable(&self) -> WL_ENABLE_R {
WL_ENABLE_R::new((self.bits & 0xffff) as u16)
}
}
impl W {
#[doc = "Bits 0:15 - Stores the valid entry bit corresponding to each of the eight device address stored in the whitelist. 1 - White list entry is Valid 0 - White list entry is Invalid"]
#[inline(always)]
pub fn wl_enable(&mut self) -> WL_ENABLE_W {
WL_ENABLE_W { w: self }
}
}
|
#[derive(Debug)]
pub struct Stack <T>
{
stack: Vec<T>,
}
impl <T> Stack<T>
{
pub fn new (head: T) -> Self
{
Stack { stack: vec![ head ] }
}
pub fn head (&mut self) -> &mut T
{
self.stack.last_mut().expect("stack_empty")
}
pub fn push (&mut self, head: T)
{
self.stack.push(head);
}
pub fn pop (&mut self)
{
self.stack.pop().expect("stack_pop_empty");
}
/*
pub fn take (mut self) -> T
{
assert!(self.stack.len() == 1, "stack_take_1");
self.stack.pop().unwrap()
}
*/
}
|
use walkdir::WalkDir;
use std::{collections::HashMap, hash::Hasher, io, path::{Path, PathBuf}};
use std::fs::File;
use twox_hash::XxHash64;
use gumdrop::Options;
use std::fs;
#[derive(Debug, Options)]
struct MyOptions {
#[options(help = "Root directory to scan")]
root: String,
#[options(help = "Enable destructive relinking")]
relink: bool,
#[options(help = "Perform soft linking")]
softlink: bool,
#[options(help = "Prefer originals if containing this string")]
resolve_filter: Option<String>,
}
struct HashWriter<T: Hasher>(T);
impl<T: Hasher> io::Write for HashWriter<T> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0.write(buf);
Ok(buf.len())
}
fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
self.write(buf).map(|_| ())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
/// Produce a hash from a file
fn hash_file(file: &Path) -> u64{
let mut f = File::open(file).expect("Unable to open file");
let hasher = XxHash64::with_seed(0);
let mut hw = HashWriter(hasher);
io::copy(&mut f, &mut hw).expect("Unable to copy data");
let hasher = hw.0;
hasher.finish()
}
/// Link a file, optionally as soft link.
fn link(src: &Path, dest: &Path, soft: bool) -> io::Result<()> {
if soft {
#[cfg(target_os = "windows")]
{
std::os::windows::fs::symlink_file(src, dest)
}
#[cfg(target_family = "unix")]
{
std::os::unix::fs::symlink(src, dest)
}
}
else {
fs::hard_link(src, dest)
}
}
fn safe_link(src: &Path, dest: &Path, soft: bool) {
let dest_backup = dest.with_extension("rdup");
let _ = fs::rename(dest, &dest_backup);
match link(src, dest, soft) {
Ok(_) => {
let _ = fs::remove_file(dest_backup);
},
Err(e) => {
// Rename back, link failed
let _ = fs::rename(dest_backup, dest);
eprintln!("Could not link {:?}", e);
}
}
}
/// Resolve a duplicate
fn duplicate_resolver(duplicates: &Vec<PathBuf>, destructive: bool, softlink: bool) {
// Safeguard against having no duplicates
if duplicates.len() < 2 {
return
}
if let Some(source) = duplicates.first() {
let dest = &duplicates[1..];
if destructive {
println!("Relinking to {:?}:", source);
for duplicate in dest {
println!("\tLinking {:?}", duplicate);
safe_link(&source, &duplicate, softlink);
}
}
}
}
fn main() {
let opts = MyOptions::parse_args_or_exit(gumdrop::ParsingStyle::AllOptions);
if opts.root == "" {
eprintln!("You must supply a --root parameter");
return;
}
let mut db: HashMap<u64, Vec<PathBuf>> = HashMap::new();
for entry in WalkDir::new(opts.root).into_iter()
.filter_map(|e| e.ok())
.filter(|e| e.path().is_file())
.filter(|f| !f.path_is_symlink()) {
// TODO: skip file if it's any type of link
if entry.path().read_link().is_ok() {
continue;
}
let hash = hash_file(entry.path());
let e = db.entry(hash).or_default();
e.push(entry.path().to_owned());
}
// at this point we have all files ordered by hash, with filenames. Everything with more than one entry is a duplicate.
for entry in db.values() {
if entry.len() > 1 {
duplicate_resolver(entry, opts.relink, opts.softlink);
}
}
} |
use cocoa::base::{class, id};
use objc::runtime::BOOL;
use MTLCompareFunction;
pub trait MTLDepthStencilDescriptor {
unsafe fn new(_: Self) -> id {
msg_send![class("MTLDepthStencilDescriptor"), new]
}
unsafe fn depthCompareFunction(self) -> MTLCompareFunction;
unsafe fn setDepthCompareFunction(self, depthCompareFunction: MTLCompareFunction);
unsafe fn depthWriteEnabled(self) -> BOOL;
unsafe fn setDepthWriteEnabled(self, depthWriteEnabled: BOOL);
unsafe fn backFaceStencil(self) -> id;
unsafe fn setBackFaceStencil(self, backFaceStencil: id);
unsafe fn frontFaceStencil(self) -> id;
unsafe fn setFrontFaceStencil(self, frontFaceStencil: id);
unsafe fn label(self) -> id;
unsafe fn setLabel(self, label: id);
unsafe fn copy(self) -> id;
}
impl MTLDepthStencilDescriptor for id {
unsafe fn depthCompareFunction(self) -> MTLCompareFunction {
msg_send![self, depthCompareFunction]
}
unsafe fn setDepthCompareFunction(self, depthCompareFunction: MTLCompareFunction) {
msg_send![self, setDepthCompareFunction:depthCompareFunction]
}
unsafe fn depthWriteEnabled(self) -> BOOL {
msg_send![self, depthWriteEnabled]
}
unsafe fn setDepthWriteEnabled(self, depthWriteEnabled: BOOL) {
msg_send![self, setDepthWriteEnabled:depthWriteEnabled]
}
unsafe fn backFaceStencil(self) -> id {
msg_send![self, backFaceStencil]
}
unsafe fn setBackFaceStencil(self, backFaceStencil: id) {
msg_send![self, setBackFaceStencil:backFaceStencil]
}
unsafe fn frontFaceStencil(self) -> id {
msg_send![self, frontFaceStencil]
}
unsafe fn setFrontFaceStencil(self, frontFaceStencil: id) {
msg_send![self, setFrontFaceStencil:frontFaceStencil]
}
unsafe fn label(self) -> id {
msg_send![self, label]
}
unsafe fn setLabel(self, label: id) {
msg_send![self, setLabel:label]
}
unsafe fn copy(self) -> id {
msg_send![self, copy]
}
}
|
// include!("lib.rs");
fn main() {
// let tweet = Tweet{
// username: String::from("twttr"),
// content: String::from("first tweet ever")
// };
//
// println!("Summarize tweet: {}", tweet.summarize());
}
fn add(a: i32, b:i32) -> i32{
a+b
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_add(){
assert_eq!(add(1,2), 3);
assert_ne!(add(1,2), 4);
}
} |
use std::borrow::Cow;
use scroll::{ctx::TryFromCtx, Endian, Pread};
use crate::common::*;
use crate::msf::Stream;
/// Magic bytes identifying the string name table.
///
/// This value is declared as `NMT::verHdr` in `nmt.h`.
const PDB_NMT_HDR: u32 = 0xEFFE_EFFE;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum StringTableHashVersion {
/// Default hash method used for reverse string lookups.
///
/// The hash function has originally been defined in `LHashPbCb`.
LongHash = 1,
/// Revised hash method used for reverse string lookups.
///
/// The hash function has originally been defined in `LHashPbCbV2`.
LongHashV2 = 2,
}
impl StringTableHashVersion {
fn parse_u32(value: u32) -> Result<Self> {
match value {
1 => Ok(Self::LongHash),
2 => Ok(Self::LongHashV2),
_ => Err(Error::UnimplementedFeature(
"unknown string table hash version",
)),
}
}
}
/// Raw header of the string table stream.
#[repr(C)]
#[derive(Clone, Copy, Debug)]
struct StringTableHeader {
/// Magic bytes of the string table.
magic: u32,
/// Version of the hash table after the names.
hash_version: u32,
/// The size of all names in bytes.
names_size: u32,
}
impl<'t> TryFromCtx<'t, Endian> for StringTableHeader {
type Error = scroll::Error;
fn try_from_ctx(this: &'t [u8], le: Endian) -> scroll::Result<(Self, usize)> {
let mut offset = 0;
let data = Self {
magic: this.gread_with(&mut offset, le)?,
hash_version: this.gread_with(&mut offset, le)?,
names_size: this.gread_with(&mut offset, le)?,
};
Ok((data, offset))
}
}
impl StringTableHeader {
/// Start index of the names buffer in the string table stream.
fn names_start(self) -> usize {
std::mem::size_of::<Self>()
}
/// End index of the names buffer in the string table stream.
fn names_end(self) -> usize {
self.names_start() + self.names_size as usize
}
}
/// The global string table of a PDB.
///
/// The string table is a two-way mapping from offset to string and back. It can be used to resolve
/// [`StringRef`] offsets to their string values. Sometimes, it is also referred to as "Name table".
/// The mapping from string to offset has not been implemented yet.
///
/// Use [`PDB::string_table`](crate::PDB::string_table) to obtain an instance.
#[derive(Debug)]
pub struct StringTable<'s> {
header: StringTableHeader,
#[allow(dead_code)] // reason = "reverse-lookups through hash table not implemented"
hash_version: StringTableHashVersion,
stream: Stream<'s>,
}
impl<'s> StringTable<'s> {
pub(crate) fn parse(stream: Stream<'s>) -> Result<Self> {
let mut buf = stream.parse_buffer();
let header = buf.parse::<StringTableHeader>()?;
if header.magic != PDB_NMT_HDR {
return Err(Error::UnimplementedFeature(
"invalid string table signature",
));
}
// The string table should at least contain all names as C-strings. Their combined size is
// declared in the `names_size` header field.
if buf.len() < header.names_end() {
return Err(Error::UnexpectedEof);
}
let hash_version = StringTableHashVersion::parse_u32(header.hash_version)?;
// After the name buffer, the stream contains a closed hash table for reverse mapping. From
// the original header file (`nmi.h`):
//
// Strings are mapped into name indices using a closed hash table of NIs.
// To find a string, we hash it and probe into the table, and compare the
// string against each successive ni's name until we hit or find an empty
// hash table entry.
Ok(StringTable {
header,
hash_version,
stream,
})
}
}
impl<'s> StringTable<'s> {
/// Resolves a string value from this string table.
///
/// Errors if the offset is out of bounds, otherwise returns the raw binary string value.
pub fn get(&self, offset: StringRef) -> Result<RawString<'_>> {
if offset.0 >= self.header.names_size {
return Err(Error::UnexpectedEof);
}
let string_offset = self.header.names_start() + offset.0 as usize;
let data = &self.stream.as_slice()[string_offset..self.header.names_end()];
ParseBuffer::from(data).parse_cstring()
}
}
impl StringRef {
/// Resolves the raw string value of this reference.
///
/// This method errors if the offset is out of bounds of the string table. Use
/// [`PDB::string_table`](crate::PDB::string_table) to obtain an instance of the string table.
pub fn to_raw_string<'s>(self, strings: &'s StringTable<'_>) -> Result<RawString<'s>> {
strings.get(self)
}
/// Resolves and decodes the UTF-8 string value of this reference.
///
/// This method errors if the offset is out of bounds of the string table. Use
/// [`PDB::string_table`](crate::PDB::string_table) to obtain an instance of the string table.
pub fn to_string_lossy<'s>(self, strings: &'s StringTable<'_>) -> Result<Cow<'s, str>> {
strings.get(self).map(|r| r.to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::mem;
#[test]
fn test_string_table_header() {
assert_eq!(mem::size_of::<StringTableHeader>(), 12);
assert_eq!(mem::align_of::<StringTableHeader>(), 4);
}
}
|
#[cfg(unix)]
mod fuzzer;
#[cfg(unix)]
pub fn main() {
fuzzer::main();
}
#[cfg(not(unix))]
pub fn main() {
todo!("Frida not yet supported on this OS.");
}
|
use crate::name_resolution::TopLevelContext;
use crate::rustspec::*;
use core::iter::IntoIterator;
use core::slice::Iter;
use heck::TitleCase;
use itertools::Itertools;
use pretty::RcDoc;
use rustc_session::Session;
use rustc_span::DUMMY_SP;
use std::fs::File;
use std::io::Write;
use std::path;
use rustc_ast::node_id::NodeId;
use crate::rustspec_to_coq_base::*;
fn make_let_binding<'a>(
pat: RcDoc<'a, ()>,
typ: Option<RcDoc<'a, ()>>,
expr: RcDoc<'a, ()>,
toplevel: bool,
) -> RcDoc<'a, ()> {
RcDoc::as_string(if toplevel { "Definition" } else { "let" })
.append(RcDoc::space())
.append(
pat.append(match typ {
None => RcDoc::nil(),
Some(tau) => RcDoc::space()
.append(RcDoc::as_string(":"))
.append(RcDoc::space())
.append(tau),
})
.group(),
)
.append(RcDoc::space())
.append(RcDoc::as_string(":="))
.group()
.append(RcDoc::line().append(expr.group()))
.nest(2)
.append(if toplevel {
RcDoc::as_string(".")
} else {
RcDoc::space()
.append(RcDoc::as_string("in"))
.append(RcDoc::space())
})
}
fn make_uint_size_coercion<'a>(pat: RcDoc<'a, ()>) -> RcDoc<'a, ()> {
RcDoc::as_string("Definition")
.append(RcDoc::space())
.append(RcDoc::as_string("uint_size_in_"))
.append(pat.clone())
.append(RcDoc::as_string("(n : uint_size) : "))
.append(pat.clone())
.append(RcDoc::space())
.append(RcDoc::as_string(":= int_in_nat_mod n."))
.append(RcDoc::line())
.append(RcDoc::as_string("Coercion "))
.append(RcDoc::as_string("uint_size_in_"))
.append(pat.clone())
.append(RcDoc::as_string(" : uint_size >-> "))
.append(pat.clone())
.append(RcDoc::as_string("."))
}
fn translate_constructor<'a>(enum_name: TopLevelIdent) -> RcDoc<'a> {
RcDoc::as_string(enum_name.string)
}
fn translate_enum_name<'a>(enum_name: TopLevelIdent) -> RcDoc<'a> {
translate_toplevel_ident(enum_name)
}
fn translate_enum_case_name<'a>(
enum_name: BaseTyp,
case_name: TopLevelIdent,
explicit: bool,
) -> RcDoc<'a> {
match enum_name {
BaseTyp::Named(name, opts) => match opts {
None => translate_constructor(case_name),
Some(tyvec) => if explicit && tyvec.len() != 0 {
RcDoc::as_string("@")
} else {
RcDoc::nil()
}
.append(translate_constructor(case_name))
.append(
if (name.0).string == "Option" || (name.0).string == "Result" {
RcDoc::nil()
} else {
RcDoc::as_string("(")
.append(translate_toplevel_ident(name.0))
.append(RcDoc::as_string(")"))
},
)
.append(if explicit && tyvec.len() != 0 {
RcDoc::space().append(RcDoc::intersperse(
tyvec.into_iter().map(|(x, _)| translate_base_typ(x)),
RcDoc::space(),
))
} else {
RcDoc::nil()
}),
},
_ => panic!("should not happen"),
}
}
pub fn translate_base_typ<'a>(tau: BaseTyp) -> RcDoc<'a, ()> {
match tau {
BaseTyp::Bool => RcDoc::as_string("bool"),
BaseTyp::UInt8 => RcDoc::as_string("int8"),
BaseTyp::Int8 => RcDoc::as_string("int8"),
BaseTyp::UInt16 => RcDoc::as_string("int16"),
BaseTyp::Int16 => RcDoc::as_string("int16"),
BaseTyp::UInt32 => RcDoc::as_string("int32"),
BaseTyp::Int32 => RcDoc::as_string("int32"),
BaseTyp::UInt64 => RcDoc::as_string("int64"),
BaseTyp::Int64 => RcDoc::as_string("int64"),
BaseTyp::UInt128 => RcDoc::as_string("int128"),
BaseTyp::Int128 => RcDoc::as_string("int128"),
BaseTyp::Usize => RcDoc::as_string("uint_size"),
BaseTyp::Isize => RcDoc::as_string("int_size"),
BaseTyp::Str => RcDoc::as_string("string"),
BaseTyp::Seq(tau) => {
let tau: BaseTyp = tau.0;
RcDoc::as_string("seq")
.append(RcDoc::space())
.append(translate_base_typ(tau))
.group()
}
BaseTyp::Enum(_cases, _type_args) => {
unimplemented!()
}
BaseTyp::Array(size, tau) => {
let tau = tau.0;
RcDoc::as_string("nseq")
.append(RcDoc::space())
.append(translate_base_typ(tau))
.append(RcDoc::space())
.append(RcDoc::as_string(match &size.0 {
ArraySize::Ident(id) => format!("{}", id),
ArraySize::Integer(i) => format!("{}", i),
}))
.group()
}
BaseTyp::Named((ident, _span), args) => match args {
None => translate_ident(Ident::TopLevel(ident)),
Some(args) => make_paren(
translate_ident(Ident::TopLevel(ident))
.append(RcDoc::space())
.append(RcDoc::intersperse(
args.iter().map(|arg| translate_base_typ(arg.0.clone())),
RcDoc::space(),
)),
),
},
BaseTyp::Variable(id) => RcDoc::as_string(format!("t{}", id.0)),
BaseTyp::Tuple(args) => {
if args.len() == 0 {
RcDoc::as_string("unit")
} else {
make_typ_tuple(args.into_iter().map(|(arg, _)| translate_base_typ(arg)))
}
}
BaseTyp::NaturalInteger(_secrecy, modulo, _bits) => RcDoc::as_string("nat_mod")
.append(RcDoc::space())
.append(RcDoc::as_string(format!("0x{}", &modulo.0)))
.append(RcDoc::hardline()),
BaseTyp::Placeholder => panic!("Got unexpected type `Placeholder`: this should have been filled by during the typechecking phase."),
}
}
fn translate_typ<'a>((_, (tau, _)): Typ) -> RcDoc<'a, ()> {
translate_base_typ(tau)
}
fn translate_literal<'a>(lit: Literal) -> RcDoc<'a, ()> {
match lit {
Literal::Unit => RcDoc::as_string("tt"),
Literal::Bool(true) => RcDoc::as_string("true"),
Literal::Bool(false) => RcDoc::as_string("false"),
Literal::Int128(x) => RcDoc::as_string(format!("@repr WORDSIZE128 {}", x)),
Literal::UInt128(x) => RcDoc::as_string(format!("@repr WORDSIZE128 {}", x)),
Literal::Int64(x) => RcDoc::as_string(format!("@repr WORDSIZE64 {}", x)),
Literal::UInt64(x) => RcDoc::as_string(format!("@repr WORDSIZE64 {}", x)),
Literal::Int32(x) => RcDoc::as_string(format!("@repr WORDSIZE32 {}", x)),
Literal::UInt32(x) => RcDoc::as_string(format!("@repr WORDSIZE32 {}", x)),
Literal::Int16(x) => RcDoc::as_string(format!("@repr WORDSIZE16 {}", x)),
Literal::UInt16(x) => RcDoc::as_string(format!("@repr WORDSIZE16 {}", x)),
Literal::Int8(x) => RcDoc::as_string(format!("@repr WORDSIZE8 {}", x)),
Literal::UInt8(x) => RcDoc::as_string(format!("@repr WORDSIZE8 {}", x)),
Literal::Isize(x) => RcDoc::as_string(format!("isize {}", x)),
Literal::Usize(x) => RcDoc::as_string(format!("usize {}", x)),
Literal::UnspecifiedInt(_) => panic!("Got a `UnspecifiedInt` literal: those should have been resolved into concrete types during the typechecking phase"),
Literal::Str(msg) => RcDoc::as_string(format!("\"{}\"", msg)),
}
}
/// Returns the func name, as well as additional arguments to add when calling
/// the function in Coq
pub(crate) fn translate_func_name<'a>(
prefix: Option<Spanned<BaseTyp>>,
name: Ident,
top_ctx: &'a TopLevelContext,
args_ty: Vec<BaseTyp>,
) -> (
RcDoc<'a, ()>,
Vec<RcDoc<'a, ()>>,
Option<BaseTyp>,
Vec<(RcDoc<'a, ()>, RcDoc<'a, ()>)>,
) {
match prefix.clone() {
None => {
let name = translate_ident(name.clone());
match format!("{}", name.pretty(0)).as_str() {
// In this case, we're trying to apply a secret
// int constructor. The value it is applied to is
// a public integer of the same kind. So in Coq, that
// will amount to a classification operation
// TODO: may need to add type annotation here
x @ ("uint128" | "uint64" | "uint32" | "uint16" | "uint8" | "int128" | "int64"
| "int32" | "int16" | "int8") => (
RcDoc::as_string("secret"),
vec![],
Some(match x {
"uint128" => BaseTyp::UInt128,
"uint64" => BaseTyp::UInt64,
"uint32" => BaseTyp::UInt32,
"uint16" => BaseTyp::UInt16,
"uint8" => BaseTyp::UInt8,
"int128" => BaseTyp::Int128,
"int64" => BaseTyp::Int64,
"int32" => BaseTyp::Int32,
"int16" => BaseTyp::Int16,
"int8" => BaseTyp::Int8,
_ => panic!("Should not happen"),
}),
vec![],
),
_ => (name, vec![], None, vec![]),
}
}
Some((prefix, _)) => {
let (module_name, prefix_info) =
translate_prefix_for_func_name(prefix.clone(), top_ctx);
let mut result_typ = None;
let func_ident = translate_ident(name.clone());
let mut additional_args = Vec::new();
let mut extra_info = Vec::new();
// We add the modulo value for nat_mod
match (
format!("{}", module_name.pretty(0)).as_str(),
format!("{}", func_ident.pretty(0)).as_str(),
) {
(NAT_MODULE, "from_literal") | (NAT_MODULE, "pow2") => {
match &prefix_info {
FuncPrefix::NatMod(modulo, _) => {
if modulo == "unknown" {
additional_args.push(RcDoc::as_string("_"));
} else {
additional_args.push(RcDoc::as_string(format!("0x{}", modulo)));
}
result_typ = Some(prefix.clone());
}
_ => panic!(), // should not happen
}
}
_ => (),
};
// And the encoding length for certain nat_mod related function
match (
format!("{}", module_name.pretty(0)).as_str(),
format!("{}", func_ident.pretty(0)).as_str(),
) {
(NAT_MODULE, "to_public_byte_seq_le") | (NAT_MODULE, "to_public_byte_seq_be") => {
match &prefix_info {
FuncPrefix::NatMod(_, encoding_bits) => additional_args
.push(RcDoc::as_string(format!("{}", (encoding_bits + 7) / 8))),
_ => panic!(), // should not happen
}
}
_ => (),
};
// And decoding
match (
format!("{}", module_name.pretty(0)).as_str(),
format!("{}", func_ident.pretty(0)).as_str(),
) {
(NAT_MODULE, "from_byte_seq_le") | (NAT_MODULE, "from_byte_seq_be") => {
match &prefix_info {
FuncPrefix::NatMod(_modulo, _) => {
result_typ = Some(prefix.clone());
}
_ => panic!(), // should not happen
}
}
_ => (),
};
// Then the default value for seqs
match (
format!("{}", module_name.pretty(0)).as_str(),
format!("{}", func_ident.pretty(0)).as_str(),
) {
(ARRAY_MODULE, "new_")
| (SEQ_MODULE, "new_")
| (ARRAY_MODULE, "from_slice")
| (ARRAY_MODULE, "from_slice_range") => {
match &prefix_info {
FuncPrefix::Array(_, bt) | FuncPrefix::Seq(bt) => {
additional_args.push(
RcDoc::as_string("default : ")
.append(translate_base_typ(bt.clone())),
);
}
_ => panic!(), // should not happen
}
}
_ => (),
};
// Handle everything with the SeqTrait.
match (
format!("{}", module_name.pretty(0)).as_str(),
format!("{}", func_ident.pretty(0)).as_str(),
) {
m @ ((ARRAY_MODULE, "from_slice")
| (ARRAY_MODULE, "concat")
| (ARRAY_MODULE, "from_slice_range")
| (ARRAY_MODULE, "set_chunk")
| (ARRAY_MODULE, "update_slice")
| (ARRAY_MODULE, "update")
| (ARRAY_MODULE, "update_start")
| (ARRAY_MODULE, "from_seq")
| (SEQ_MODULE, "from_slice")
| (SEQ_MODULE, "concat")
| (SEQ_MODULE, "from_slice_range")
| (SEQ_MODULE, "set_chunk")
| (SEQ_MODULE, "set_exact_chunk")
| (SEQ_MODULE, "update_slice")
| (SEQ_MODULE, "update")
| (SEQ_MODULE, "update_start")
| (SEQ_MODULE, "from_seq")
| (SEQ_MODULE, "from_public_seq")
| (NAT_MODULE, "from_byte_seq_le")
| (NAT_MODULE, "from_byte_seq_be")
| (NAT_MODULE, "to_public_byte_seq_le")
| (NAT_MODULE, "to_public_byte_seq_be")) => {
// position in arg list (does not count self)
let position = match m {
(ARRAY_MODULE, "from_slice")
| (ARRAY_MODULE, "concat")
| (ARRAY_MODULE, "from_slice_range")
| (ARRAY_MODULE, "update_start")
| (ARRAY_MODULE, "from_seq")
| (SEQ_MODULE, "from_slice")
| (SEQ_MODULE, "concat")
| (SEQ_MODULE, "from_slice_range")
| (SEQ_MODULE, "update_start")
| (SEQ_MODULE, "from_seq")
| (SEQ_MODULE, "from_public_seq")
| (NAT_MODULE, "from_byte_seq_le")
| (NAT_MODULE, "from_byte_seq_be")
| (NAT_MODULE, "to_public_byte_seq_le")
| (NAT_MODULE, "to_public_byte_seq_be") => 0,
(ARRAY_MODULE, "update")
| (SEQ_MODULE, "update")
| (ARRAY_MODULE, "update_slice")
| (SEQ_MODULE, "update_slice") => 1,
(ARRAY_MODULE, "set_chunk")
| (SEQ_MODULE, "set_chunk")
| (SEQ_MODULE, "set_exact_chunk") => 2,
_ => panic!(),
};
let ty = match args_ty[position].clone() {
BaseTyp::Named(p, _) => match top_ctx.typ_dict.get(&p.0) {
Some(x) => x.0 .1 .0.clone(),
None => args_ty[position].clone(),
},
_ => args_ty[position].clone(),
};
if let BaseTyp::Array(..) = ty {
while extra_info.len() <= position {
extra_info.push((RcDoc::nil(), RcDoc::nil()))
}
extra_info.insert(
position,
(RcDoc::as_string("array_to_seq ("), RcDoc::as_string(")")),
);
}
}
_ => (),
};
match (
format!("{}", module_name.pretty(0)).as_str(),
format!("{}", func_ident.pretty(0)).as_str(),
) {
// Then we add the size for arrays
(ARRAY_MODULE, "new_")
| (ARRAY_MODULE, "from_seq")
| (ARRAY_MODULE, "from_slice")
| (ARRAY_MODULE, "from_slice_range") => {
match &prefix_info {
FuncPrefix::Array(ArraySize::Ident(s), _) => {
additional_args.push(translate_ident(Ident::TopLevel(s.clone())))
}
FuncPrefix::Array(ArraySize::Integer(i), _) => {
if *i == 0 {
additional_args.push(RcDoc::as_string("_"))
} else {
additional_args.push(RcDoc::as_string(format!("{}", i)))
}
}
FuncPrefix::Seq(_) => {
// This is the Seq case, should be alright
()
}
_ => panic!(), // should not happen
}
}
_ => (),
}
(
module_name
.clone()
.append(RcDoc::as_string("_"))
.append(func_ident.clone()),
additional_args,
result_typ,
extra_info,
)
}
}
}
fn translate_pattern_tick<'a>(p: Pattern) -> RcDoc<'a, ()> {
match p {
// If the pattern is a tuple, expand it
Pattern::Tuple(_) => RcDoc::as_string("'").append(translate_pattern(p)),
_ => translate_pattern(p),
}
}
fn translate_pattern<'a>(p: Pattern) -> RcDoc<'a, ()> {
match p {
Pattern::EnumCase(ty_name, name, None) => {
translate_enum_case_name(ty_name, name.0.clone(), false)
}
Pattern::EnumCase(ty_name, name, Some(inner_pat)) => {
translate_enum_case_name(ty_name, name.0.clone(), false)
.append(RcDoc::space())
.append(make_paren(translate_pattern(inner_pat.0)))
}
Pattern::IdentPat(x, _) => translate_ident(x.clone()),
Pattern::LiteralPat(x) => translate_literal(x.clone()),
Pattern::WildCard => RcDoc::as_string("_"),
Pattern::Tuple(pats) => make_tuple(pats.into_iter().map(|(pat, _)| translate_pattern(pat))),
}
}
pub(crate) fn translate_expression<'a>(e: Expression, top_ctx: &'a TopLevelContext) -> RcDoc<'a, ()> {
match e {
Expression::MonadicLet(..) => panic!("TODO: Coq support for Expression::MonadicLet"),
Expression::QuestionMark(..) => {
// TODO: eliminiate this `panic!` with nicer types (See issue #303)
panic!("[Expression::QuestionMark] nodes should have been eliminated before printing.")
}
Expression::Binary((op, _), e1, e2, op_typ) => {
let e1 = e1.0;
let e2 = e2.0;
make_paren(translate_expression(e1, top_ctx))
.append(RcDoc::space())
.append(translate_binop(
RcDoc::nil(),
op,
op_typ.as_ref().unwrap(),
top_ctx,
))
.append(RcDoc::space())
.append(make_paren(translate_expression(e2, top_ctx)))
.group()
}
Expression::MatchWith(arg, arms) => RcDoc::as_string("match")
.append(RcDoc::space())
.append(translate_expression(arg.0, top_ctx))
.append(RcDoc::space())
.append(RcDoc::as_string("with"))
.append(RcDoc::line())
.append(RcDoc::intersperse(
arms.into_iter().map(|(pat, e1)| {
RcDoc::as_string("|")
.append(RcDoc::space())
.append(translate_pattern(pat.0.clone()))
.append(RcDoc::space())
.append(RcDoc::as_string("=>"))
.append(RcDoc::space())
.append(translate_expression(e1.0, top_ctx))
}),
RcDoc::line(),
))
.append(RcDoc::line())
.append(RcDoc::as_string("end")),
Expression::FieldAccessor(e1, field) => {
unimplemented!()
}
Expression::EnumInject(enum_name, case_name, payload) => {
translate_enum_case_name(enum_name.clone(), case_name.0.clone(), true).append(
match payload {
None => RcDoc::nil(),
Some(payload) => RcDoc::space().append(make_paren(translate_expression(
*payload.0.clone(),
top_ctx,
))),
},
)
}
Expression::InlineConditional(cond, e_t, e_f) => {
let cond = cond.0;
let e_t = e_t.0;
let e_f = e_f.0;
make_paren(
RcDoc::as_string("if")
.append(RcDoc::space())
.append(make_paren(translate_expression(cond, top_ctx)))
.append(RcDoc::as_string(":bool"))
.append(RcDoc::space())
.append(RcDoc::as_string("then"))
.append(RcDoc::space())
.append(make_paren(translate_expression(e_t, top_ctx)))
.append(RcDoc::space())
.append(RcDoc::as_string("else"))
.append(RcDoc::space())
.append(make_paren(translate_expression(e_f, top_ctx))),
)
.group()
}
Expression::Unary(op, e1, op_typ) => {
let e1 = e1.0;
translate_unop(op, op_typ.as_ref().unwrap().clone())
.append(RcDoc::space())
.append(make_paren(translate_expression(e1, top_ctx)))
.group()
}
Expression::Lit(lit) => translate_literal(lit.clone()),
Expression::Tuple(es) => make_tuple(
es.into_iter()
.map(|(e, _)| translate_expression(e, top_ctx)),
),
Expression::Named(p) => translate_ident(p.clone()),
Expression::FuncCall(prefix, name, args, arg_types) => {
let (func_name, additional_args, func_ret_ty, extra_info) = translate_func_name(
prefix.clone(),
Ident::TopLevel(name.0.clone()),
top_ctx,
arg_types.unwrap(),
);
let total_args = args.len() + additional_args.len();
func_name
// We append implicit arguments first
.append(RcDoc::concat(
additional_args
.into_iter()
.map(|arg| RcDoc::space().append(make_paren(arg))),
))
// Then the explicit arguments
.append(RcDoc::concat(args.into_iter().enumerate().map(
|(i, ((arg, _), _))| {
RcDoc::space().append(make_paren(if i < extra_info.len() {
let (pre_arg, post_arg) = extra_info[i].clone();
pre_arg
.clone()
.append(translate_expression(arg, top_ctx))
.append(post_arg.clone())
} else {
translate_expression(arg, top_ctx)
}))
},
)))
.append(if total_args == 0 {
RcDoc::space()
} else {
RcDoc::nil()
})
.append(match func_ret_ty {
Some(ret_ty) => RcDoc::as_string(" : ").append(translate_base_typ(ret_ty)),
None => RcDoc::nil(),
})
}
Expression::MethodCall(sel_arg, sel_typ, (f, _), args, arg_types) => {
// Ignore "clone" // TODO: is this correct?
if f.string == "clone" {
// Then the self argument
make_paren(translate_expression((sel_arg.0).0, top_ctx))
// And finally the rest of the arguments
.append(RcDoc::concat(args.into_iter().map(|((arg, _), _)| {
RcDoc::space().append(make_paren(translate_expression(arg, top_ctx)))
})))
} else {
let (func_name, additional_args, func_ret_ty, extra_info) = translate_func_name(
sel_typ.clone().map(|x| x.1),
Ident::TopLevel(f.clone()),
top_ctx,
arg_types.unwrap(),
);
func_name // We append implicit arguments first
.append(RcDoc::concat(
additional_args
.into_iter()
.map(|arg| RcDoc::space().append(make_paren(arg))),
))
.append(RcDoc::space())
// Then the self argument
.append(make_paren(translate_expression((sel_arg.0).0, top_ctx)))
// And finally the rest of the arguments
.append(RcDoc::concat(args.into_iter().enumerate().map(
|(i, ((arg, _), _))| {
RcDoc::space().append(make_paren(if i < extra_info.len() {
let (pre_arg, post_arg) = extra_info[i].clone();
pre_arg
.clone()
.append(translate_expression(arg, top_ctx))
.append(post_arg.clone())
} else {
translate_expression(arg, top_ctx)
}))
},
)))
.append(match func_ret_ty {
Some(ret_ty) => RcDoc::as_string(" : ").append(translate_base_typ(ret_ty)),
None => RcDoc::nil(),
})
}
}
Expression::ArrayIndex(x, e2, typ) => {
let e2 = e2.0;
let array_or_seq = array_or_seq(typ.unwrap(), top_ctx);
array_or_seq
.append(RcDoc::as_string("_index"))
.append(RcDoc::space())
.append(make_paren(translate_ident(x.0.clone())))
.append(RcDoc::space())
.append(make_paren(translate_expression(e2, top_ctx)))
}
// Expression::NewArray(_array_name, inner_ty, args) => {
Expression::NewArray(_array_name, inner_ty, args) => {
let inner_ty = inner_ty.unwrap();
// inner_ty is the type of the cell elements
// TODO: do the case when _array_name is None (the Seq case)
match _array_name {
// Seq case
None => make_list(
args.into_iter()
.map(|(e, _)| translate_expression(e.clone(), top_ctx)),
),
Some(_) =>
// Array case
{
RcDoc::as_string(format!("{}_from_list", ARRAY_MODULE))
.append(RcDoc::space())
.append(translate_base_typ(inner_ty.clone()))
.append(RcDoc::space())
.append(make_paren(
make_let_binding(
RcDoc::as_string("l"),
None,
make_list(
args.into_iter()
.map(|(e, _)| translate_expression(e, top_ctx)),
),
false,
)
.append(RcDoc::space())
.append(RcDoc::as_string("l")),
))
}
}
}
Expression::IntegerCasting(x, new_t, old_t) => {
let old_t = old_t.unwrap();
match old_t {
BaseTyp::Usize | BaseTyp::Isize => {
(match &new_t.0 {
BaseTyp::UInt8 => RcDoc::as_string("pub_u8"),
BaseTyp::UInt16 => RcDoc::as_string("pub_u16"),
BaseTyp::UInt32 => RcDoc::as_string("pub_u32"),
BaseTyp::UInt64 => RcDoc::as_string("pub_u64"),
BaseTyp::UInt128 => RcDoc::as_string("pub_u128"),
BaseTyp::Usize => RcDoc::as_string("usize"),
BaseTyp::Int8 => RcDoc::as_string("pub_i8"),
BaseTyp::Int16 => RcDoc::as_string("pub_i16"),
BaseTyp::Int32 => RcDoc::as_string("pub_i32"),
BaseTyp::Int64 => RcDoc::as_string("pub_i64"),
BaseTyp::Int128 => RcDoc::as_string("pub_i28"),
BaseTyp::Isize => RcDoc::as_string("isize"),
_ => panic!(), // should not happen
})
.append(RcDoc::space())
.append(make_paren(translate_expression(x.0.clone(), top_ctx)))
}
_ => {
let new_t_doc = match &new_t.0 {
BaseTyp::UInt8 => String::from("uint8"),
BaseTyp::UInt16 => String::from("uint16"),
BaseTyp::UInt32 => String::from("uint32"),
BaseTyp::UInt64 => String::from("uint64"),
BaseTyp::UInt128 => String::from("uint128"),
BaseTyp::Usize => String::from("uint32"),
BaseTyp::Int8 => String::from("int8"),
BaseTyp::Int16 => String::from("int16"),
BaseTyp::Int32 => String::from("int32"),
BaseTyp::Int64 => String::from("int64"),
BaseTyp::Int128 => String::from("int128"),
BaseTyp::Isize => String::from("int32"),
BaseTyp::Named((TopLevelIdent { string: s, .. }, _), None) => s.clone(),
_ => panic!(), // should not happen
};
let _secret = match &new_t.0 {
BaseTyp::Named(_, _) => true,
_ => false,
};
RcDoc::as_string("@cast _")
.append(RcDoc::space())
.append(new_t_doc)
.append(RcDoc::space())
.append(RcDoc::as_string("_"))
.append(RcDoc::space())
.append(make_paren(translate_expression(
x.as_ref().0.clone(),
top_ctx,
)))
.group()
}
}
}
}
}
fn translate_statements<'a>(
mut statements: Iter<Spanned<Statement>>,
top_ctx: &'a TopLevelContext,
) -> RcDoc<'a, ()> {
let s = match statements.next() {
None => return RcDoc::nil(),
Some(s) => s.clone(),
};
match s.0 {
Statement::LetBinding((pat, _), typ, (expr, _), _carrier, question_mark) => {
if question_mark.is_some() {
RcDoc::as_string("bind ")
.append(make_paren(translate_expression(expr.clone(), top_ctx)))
.append(RcDoc::space())
.append(make_paren(
RcDoc::as_string("fun")
.append(RcDoc::space())
.append(match pat.clone() {
Pattern::EnumCase(_, _, _) => RcDoc::as_string("'"),
_ => RcDoc::nil(),
})
.append(translate_pattern_tick(pat.clone()))
.append(RcDoc::as_string(" =>"))
.append(RcDoc::softline())
.append(translate_statements(statements, top_ctx)),
))
} else {
make_let_binding(
match pat.clone() {
Pattern::EnumCase(_, _, _) => RcDoc::as_string("'"),
_ => RcDoc::nil(),
}
.append(translate_pattern_tick(pat.clone())),
match pat.clone() {
Pattern::EnumCase(_, _, _) | Pattern::Tuple(_) => None,
_ => typ.map(|(typ, _)| translate_typ(typ)),
},
translate_expression(expr.clone(), top_ctx),
false,
)
.append(RcDoc::hardline())
.append(translate_statements(statements, top_ctx))
}
}
Statement::Reassignment((x, _), _x_typ, (e1, _), _carrier, question_mark) =>
{
if question_mark.is_some() {
RcDoc::as_string("bind")
.append(RcDoc::space())
.append(make_paren(translate_expression(e1.clone(), top_ctx)))
.append(RcDoc::space())
.append(make_paren(
RcDoc::as_string("fun")
.append(RcDoc::space())
.append(translate_ident(x.clone()))
.append(RcDoc::space())
.append(RcDoc::as_string(" =>"))
.append(RcDoc::softline())
.append(translate_statements(statements, top_ctx)),
))
} else {
make_let_binding(
translate_ident(x.clone()),
None,
translate_expression(e1.clone(), top_ctx),
false,
)
.append(RcDoc::hardline())
.append(translate_statements(statements, top_ctx))
}
}
Statement::ArrayUpdate((x, _), (e1, _), (e2, _), _carrier, question_mark, typ) => {
let array_or_seq = array_or_seq(typ.unwrap(), top_ctx);
if question_mark.is_some() {
RcDoc::as_string("bind")
.append(RcDoc::space())
.append(make_paren(translate_expression(e2.clone(), top_ctx)))
.append(RcDoc::space())
.append(make_paren(
RcDoc::as_string("fun")
.append(RcDoc::space())
.append(RcDoc::as_string("_temp"))
.append(RcDoc::space())
.append(RcDoc::as_string("=>"))
.append(RcDoc::softline())
.append(make_let_binding(
translate_ident(x.clone()),
None,
array_or_seq
.append(RcDoc::as_string("_upd"))
.append(RcDoc::space())
.append(translate_ident(x.clone()))
.append(RcDoc::space())
.append(make_paren(translate_expression(e1.clone(), top_ctx)))
.append(RcDoc::space())
.append(RcDoc::as_string("_temp")),
false,
))
.append(RcDoc::hardline())
.append(translate_statements(statements, top_ctx)),
))
} else {
let array_upd_payload = array_or_seq
.append(RcDoc::as_string("_upd"))
.append(RcDoc::space())
.append(translate_ident(x.clone()))
.append(RcDoc::space())
.append(make_paren(translate_expression(e1.clone(), top_ctx)))
.append(RcDoc::space())
.append(make_paren(translate_expression(e2.clone(), top_ctx)));
make_let_binding(translate_ident(x.clone()), None, array_upd_payload, false)
.append(RcDoc::hardline())
.append(translate_statements(statements, top_ctx))
}
}
Statement::ReturnExp(e1, _) => translate_expression(e1.clone(), top_ctx),
Statement::Conditional((cond, _), (mut b1, _), b2, mutated) => {
let mutated_info = mutated.unwrap();
let pat = RcDoc::as_string("'").append(make_tuple(
mutated_info
.vars
.0
.iter()
.sorted()
.map(|i| translate_ident(Ident::Local(i.clone()))),
));
let b1_question_mark = *b1.contains_question_mark.as_ref().unwrap();
let b2_question_mark = match &b2 {
None => false,
Some(b2) => *b2.0.contains_question_mark.as_ref().unwrap(),
};
let either_blocks_contains_question_mark = b1_question_mark || b2_question_mark;
b1.stmts.push(add_ok_if_result(
mutated_info.stmt.clone(),
if b1_question_mark {
mutated_info.early_return_type.clone()
} else {
None
},
));
let expr = RcDoc::as_string("if")
.append(RcDoc::space())
.append(translate_expression(cond.clone(), top_ctx))
.append(RcDoc::as_string(":bool"))
.append(RcDoc::space())
.append(RcDoc::as_string("then"))
.append(RcDoc::space())
.append(make_paren(translate_block(b1.clone(), true, top_ctx)))
.append(match b2.clone() {
None => RcDoc::space()
.append(RcDoc::as_string("else"))
.append(RcDoc::space())
.append(make_paren(translate_statements(
[(mutated_info.stmt.clone(), DUMMY_SP.into())].iter(),
top_ctx,
))),
Some((mut b2, _)) => {
b2.stmts.push(add_ok_if_result(
mutated_info.stmt.clone(),
if b2_question_mark {
mutated_info.early_return_type.clone()
} else {
None
},
));
RcDoc::space()
.append(RcDoc::as_string("else"))
.append(RcDoc::space())
.append(make_paren(translate_block(b2, true, top_ctx)))
}
});
if either_blocks_contains_question_mark {
let block1 = make_paren(translate_block(b1.clone(), true, top_ctx));
RcDoc::as_string("ifbnd")
.append(RcDoc::space())
.append(translate_expression(cond.clone(), top_ctx))
.append(RcDoc::space())
.append(RcDoc::as_string(": bool"))
.append(RcDoc::line())
.append(if b1_question_mark {
RcDoc::as_string("thenbnd")
} else {
RcDoc::as_string("then")
})
.append(RcDoc::space())
.append(block1)
.append(RcDoc::line())
.append(match b2 {
None => RcDoc::as_string("else")
.append(RcDoc::space())
.append(make_paren(translate_statements(
[(mutated_info.stmt.clone(), DUMMY_SP.into())].iter(),
top_ctx,
))),
Some((mut b2, _)) => {
b2.stmts.push(add_ok_if_result(
mutated_info.stmt.clone(),
if b2_question_mark {
mutated_info.early_return_type.clone()
} else {
None
},
));
let block2 = make_paren(translate_block(b2, true, top_ctx));
(if b2_question_mark {
RcDoc::as_string("elsebnd")
} else {
RcDoc::as_string("else")
})
.append(block2)
}
})
.append(RcDoc::space())
.append(RcDoc::as_string(">> (fun"))
.append(RcDoc::space())
.append(pat)
.append(RcDoc::space())
.append(RcDoc::as_string("=>"))
.append(RcDoc::line())
.append(translate_statements(statements.clone(), top_ctx))
.append(RcDoc::as_string(")"))
} else {
make_let_binding(pat, None, expr, false)
.append(RcDoc::hardline())
.append(translate_statements(statements.clone(), top_ctx))
}
}
Statement::ForLoop(x, (e1, _), (e2, _), (mut b, _)) => {
let mutated_info = b.mutated.clone().unwrap();
let b_question_mark = *b.contains_question_mark.as_ref().unwrap();
b.stmts.push(add_ok_if_result(
mutated_info.stmt.clone(),
if b_question_mark {
mutated_info.early_return_type.clone()
} else {
None
},
));
let mut_tuple = |prefix: String| -> RcDoc<'a> {
// if there is only one element, just print the identifier instead of making a tuple
if mutated_info.vars.0.len() == 1 {
match mutated_info.vars.0.iter().next() {
None => RcDoc::nil(),
Some(i) => translate_ident(Ident::Local(i.clone())),
}
}
// print as tuple otherwise
else {
RcDoc::as_string(prefix).append(make_tuple(
mutated_info
.vars
.0
.iter()
.sorted()
.map(|i| translate_ident(Ident::Local(i.clone()))),
))
}
};
if b_question_mark {
let loop_expr = RcDoc::as_string("foldibnd")
.append(RcDoc::space())
.append(make_paren(translate_expression(e1.clone(), top_ctx)))
.append(RcDoc::space())
.append(RcDoc::as_string("to"))
.append(RcDoc::space())
.append(make_paren(translate_expression(e2.clone(), top_ctx)))
.append(RcDoc::space())
.append(RcDoc::as_string("for"))
.append(RcDoc::space())
.append(mut_tuple("".to_string()).clone())
.append(RcDoc::space())
.append(">> (fun")
.append(RcDoc::space())
.append(match x {
Some((x, _)) => translate_ident(x.clone()),
None => RcDoc::as_string("_"),
})
.append(RcDoc::space())
.append(mut_tuple("'".to_string()).clone())
.append(RcDoc::space())
.append(RcDoc::as_string("=>"))
.append(RcDoc::line())
.append(translate_block(b, true, top_ctx))
.append(RcDoc::as_string(")"));
RcDoc::as_string("bind")
.append(RcDoc::space())
.append(make_paren(loop_expr))
.append(RcDoc::space())
.append(make_paren(
RcDoc::as_string("fun")
.append(RcDoc::space())
.append(if mutated_info.vars.0.iter().len() == 0 {
RcDoc::as_string("_")
} else {
mut_tuple("'".to_string()).clone()
})
.append(RcDoc::space())
.append(RcDoc::as_string("=>"))
.append(RcDoc::softline())
.append(translate_statements(statements, top_ctx)),
))
} else {
let loop_expr = RcDoc::as_string("foldi")
.append(RcDoc::space())
.append(make_paren(translate_expression(e1.clone(), top_ctx)))
.append(RcDoc::space())
.append(make_paren(translate_expression(e2.clone(), top_ctx)))
.append(RcDoc::space())
.append(RcDoc::as_string("(fun"))
.append(RcDoc::space())
.append(match x {
Some((x, _)) => translate_ident(x.clone()),
None => RcDoc::as_string("_"),
})
.append(RcDoc::space())
.append(mut_tuple("'".to_string()).clone())
.append(RcDoc::space())
.append(RcDoc::as_string("=>"))
.append(RcDoc::line())
.append(translate_block(b, true, top_ctx))
.append(RcDoc::as_string(")"))
.group()
.nest(2)
.append(RcDoc::line())
.append(mut_tuple("".to_string()).clone());
make_let_binding(mut_tuple("'".to_string()), None, loop_expr, false)
.append(RcDoc::hardline())
.append(translate_statements(statements, top_ctx))
}
}
}
.group()
}
fn translate_block<'a>(
b: Block,
omit_extra_unit: bool,
top_ctx: &'a TopLevelContext,
) -> RcDoc<'a, ()> {
let mut statements = b.stmts;
match (&b.return_typ, omit_extra_unit) {
(None, _) => panic!(), // should not happen,
(Some(((Borrowing::Consumed, _), (BaseTyp::Tuple(tup), _))), false) if tup.is_empty() => {
statements.push((
Statement::ReturnExp(Expression::Lit(Literal::Unit), b.return_typ),
DUMMY_SP.into(),
));
}
(Some(_), _) => (),
}
translate_statements(statements.iter(), top_ctx).group()
}
fn translate_item<'a>(
item: &'a DecoratedItem,
top_ctx: &'a TopLevelContext,
export_quick_check: bool,
) -> RcDoc<'a, ()> {
match &item.item {
Item::FnDecl((f, _), sig, (b, _)) => make_let_binding(
translate_ident(Ident::TopLevel(f.clone()))
.append(RcDoc::line())
.append(if sig.args.len() > 0 {
RcDoc::intersperse(
sig.args.iter().map(|((x, _), (tau, _))| {
make_paren(
translate_ident(x.clone())
.append(RcDoc::space())
.append(RcDoc::as_string(":"))
.append(RcDoc::space())
.append(translate_typ(tau.clone())),
)
}),
RcDoc::line(),
)
} else {
RcDoc::nil()
})
.append(RcDoc::line())
.append(if sig.requires.len() > 0 {
sig.requires.iter().fold(RcDoc::nil(), |rc, e| {
rc
.append(RcDoc::line())
.append(RcDoc::as_string("`{"))
.append(crate::pearlite::translate_quantified_expression(e.clone(), top_ctx))
.append(RcDoc::as_string("}"))
})
} else {
RcDoc::nil()
})
.append(RcDoc::line())
.append(
RcDoc::as_string(":")
.append(RcDoc::space())
.append(translate_base_typ(sig.ret.0.clone()))
.group(),
),
None,
translate_block(b.clone(), false, top_ctx)
.append(RcDoc::nil())
.group(),
true,
)
.append(
if sig.ensures.len() > 0 {
RcDoc::hardline()
.append(RcDoc::hardline())
.append(RcDoc::as_string("Theorem ensures_"))
.append(translate_ident(Ident::TopLevel(f.clone())))
.append(RcDoc::as_string(" : forall"))
.append(RcDoc::space())
.append(translate_ident(Ident::Local(LocalIdent {
id: NodeId::MAX.as_usize(),
name: "result".to_string(),
mutable: false,
})))
.append(RcDoc::space())
.append(RcDoc::intersperse(
sig.args.iter().map(|((x, _), (tau, _))| {
make_paren(
translate_ident(x.clone())
.append(RcDoc::space())
.append(RcDoc::as_string(":"))
.append(RcDoc::space())
.append(translate_typ(tau.clone()))
)
}),
RcDoc::space()
))
.append(RcDoc::as_string(","))
.append(
sig.requires.iter().enumerate().fold(RcDoc::line(), |rs, (i, e)| {
rs
.append(RcDoc::as_string("forall {H_"))
.append(RcDoc::as_string(i.to_string()))
.append(RcDoc::as_string(" : "))
.append(crate::pearlite::translate_quantified_expression(e.clone(), top_ctx))
.append(RcDoc::as_string("}"))
.append(RcDoc::as_string(","))
.append(RcDoc::line())
})
.append(RcDoc::as_string("@"))
.append(translate_ident(Ident::TopLevel(f.clone())))
.append(RcDoc::space())
.append(RcDoc::intersperse(
sig.args.iter().map(|((x, _), _)| {
translate_ident(x.clone())
}),
RcDoc::space()
))
.append(RcDoc::space())
.append(RcDoc::intersperse(
(0..sig.requires.iter().len())
.map(|i| {
RcDoc::as_string("H_")
.append(RcDoc::as_string(i.to_string()))
.append(RcDoc::space())
}),
RcDoc::nil()))
.append(RcDoc::as_string("="))
.append(RcDoc::space())
.append(translate_ident(Ident::Local(LocalIdent {
id: NodeId::MAX.as_usize(),
name: "result".to_string(),
mutable: false,
})))
.append(RcDoc::space())
.append(RcDoc::as_string("->"))
.append(RcDoc::line())
.append(RcDoc::intersperse(sig.ensures.iter().map(|e| crate::pearlite::translate_quantified_expression(e.clone(), top_ctx)), RcDoc::as_string("/\\")))
.append(RcDoc::as_string("."))
.append(RcDoc::line())
.nest(1)
)
.append(RcDoc::as_string("Proof. Admitted."))
}
else {
RcDoc::nil()
})
.append({
if item.tags.0.contains(&"quickcheck".to_string()) {
RcDoc::hardline()
.append(RcDoc::as_string("(*"))
.append(RcDoc::as_string("QuickChick"))
.append(RcDoc::space())
.append(make_paren(RcDoc::concat(
sig.args
.iter()
.map(|((x, _), (tau, _))| {
RcDoc::as_string("forAll g_")
.append(translate_typ(tau.clone()))
.append(RcDoc::space())
.append("(")
.append(RcDoc::as_string("fun"))
.append(RcDoc::space())
.append(translate_ident(x.clone()))
.append(RcDoc::space())
.append(RcDoc::as_string(":"))
.append(RcDoc::space())
.append(translate_typ(tau.clone()))
.append(RcDoc::space())
.append(RcDoc::as_string("=>"))
}))
.append(translate_ident(Ident::TopLevel(f.clone())))
.append(RcDoc::concat(sig.args.iter().map(|((x, _), (_, _))| {
RcDoc::space()
.append(translate_ident(x.clone()))
}
)))
.append(RcDoc::concat(sig.args.iter().map(|_| RcDoc::as_string(")")))),
))
.append(RcDoc::as_string("."))
.append(RcDoc::as_string("*)"))
.append(RcDoc::hardline())
.group()
} else {
RcDoc::nil()
}
}),
Item::EnumDecl(name, cases) => RcDoc::as_string("Inductive")
.append(RcDoc::space())
.append(translate_enum_name(name.0.clone()))
.append(RcDoc::space())
.append(RcDoc::as_string(":="))
.append(RcDoc::line())
.append(RcDoc::intersperse(
cases.into_iter().map(|(case_name, case_typ)| {
let name_ty = BaseTyp::Named(name.clone(), None);
RcDoc::as_string("|")
.append(RcDoc::space())
.append(translate_enum_case_name(name_ty, case_name.0.clone(), false))
.append(match case_typ {
None => RcDoc::space()
.append(RcDoc::as_string(":"))
.append(RcDoc::space())
.append(translate_enum_name(name.0.clone())),
Some(case_typ) => RcDoc::space()
.append(RcDoc::as_string(":"))
.append(RcDoc::space())
.append(translate_base_typ(case_typ.0.clone()))
.append(RcDoc::space())
.append(RcDoc::as_string("->"))
.append(RcDoc::space())
.append(translate_enum_name(name.0.clone())),
})
}),
RcDoc::line(),
))
.append(RcDoc::as_string("."))
.append(if item.tags.0.contains(&"PartialEq".to_string()) {
RcDoc::hardline()
.append(RcDoc::hardline())
.append(RcDoc::as_string("Definition"))
.append(RcDoc::space())
.append(RcDoc::as_string("eqb_"))
.append(translate_enum_name(name.0.clone()))
.append(RcDoc::space())
.append(RcDoc::as_string("(x y : "))
.append(translate_enum_name(name.0.clone()))
.append(RcDoc::as_string(")"))
.append(RcDoc::space())
.append(RcDoc::as_string(":"))
.append(RcDoc::space())
.append(RcDoc::as_string("bool"))
.append(RcDoc::space())
.append(RcDoc::as_string(":="))
.append(RcDoc::line())
.append(
RcDoc::as_string("match x with")
.append(RcDoc::line())
.append(RcDoc::intersperse(
cases.into_iter().map(|(case_name, case_typ)| {
let name_ty = BaseTyp::Named(name.clone(), None);
RcDoc::as_string("|")
.append(RcDoc::space())
.append(translate_enum_case_name(
name_ty.clone(),
case_name.0.clone(), false,
))
.append(RcDoc::space())
.append(match case_typ {
None => RcDoc::nil(),
Some(_) => RcDoc::as_string("a").append(RcDoc::space()),
})
.append(RcDoc::as_string("=>"))
.append(RcDoc::line())
.append(
RcDoc::as_string("match y with")
.append(RcDoc::line())
.append(RcDoc::as_string("|"))
.append(RcDoc::space())
.append(translate_enum_case_name(
name_ty.clone(),
case_name.0.clone(), false,
))
.append(match case_typ {
None => RcDoc::as_string("=> true"),
Some(_) => RcDoc::space()
.append(RcDoc::as_string("b"))
.append(RcDoc::space())
.append(RcDoc::as_string("=> a =.? b")),
})
.append(RcDoc::line())
.append(match &cases.into_iter().size_hint().1 {
Some(0) => RcDoc::nil(),
Some(1) => RcDoc::nil(),
_ => RcDoc::as_string("| _ => false")
.append(RcDoc::line()),
})
.append(RcDoc::as_string("end")),
)
.group()
.nest(4)
}),
RcDoc::line(),
))
.append(RcDoc::line())
.append("end.")
.nest(3),
)
.append(RcDoc::hardline())
.append(RcDoc::hardline())
.append(RcDoc::as_string("Definition"))
.append(RcDoc::space())
.append(RcDoc::as_string("eqb_leibniz_"))
.append(translate_enum_name(name.0.clone()))
.append(RcDoc::space())
.append(RcDoc::as_string("(x y : "))
.append(translate_enum_name(name.0.clone()))
.append(RcDoc::as_string(") :"))
.append(RcDoc::space())
.append(RcDoc::as_string("eqb_"))
.append(translate_enum_name(name.0.clone()))
.append(RcDoc::space())
.append(RcDoc::as_string("x y = true <-> x = y."))
.append(RcDoc::hardline())
.append(
RcDoc::as_string("Proof. split. intros; destruct x ; destruct y ; try (f_equal ; apply eqb_leibniz) ; easy. intros ; subst ; destruct y ; try reflexivity ; try (apply eqb_refl). Qed.")
)
.append(RcDoc::hardline())
.append(RcDoc::hardline())
.append(RcDoc::as_string("Instance"))
.append(RcDoc::space())
.append(RcDoc::as_string("eq_dec_"))
.append(translate_enum_name(name.0.clone()))
.append(RcDoc::space())
.append(RcDoc::as_string(":"))
.append(RcDoc::space())
.append(RcDoc::as_string("EqDec ("))
.append(translate_enum_name(name.0.clone()))
.append(RcDoc::as_string(") :="))
.append(RcDoc::hardline())
.append(
RcDoc::as_string("Build_EqDec (")
.append(translate_enum_name(name.0.clone()))
.append(RcDoc::as_string(") (eqb_"))
.append(translate_enum_name(name.0.clone()))
.append(RcDoc::as_string(") (eqb_leibniz_"))
.append(translate_enum_name(name.0.clone()))
.append(RcDoc::as_string(")."))
.nest(2)
)
.append(RcDoc::hardline())
} else {
RcDoc::nil()
})
.append(if export_quick_check {
RcDoc::hardline()
.append(RcDoc::as_string("Global Instance"))
.append(RcDoc::space())
.append(RcDoc::as_string("show_"))
.append(translate_ident(Ident::TopLevel(name.0.clone())))
.append(RcDoc::space())
.append(RcDoc::as_string(":"))
.append(RcDoc::space())
.append(RcDoc::as_string("Show ("))
.append(translate_ident(Ident::TopLevel(name.0.clone())))
.append(RcDoc::as_string(") :="))
.group()
.append(RcDoc::line())
.append(RcDoc::as_string(" @Build_Show ("))
.append(translate_ident(Ident::TopLevel(name.0.clone())))
.append(RcDoc::as_string(")"))
.append(RcDoc::space())
.append(RcDoc::as_string("(fun x =>"))
.append(RcDoc::line())
.append(RcDoc::as_string("match x with"))
.append(RcDoc::line())
.append(RcDoc::intersperse(
cases.into_iter().map(|(case_name, case_typ)| {
let name_ty = BaseTyp::Named(name.clone(), None);
translate_enum_case_name(
name_ty.clone(),
case_name.0.clone(),
false,
)
.append(RcDoc::space())
.append(match case_typ {
None => RcDoc::nil(),
Some(_) => RcDoc::as_string("a").append(RcDoc::space()),
})
.append(RcDoc::as_string("=>"))
.append(RcDoc::space())
.append(make_paren(
RcDoc::as_string("\"")
.append(
translate_enum_case_name(
name_ty.clone(),
case_name.0.clone(),
false
)
)
.append(RcDoc::as_string("\""))
.append(match case_typ {
None => RcDoc::nil(),
Some(_) => RcDoc::space().append(RcDoc::as_string("++ show a")),
})
))
.append(RcDoc::as_string("%string"))
}),
RcDoc::line().append(RcDoc::as_string("|")).append(RcDoc::space())))
.append(RcDoc::line())
.append(RcDoc::as_string("end)."))
.nest(1)
.append(RcDoc::hardline())
.append(RcDoc::as_string("Definition"))
.append(RcDoc::space())
.append(RcDoc::as_string("g_"))
.append(translate_ident(Ident::TopLevel(name.0.clone())))
.append(RcDoc::space())
.append(RcDoc::as_string(":"))
.append(RcDoc::space())
.append(RcDoc::as_string("G ("))
.append(translate_ident(Ident::TopLevel(name.0.clone())))
.append(RcDoc::as_string(") := oneOf_ ("))
.append(match cases.into_iter().next() {
Some ((case_name, case_typ)) => {
let name_ty = BaseTyp::Named(name.clone(), None);
match case_typ {
None => RcDoc::as_string("returnGen "),
Some(_) => RcDoc::as_string("bindGen arbitrary (fun a => returnGen ("),
}
.append(
translate_enum_case_name(
name_ty.clone(),
case_name.0.clone(),
false
))
.append(match case_typ {
None => RcDoc::nil(),
Some(_) => RcDoc::as_string(" a))"),
})
}
None => RcDoc::nil(),
})
.append(RcDoc::as_string(") ["))
.append(RcDoc::intersperse(
cases.into_iter().map(|(case_name, case_typ)| {
let name_ty = BaseTyp::Named(name.clone(), None);
match case_typ {
None => RcDoc::as_string("returnGen "),
Some(_) => RcDoc::as_string("bindGen arbitrary (fun a => returnGen ("),
}
.append(
translate_enum_case_name(
name_ty.clone(),
case_name.0.clone(),
false,
))
.append(match case_typ {
None => RcDoc::nil(),
Some(_) => RcDoc::as_string(" a))"),
})
}),
RcDoc::as_string(";")))
.append(RcDoc::as_string("]."))
.append(RcDoc::hardline())
.append(RcDoc::as_string("#[global] Instance"))
.append(RcDoc::space())
.append(RcDoc::as_string("gen_"))
.append(translate_ident(Ident::TopLevel(name.0.clone())))
.append(RcDoc::space())
.append(RcDoc::as_string(":"))
.append(RcDoc::space())
.append(RcDoc::as_string("Gen ("))
.append(translate_ident(Ident::TopLevel(name.0.clone())))
.append(RcDoc::as_string(") := Build_Gen"))
.append(RcDoc::space())
.append(translate_ident(Ident::TopLevel(name.0.clone())))
.append(RcDoc::space())
.append(RcDoc::as_string("g_"))
.append(translate_ident(Ident::TopLevel(name.0.clone())))
.append(RcDoc::as_string("."))
.append(RcDoc::hardline())
} else {
RcDoc::nil()
}),
Item::ArrayDecl(name, size, cell_t, index_typ) => RcDoc::as_string("Definition")
.append(RcDoc::space())
.append(translate_ident(Ident::TopLevel(name.0.clone())))
.append(RcDoc::space())
.append(RcDoc::as_string(":="))
.group()
.append(
RcDoc::line()
.append(RcDoc::as_string("nseq"))
.append(RcDoc::space())
.append(make_paren(translate_base_typ(cell_t.0.clone())))
.append(RcDoc::space())
.append(make_paren(translate_expression(size.0.clone(), top_ctx)))
.group()
.nest(2),
)
.append(RcDoc::as_string("."))
.append(match index_typ {
None => RcDoc::nil(),
Some(index_typ) => RcDoc::hardline()
.append(RcDoc::hardline())
.append(make_let_binding(
translate_ident(Ident::TopLevel(index_typ.0.clone())),
None,
RcDoc::as_string("nat_mod")
.append(RcDoc::space())
.append(make_paren(translate_expression(size.0.clone(), top_ctx))),
true,
))
.append(RcDoc::hardline())
.append(make_uint_size_coercion(translate_ident(Ident::TopLevel(
index_typ.0.clone(),
)))),
}),
Item::ConstDecl(name, ty, e) => make_let_binding(
translate_ident(Ident::TopLevel(name.0.clone())),
Some(translate_base_typ(ty.0.clone())),
translate_expression(e.0.clone(), top_ctx),
true,
),
Item::NaturalIntegerDecl(nat_name, _secrecy, canvas_size, info) => {
let canvas_size = match &canvas_size.0 {
Expression::Lit(Literal::Usize(size)) => size,
_ => panic!(), // should not happen by virtue of typchecking
};
let canvas_size_bytes = RcDoc::as_string(format!("{}", (canvas_size + 7) / 8));
(match info {
Some((canvas_name, _modulo)) => RcDoc::as_string("Definition")
.append(RcDoc::space())
.append(translate_ident(Ident::TopLevel(canvas_name.0.clone())))
.append(RcDoc::space())
.append(RcDoc::as_string(":="))
.group()
.append(
RcDoc::line()
.append(RcDoc::as_string("nseq"))
.append(RcDoc::space())
.append(make_paren(translate_base_typ(BaseTyp::UInt8)))
.append(RcDoc::space())
.append(make_paren(canvas_size_bytes.clone()))
.group()
.nest(2),
)
.append(RcDoc::as_string("."))
.append(RcDoc::hardline()),
None => RcDoc::nil(),
})
.append(
RcDoc::as_string("Definition")
.append(RcDoc::space())
.append(translate_ident(Ident::TopLevel(nat_name.0.clone())))
.append(RcDoc::space())
.append(RcDoc::as_string(":="))
.group()
.append(
RcDoc::line()
.append(RcDoc::as_string("nat_mod"))
.append(RcDoc::space())
.append(match info {
Some((_, modulo)) => RcDoc::as_string(format!("0x{}", &modulo.0)),
None => RcDoc::as_string(format!("pow2 {}", canvas_size)),
})
.append(RcDoc::as_string("."))
.group()
.nest(2),
)
.append(if export_quick_check {
RcDoc::hardline()
.append(RcDoc::as_string("Instance"))
.append(RcDoc::space())
.append(RcDoc::as_string("show_"))
.append(translate_ident(Ident::TopLevel(nat_name.0.clone())))
.append(RcDoc::space())
.append(RcDoc::as_string(":"))
.append(RcDoc::space())
.append(RcDoc::as_string("Show ("))
.append(translate_ident(Ident::TopLevel(nat_name.0.clone())))
.append(RcDoc::as_string(") := Build_Show ("))
.append(translate_ident(Ident::TopLevel(nat_name.0.clone())))
.append(RcDoc::as_string(") (fun x => show (GZnZ.val "))
.append(RcDoc::as_string("_"))
.append(RcDoc::as_string(" x))."))
.append(RcDoc::hardline())
.append(RcDoc::as_string("Definition"))
.append(RcDoc::space())
.append(RcDoc::as_string("g_"))
.append(translate_ident(Ident::TopLevel(nat_name.0.clone())))
.append(RcDoc::space())
.append(RcDoc::as_string(":"))
.append(RcDoc::space())
.append(RcDoc::as_string("G ("))
.append(translate_ident(Ident::TopLevel(nat_name.0.clone())))
.append(RcDoc::as_string(") := @bindGen Z ("))
.append(translate_ident(Ident::TopLevel(nat_name.0.clone())))
.append(RcDoc::as_string(
") (arbitrary) (fun x => returnGen (@Z_in_nat_mod ",
))
.append(RcDoc::as_string("_"))
.append(RcDoc::as_string(" x))."))
.append(RcDoc::hardline())
.append(RcDoc::as_string("Instance"))
.append(RcDoc::space())
.append(RcDoc::as_string("gen_"))
.append(translate_ident(Ident::TopLevel(nat_name.0.clone())))
.append(RcDoc::space())
.append(RcDoc::as_string(":"))
.append(RcDoc::space())
.append(RcDoc::as_string("Gen ("))
.append(translate_ident(Ident::TopLevel(nat_name.0.clone())))
.append(RcDoc::as_string(") := Build_Gen"))
.append(RcDoc::space())
.append(translate_ident(Ident::TopLevel(nat_name.0.clone())))
.append(RcDoc::space())
.append(RcDoc::as_string("g_"))
.append(translate_ident(Ident::TopLevel(nat_name.0.clone())))
.append(RcDoc::as_string("."))
.append(RcDoc::hardline())
} else {
RcDoc::nil()
}),
)
}
Item::ImportedCrate((TopLevelIdent { string: kr, .. }, _)) => {
RcDoc::as_string(format!(
"Require Import {}.",
str::replace(&kr.to_title_case(), " ", "_"),
))
}
// Aliases are translated to Coq Notations
Item::AliasDecl((ident, _), (ty, _)) => {
RcDoc::as_string("Notation")
.append(RcDoc::space())
.append(RcDoc::as_string("\"'"))
.append(translate_ident(Ident::TopLevel(ident.clone())))
.append(RcDoc::as_string("'\""))
.append(RcDoc::space())
.append(RcDoc::as_string(":= ("))
.append(translate_base_typ(ty.clone()))
.append(RcDoc::as_string(") : hacspec_scope."))
.append(if export_quick_check {
match ty.clone() {
BaseTyp::Tuple(args) => {
RcDoc::hardline()
.append(RcDoc::as_string("Instance"))
.append(RcDoc::space())
.append(RcDoc::as_string("show_"))
.append(translate_ident(Ident::TopLevel(ident.clone())))
.append(RcDoc::space())
.append(RcDoc::as_string(":"))
.append(RcDoc::space())
.append(RcDoc::as_string("Show ("))
.append(translate_ident(Ident::TopLevel(ident.clone())))
.append(RcDoc::as_string(") :="))
.append(RcDoc::line())
.append(
RcDoc::as_string("Build_Show")
.append(RcDoc::space())
.append(translate_ident(Ident::TopLevel(ident.clone())))
.append(RcDoc::space())
.append(RcDoc::as_string("(fun x =>"))
.append(RcDoc::line())
.append(RcDoc::concat((0..args.len() - 1).map(|n| {
RcDoc::as_string("let (x, x")
.append(RcDoc::as_string(n.to_string()))
.append(RcDoc::as_string(") := x in"))
.append(RcDoc::line())
})))
.append(make_paren(
RcDoc::as_string("(\"(\") ++ (")
.append(RcDoc::as_string("(show x) ++ ("))
.append(RcDoc::concat((0..args.len() - 1).map(|n| {
RcDoc::as_string(
"(\",\") ++ ((show x",
)
.append(RcDoc::as_string(n.to_string()))
.append(RcDoc::as_string(") ++ ("))
})))
.append(RcDoc::as_string("\")\")"))
.append(RcDoc::concat((0..args.len() - 1).map(|_| {
RcDoc::as_string("))")
})))
.append(RcDoc::as_string("))"))
))
.append(RcDoc::as_string("%string"))
.group()
.nest(2)
)
.append(RcDoc::as_string("."))
.group()
.append(RcDoc::hardline())
.append(RcDoc::as_string("Definition"))
.append(RcDoc::space())
.append(RcDoc::as_string("g_"))
.append(translate_ident(Ident::TopLevel(ident.clone())))
.append(RcDoc::space())
.append(RcDoc::as_string(":"))
.append(RcDoc::space())
.append(RcDoc::as_string("G ("))
.append(translate_ident(Ident::TopLevel(ident.clone())))
.append(RcDoc::as_string(") :="))
.append(RcDoc::line())
.append(match ty.clone() {
BaseTyp::Tuple(args) => {
let answer =
RcDoc::concat(args.clone().into_iter().enumerate()
.map (|(n, (arg, _))| {
RcDoc::as_string(
"bindGen arbitrary (fun x",
)
.append(RcDoc::as_string(n.to_string()))
.append(RcDoc::space())
.append(RcDoc::as_string(":"))
.append(RcDoc::space())
.append(translate_base_typ(arg))
.append(RcDoc::space())
.append(RcDoc::as_string("=>"))
.append(RcDoc::line())
}));
answer
.append(RcDoc::as_string("returnGen (x0"))
.append(RcDoc::concat((1..args.len()).map(|n| {
RcDoc::as_string(",")
.append(RcDoc::as_string("x"))
.append(RcDoc::as_string(n.to_string()))
})))
.append(RcDoc::as_string(")"))
.append(RcDoc::concat(
(0..args.len()).map(|_| {
RcDoc::as_string(")")
}))
)
.group()
.nest(2)
}
_ => RcDoc::nil(),
})
.append(RcDoc::as_string("."))
.group()
.append(RcDoc::hardline())
.append(RcDoc::as_string("Instance"))
.append(RcDoc::space())
.append(RcDoc::as_string("gen_"))
.append(translate_ident(Ident::TopLevel(ident.clone())))
.append(RcDoc::space())
.append(RcDoc::as_string(":"))
.append(RcDoc::space())
.append(RcDoc::as_string("Gen ("))
.append(translate_ident(Ident::TopLevel(ident.clone())))
.append(RcDoc::as_string(") := Build_Gen"))
.append(RcDoc::space())
.append(translate_ident(Ident::TopLevel(ident.clone())))
.append(RcDoc::space())
.append(RcDoc::as_string("g_"))
.append(translate_ident(Ident::TopLevel(ident.clone())))
.append(RcDoc::as_string("."))
.group()
.append(RcDoc::hardline())
}
_ => RcDoc::nil(),
}
} else {
RcDoc::nil()
})
}
}
}
fn translate_program<'a>(
p: &'a Program,
top_ctx: &'a TopLevelContext,
export_quick_check: bool,
) -> RcDoc<'a, ()> {
RcDoc::concat(p.items.iter().map(|(i, _)| {
translate_item(i, top_ctx, export_quick_check)
.append(RcDoc::hardline())
.append(RcDoc::hardline())
}))
}
pub fn translate_and_write_to_file(
sess: &Session,
p: &Program,
file: &str,
top_ctx: &TopLevelContext,
) {
let file = file.trim();
let path = path::Path::new(file);
let mut file = match File::create(&path) {
Err(why) => {
sess.err(format!("Unable to write to output file {}: \"{}\"", file, why).as_str());
return;
}
Ok(file) => file,
};
let width = 80;
let mut w = Vec::new();
let export_quick_check = p
.items
.iter()
.any(|i| i.0.tags.0.contains(&"quickcheck".to_string()));
write!(
file,
"(** This file was automatically generated using Hacspec **)\n\
Set Warnings \"-notation-overridden,-ambiguous-paths\".\n\
Require Import Hacspec_Lib MachineIntegers.\n\
From Coq Require Import ZArith.\n\
Import List.ListNotations.\n\
Open Scope Z_scope.\n\
Open Scope bool_scope.\n\
Open Scope hacspec_scope.\n\
{}",
if export_quick_check {
"From QuickChick Require Import QuickChick.\n\
Require Import QuickChickLib.\n"
} else {
""
}
)
.unwrap();
translate_program(p, top_ctx, export_quick_check)
.render(width, &mut w)
.unwrap();
write!(file, "{}", String::from_utf8(w).unwrap()).unwrap()
}
|
//! 一覧詳細情報取得APIのデータモデル
//!
//! 技術基準適合証明等を受けた機器の検索Web-APIのリクエスト条件一覧(Ver.1.1.1)
//!
//! https://www.tele.soumu.go.jp/resource/j/giteki/webapi/gk_req_conditions.pdf
use serde::{Deserialize, Serialize};
use serde_aux::field_attributes::deserialize_number_from_string;
/// 一覧詳細情報取得APIのリクエストパラメータ
#[derive(Serialize)]
pub struct RequestParameters {
/// スタートカウント
///
/// 一覧の取得開始件数を指定。
#[serde(rename = "SC")]
pub sc: u32,
/// 取得件数
///
/// 1:10件
///
/// 2:20件
///
/// 3:30件
///
/// 4:50件
///
/// 5:100件
///
/// 6:500件
///
/// 7:1000件
#[serde(rename = "DC")]
pub dc: u8,
/// 取得形式
///
/// 1:CSV
///
/// 2:JSON
///
/// 3:XML
#[serde(rename = "OF")]
pub of: u8,
/// 氏名又は名称
///
/// 「技術基準適合証明又は工事設計認証を受けた者若しくは技術基準適合自己確認の届出業者の氏名又は名称」を指定。(部分一致検索)
#[serde(rename = "NAM")]
pub nam: Option<String>,
/// 番号
///
/// 「技術基準適合証明番号、工事設計認証番号又は届出番号」を指定。
#[serde(rename = "NUM")]
pub num: Option<String>,
/// 型式又は名称
///
/// 「機器の型式又は名称」を指定。(部分一致検索)
#[serde(rename = "TN")]
pub tn: Option<String>,
/// 認証機関コード
///
/// ※「機関コード」を参照。
#[serde(rename = "OC")]
pub oc: Option<String>,
/// 年月日(開始)
///
///年月日(開始)、年月日(終了)を指定(YYYYMMDDで指定)
///
///※年月日(開始)、年月日(終了)を指定した場合の動作については、「年月日による検索方法について」を参照。
#[serde(rename = "DS")]
pub ds: Option<String>,
/// 年月日(終了)
///
///年月日(開始)、年月日(終了)を指定(YYYYMMDDで指定)
///
///※年月日(開始)、年月日(終了)を指定した場合の動作については、「年月日による検索方法について」を参照。
#[serde(rename = "DE")]
pub de: Option<String>,
/// 添付ファイル有
///
/// 1:有のみ
#[serde(rename = "AFP")]
pub afp: Option<u8>,
/// BODYSAR対応
///
/// 1:対応
#[serde(rename = "BS")]
pub bs: Option<u8>,
/// 特定無線設備の種別
///
/// ※「特定無線設備の種別」を参照。
#[serde(rename = "REC")]
pub rec: Option<String>,
/// 技術基準適合証明の種類
///
/// ※「技術基準適合証明の種類」を参照。
#[serde(rename = "TEC")]
pub tec: Option<String>,
/// 並び替えキー
///
/// ※「並び替えキー」を参照。
#[serde(rename = "SK")]
pub sk: u8,
/// 文字コード
///
/// 1:UTF-8 ※デフォルト
///
/// 2:Shift_JIS
#[serde(rename = "MC")]
pub mc: u8,
}
impl RequestParameters {
pub fn new() -> RequestParameters {
RequestParameters {
sc: 0,
dc: 5,
of: 2,
nam: None,
num: None,
tn: None,
oc: None,
ds: None,
de: None,
afp: None,
bs: None,
rec: None,
tec: None,
sk: 1,
mc: 1,
}
}
pub fn set_sc<T: Into<u32>>(&mut self, sc: T) {
self.sc = sc.into();
}
pub fn set_dc<T: Into<u8>>(&mut self, dc: T) {
self.dc = dc.into();
}
pub fn set_nam<S: Into<String>>(&mut self, nam: S) {
self.nam = Option::from(nam.into());
}
pub fn set_num<S: Into<String>>(&mut self, num: S) {
self.num = Option::from(num.into());
}
pub fn set_tn<S: Into<String>>(&mut self, tn: S) {
self.tn = Option::from(tn.into());
}
pub fn set_oc<S: Into<String>>(&mut self, oc: S) {
self.oc = Option::from(oc.into());
}
pub fn set_ds<S: Into<String>>(&mut self, ds: S) {
self.ds = Option::from(ds.into());
}
pub fn set_de<S: Into<String>>(&mut self, de: S) {
self.de = Option::from(de.into());
}
pub fn set_afp<T: Into<u8>>(&mut self, afp: T) {
self.afp = Option::from(afp.into());
}
pub fn set_bs<T: Into<u8>>(&mut self, bs: T) {
self.bs = Option::from(bs.into());
}
pub fn set_rec<S: Into<String>>(&mut self, rec: S) {
self.rec = Option::from(rec.into());
}
pub fn set_tec<S: Into<String>>(&mut self, tec: S) {
self.tec = Option::from(tec.into());
}
pub fn set_sk<T: Into<u8>>(&mut self, sk: T) {
self.sk = sk.into();
}
}
/// 一覧詳細情報取得APIのレスポンス
#[derive(Deserialize, Serialize)]
pub struct Response {
#[serde(rename = "gitekiInformation")]
pub giteki_information: GitekiInformation,
#[serde(rename = "giteki", skip_serializing_if = "Vec::is_empty", default)]
pub giteki: Vec<GitekiInfo>,
}
#[derive(Deserialize, Serialize)]
pub struct GitekiInformation {
#[serde(rename = "lastUpdateDate")]
pub last_update_date: String,
#[serde(
rename = "totalCount",
deserialize_with = "deserialize_number_from_string"
)]
pub total_count: u32,
}
#[derive(Deserialize, Serialize)]
pub struct GitekiInfo {
#[serde(
deserialize_with = "deserialize_number_from_string",
serialize_with = "bson::compat::u2f::serialize"
)]
pub no: u32,
#[serde(rename = "techCode")]
pub tech_code: String,
pub number: String,
pub date: String,
pub name: String,
#[serde(rename = "radioEquipmentCode")]
pub radio_equipment_code: String,
#[serde(rename = "typeName")]
pub type_name: String,
#[serde(rename = "elecWave")]
pub elec_wave: String,
#[serde(rename = "spuriousRules")]
pub spurious_rules: String,
#[serde(rename = "bodySar")]
pub body_sar: String,
pub note: String,
#[serde(rename = "organName")]
pub organ_name: String,
#[serde(rename = "attachmentFileName")]
pub attachment_file_name: String,
#[serde(rename = "attachmentFileKey")]
pub attachment_file_key: String,
#[serde(rename = "attachmentFileCntForCd1")]
pub attachment_file_cnt_for_cd_1: String,
#[serde(rename = "attachmentFileCntForCd2")]
pub attachment_file_cnt_for_cd_2: String,
}
|
extern crate time;
#[macro_use]
extern crate clap;
use clap::App;
use std::fs;
use std::path::Path;
use std::time::Duration;
use std::thread;
const SEC_PER_MIN: u64 = 60;
const MINUETS_PER_DAY: i32 = 1440;
const DEFAULT_DIRECTORY: &str = "/usr/share/tod_wallpaper/";
/// Calculate the curent image index and the delay in seconds to the next image.
fn calculate_deltas(delay: i32) -> (usize, u64) {
let now = time::now();
let minuets_today = now.tm_hour * 60 + now.tm_min;
let image_i = minuets_today / delay;
let delay_next = delay - (minuets_today % delay);
(image_i as usize, delay_next as u64)
}
/// Load image list from directory and calculate delay if not provided.
fn load<P: AsRef<Path>>(directory: P, delay: Option<i32>) -> (Vec<fs::DirEntry>, i32) {
let directory = directory.as_ref();
// Check if directory exists
if !directory.exists() {
eprintln!("Image directory does not exist {:?}", directory);
std::process::exit(-1);
}
// Load image list
let mut images = fs::read_dir(directory)
.unwrap_or_else(|e| {
eprintln!("Failed to read image directory {:?}\n{}", directory, e);
std::process::exit(-1);
})
.filter_map(|f| f.ok())
.collect::<Vec<_>>();
// Check that there are files
if images.len() < 1 {
eprintln!("No images present in {:?}", directory);
std::process::exit(-1);
}
// Sort files
images.sort_by(|a, b| a.path().cmp(&b.path()));
// Calculate delay if not set
// Delay is in minuets
let delay: i32 = delay.unwrap_or(MINUETS_PER_DAY / images.len() as i32);
(images, delay)
}
/// Application's entry point
fn main() {
let yaml = load_yaml!("cli.yml");
let matches = App::from_yaml(yaml).get_matches();
// Get arguments
let directory = Path::new(matches.value_of("directory").unwrap_or(DEFAULT_DIRECTORY));
let delay = match matches.value_of("delay") {
Some(delay) => delay.parse::<i32>().ok(),
None => None,
};
let (images, delay) = load(directory, delay);
// Main loop
loop {
let (image_i, next_delay) = calculate_deltas(delay);
// Bounds checking
let image_i = if image_i > images.len() {
images.len() - 1
} else {
image_i
};
// Get the next image
let next_image = &images[image_i];
// Run feh with the next image's path
// $ feh --bg-fill <path>
std::process::Command::new("feh")
.arg("--bg-fill")
.arg(next_image.path())
.status()
.expect("failed to execute process: feh");
// Sleep until the next update is due
thread::sleep(Duration::from_secs(next_delay * SEC_PER_MIN));
}
}
|
#[doc = "Reader of register GPIO_CTRL"]
pub type R = crate::R<u32, super::GPIO_CTRL>;
#[doc = "Writer for register GPIO_CTRL"]
pub type W = crate::W<u32, super::GPIO_CTRL>;
#[doc = "Register GPIO_CTRL `reset()`'s with value 0x1f"]
impl crate::ResetValue for super::GPIO_CTRL {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0x1f
}
}
#[doc = "\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum IRQOVER_A {
#[doc = "0: don't invert the interrupt"]
NORMAL = 0,
#[doc = "1: invert the interrupt"]
INVERT = 1,
#[doc = "2: drive interrupt low"]
LOW = 2,
#[doc = "3: drive interrupt high"]
HIGH = 3,
}
impl From<IRQOVER_A> for u8 {
#[inline(always)]
fn from(variant: IRQOVER_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `IRQOVER`"]
pub type IRQOVER_R = crate::R<u8, IRQOVER_A>;
impl IRQOVER_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> IRQOVER_A {
match self.bits {
0 => IRQOVER_A::NORMAL,
1 => IRQOVER_A::INVERT,
2 => IRQOVER_A::LOW,
3 => IRQOVER_A::HIGH,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `NORMAL`"]
#[inline(always)]
pub fn is_normal(&self) -> bool {
*self == IRQOVER_A::NORMAL
}
#[doc = "Checks if the value of the field is `INVERT`"]
#[inline(always)]
pub fn is_invert(&self) -> bool {
*self == IRQOVER_A::INVERT
}
#[doc = "Checks if the value of the field is `LOW`"]
#[inline(always)]
pub fn is_low(&self) -> bool {
*self == IRQOVER_A::LOW
}
#[doc = "Checks if the value of the field is `HIGH`"]
#[inline(always)]
pub fn is_high(&self) -> bool {
*self == IRQOVER_A::HIGH
}
}
#[doc = "Write proxy for field `IRQOVER`"]
pub struct IRQOVER_W<'a> {
w: &'a mut W,
}
impl<'a> IRQOVER_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: IRQOVER_A) -> &'a mut W {
{
self.bits(variant.into())
}
}
#[doc = "don't invert the interrupt"]
#[inline(always)]
pub fn normal(self) -> &'a mut W {
self.variant(IRQOVER_A::NORMAL)
}
#[doc = "invert the interrupt"]
#[inline(always)]
pub fn invert(self) -> &'a mut W {
self.variant(IRQOVER_A::INVERT)
}
#[doc = "drive interrupt low"]
#[inline(always)]
pub fn low(self) -> &'a mut W {
self.variant(IRQOVER_A::LOW)
}
#[doc = "drive interrupt high"]
#[inline(always)]
pub fn high(self) -> &'a mut W {
self.variant(IRQOVER_A::HIGH)
}
#[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 << 28)) | (((value as u32) & 0x03) << 28);
self.w
}
}
#[doc = "\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum INOVER_A {
#[doc = "0: don't invert the peri input"]
NORMAL = 0,
#[doc = "1: invert the peri input"]
INVERT = 1,
#[doc = "2: drive peri input low"]
LOW = 2,
#[doc = "3: drive peri input high"]
HIGH = 3,
}
impl From<INOVER_A> for u8 {
#[inline(always)]
fn from(variant: INOVER_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `INOVER`"]
pub type INOVER_R = crate::R<u8, INOVER_A>;
impl INOVER_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> INOVER_A {
match self.bits {
0 => INOVER_A::NORMAL,
1 => INOVER_A::INVERT,
2 => INOVER_A::LOW,
3 => INOVER_A::HIGH,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `NORMAL`"]
#[inline(always)]
pub fn is_normal(&self) -> bool {
*self == INOVER_A::NORMAL
}
#[doc = "Checks if the value of the field is `INVERT`"]
#[inline(always)]
pub fn is_invert(&self) -> bool {
*self == INOVER_A::INVERT
}
#[doc = "Checks if the value of the field is `LOW`"]
#[inline(always)]
pub fn is_low(&self) -> bool {
*self == INOVER_A::LOW
}
#[doc = "Checks if the value of the field is `HIGH`"]
#[inline(always)]
pub fn is_high(&self) -> bool {
*self == INOVER_A::HIGH
}
}
#[doc = "Write proxy for field `INOVER`"]
pub struct INOVER_W<'a> {
w: &'a mut W,
}
impl<'a> INOVER_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: INOVER_A) -> &'a mut W {
{
self.bits(variant.into())
}
}
#[doc = "don't invert the peri input"]
#[inline(always)]
pub fn normal(self) -> &'a mut W {
self.variant(INOVER_A::NORMAL)
}
#[doc = "invert the peri input"]
#[inline(always)]
pub fn invert(self) -> &'a mut W {
self.variant(INOVER_A::INVERT)
}
#[doc = "drive peri input low"]
#[inline(always)]
pub fn low(self) -> &'a mut W {
self.variant(INOVER_A::LOW)
}
#[doc = "drive peri input high"]
#[inline(always)]
pub fn high(self) -> &'a mut W {
self.variant(INOVER_A::HIGH)
}
#[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 << 16)) | (((value as u32) & 0x03) << 16);
self.w
}
}
#[doc = "\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum OEOVER_A {
#[doc = "0: drive output enable from peripheral signal selected by funcsel"]
NORMAL = 0,
#[doc = "1: drive output enable from inverse of peripheral signal selected by funcsel"]
INVERT = 1,
#[doc = "2: disable output"]
DISABLE = 2,
#[doc = "3: enable output"]
ENABLE = 3,
}
impl From<OEOVER_A> for u8 {
#[inline(always)]
fn from(variant: OEOVER_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `OEOVER`"]
pub type OEOVER_R = crate::R<u8, OEOVER_A>;
impl OEOVER_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> OEOVER_A {
match self.bits {
0 => OEOVER_A::NORMAL,
1 => OEOVER_A::INVERT,
2 => OEOVER_A::DISABLE,
3 => OEOVER_A::ENABLE,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `NORMAL`"]
#[inline(always)]
pub fn is_normal(&self) -> bool {
*self == OEOVER_A::NORMAL
}
#[doc = "Checks if the value of the field is `INVERT`"]
#[inline(always)]
pub fn is_invert(&self) -> bool {
*self == OEOVER_A::INVERT
}
#[doc = "Checks if the value of the field is `DISABLE`"]
#[inline(always)]
pub fn is_disable(&self) -> bool {
*self == OEOVER_A::DISABLE
}
#[doc = "Checks if the value of the field is `ENABLE`"]
#[inline(always)]
pub fn is_enable(&self) -> bool {
*self == OEOVER_A::ENABLE
}
}
#[doc = "Write proxy for field `OEOVER`"]
pub struct OEOVER_W<'a> {
w: &'a mut W,
}
impl<'a> OEOVER_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: OEOVER_A) -> &'a mut W {
{
self.bits(variant.into())
}
}
#[doc = "drive output enable from peripheral signal selected by funcsel"]
#[inline(always)]
pub fn normal(self) -> &'a mut W {
self.variant(OEOVER_A::NORMAL)
}
#[doc = "drive output enable from inverse of peripheral signal selected by funcsel"]
#[inline(always)]
pub fn invert(self) -> &'a mut W {
self.variant(OEOVER_A::INVERT)
}
#[doc = "disable output"]
#[inline(always)]
pub fn disable(self) -> &'a mut W {
self.variant(OEOVER_A::DISABLE)
}
#[doc = "enable output"]
#[inline(always)]
pub fn enable(self) -> &'a mut W {
self.variant(OEOVER_A::ENABLE)
}
#[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 << 12)) | (((value as u32) & 0x03) << 12);
self.w
}
}
#[doc = "\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum OUTOVER_A {
#[doc = "0: drive output from peripheral signal selected by funcsel"]
NORMAL = 0,
#[doc = "1: drive output from inverse of peripheral signal selected by funcsel"]
INVERT = 1,
#[doc = "2: drive output low"]
LOW = 2,
#[doc = "3: drive output high"]
HIGH = 3,
}
impl From<OUTOVER_A> for u8 {
#[inline(always)]
fn from(variant: OUTOVER_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `OUTOVER`"]
pub type OUTOVER_R = crate::R<u8, OUTOVER_A>;
impl OUTOVER_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> OUTOVER_A {
match self.bits {
0 => OUTOVER_A::NORMAL,
1 => OUTOVER_A::INVERT,
2 => OUTOVER_A::LOW,
3 => OUTOVER_A::HIGH,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `NORMAL`"]
#[inline(always)]
pub fn is_normal(&self) -> bool {
*self == OUTOVER_A::NORMAL
}
#[doc = "Checks if the value of the field is `INVERT`"]
#[inline(always)]
pub fn is_invert(&self) -> bool {
*self == OUTOVER_A::INVERT
}
#[doc = "Checks if the value of the field is `LOW`"]
#[inline(always)]
pub fn is_low(&self) -> bool {
*self == OUTOVER_A::LOW
}
#[doc = "Checks if the value of the field is `HIGH`"]
#[inline(always)]
pub fn is_high(&self) -> bool {
*self == OUTOVER_A::HIGH
}
}
#[doc = "Write proxy for field `OUTOVER`"]
pub struct OUTOVER_W<'a> {
w: &'a mut W,
}
impl<'a> OUTOVER_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: OUTOVER_A) -> &'a mut W {
{
self.bits(variant.into())
}
}
#[doc = "drive output from peripheral signal selected by funcsel"]
#[inline(always)]
pub fn normal(self) -> &'a mut W {
self.variant(OUTOVER_A::NORMAL)
}
#[doc = "drive output from inverse of peripheral signal selected by funcsel"]
#[inline(always)]
pub fn invert(self) -> &'a mut W {
self.variant(OUTOVER_A::INVERT)
}
#[doc = "drive output low"]
#[inline(always)]
pub fn low(self) -> &'a mut W {
self.variant(OUTOVER_A::LOW)
}
#[doc = "drive output high"]
#[inline(always)]
pub fn high(self) -> &'a mut W {
self.variant(OUTOVER_A::HIGH)
}
#[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 << 8)) | (((value as u32) & 0x03) << 8);
self.w
}
}
#[doc = "0-31 -> selects pin function according to the gpio table\\n 31 == NULL\n\nValue on reset: 31"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum FUNCSEL_A {
#[doc = "0: `0`"]
JTAG_TCK = 0,
#[doc = "1: `1`"]
SPI0_RX = 1,
#[doc = "2: `10`"]
UART0_TX = 2,
#[doc = "3: `11`"]
I2C0_SDA = 3,
#[doc = "4: `100`"]
PWM_A_0 = 4,
#[doc = "5: `101`"]
SIO_0 = 5,
#[doc = "6: `110`"]
PIO0_0 = 6,
#[doc = "7: `111`"]
PIO1_0 = 7,
#[doc = "9: `1001`"]
USB_MUXING_OVERCURR_DETECT = 9,
#[doc = "31: `11111`"]
NULL = 31,
}
impl From<FUNCSEL_A> for u8 {
#[inline(always)]
fn from(variant: FUNCSEL_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `FUNCSEL`"]
pub type FUNCSEL_R = crate::R<u8, FUNCSEL_A>;
impl FUNCSEL_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, FUNCSEL_A> {
use crate::Variant::*;
match self.bits {
0 => Val(FUNCSEL_A::JTAG_TCK),
1 => Val(FUNCSEL_A::SPI0_RX),
2 => Val(FUNCSEL_A::UART0_TX),
3 => Val(FUNCSEL_A::I2C0_SDA),
4 => Val(FUNCSEL_A::PWM_A_0),
5 => Val(FUNCSEL_A::SIO_0),
6 => Val(FUNCSEL_A::PIO0_0),
7 => Val(FUNCSEL_A::PIO1_0),
9 => Val(FUNCSEL_A::USB_MUXING_OVERCURR_DETECT),
31 => Val(FUNCSEL_A::NULL),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `JTAG_TCK`"]
#[inline(always)]
pub fn is_jtag_tck(&self) -> bool {
*self == FUNCSEL_A::JTAG_TCK
}
#[doc = "Checks if the value of the field is `SPI0_RX`"]
#[inline(always)]
pub fn is_spi0_rx(&self) -> bool {
*self == FUNCSEL_A::SPI0_RX
}
#[doc = "Checks if the value of the field is `UART0_TX`"]
#[inline(always)]
pub fn is_uart0_tx(&self) -> bool {
*self == FUNCSEL_A::UART0_TX
}
#[doc = "Checks if the value of the field is `I2C0_SDA`"]
#[inline(always)]
pub fn is_i2c0_sda(&self) -> bool {
*self == FUNCSEL_A::I2C0_SDA
}
#[doc = "Checks if the value of the field is `PWM_A_0`"]
#[inline(always)]
pub fn is_pwm_a_0(&self) -> bool {
*self == FUNCSEL_A::PWM_A_0
}
#[doc = "Checks if the value of the field is `SIO_0`"]
#[inline(always)]
pub fn is_sio_0(&self) -> bool {
*self == FUNCSEL_A::SIO_0
}
#[doc = "Checks if the value of the field is `PIO0_0`"]
#[inline(always)]
pub fn is_pio0_0(&self) -> bool {
*self == FUNCSEL_A::PIO0_0
}
#[doc = "Checks if the value of the field is `PIO1_0`"]
#[inline(always)]
pub fn is_pio1_0(&self) -> bool {
*self == FUNCSEL_A::PIO1_0
}
#[doc = "Checks if the value of the field is `USB_MUXING_OVERCURR_DETECT`"]
#[inline(always)]
pub fn is_usb_muxing_overcurr_detect(&self) -> bool {
*self == FUNCSEL_A::USB_MUXING_OVERCURR_DETECT
}
#[doc = "Checks if the value of the field is `NULL`"]
#[inline(always)]
pub fn is_null(&self) -> bool {
*self == FUNCSEL_A::NULL
}
}
#[doc = "Write proxy for field `FUNCSEL`"]
pub struct FUNCSEL_W<'a> {
w: &'a mut W,
}
impl<'a> FUNCSEL_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: FUNCSEL_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "`0`"]
#[inline(always)]
pub fn jtag_tck(self) -> &'a mut W {
self.variant(FUNCSEL_A::JTAG_TCK)
}
#[doc = "`1`"]
#[inline(always)]
pub fn spi0_rx(self) -> &'a mut W {
self.variant(FUNCSEL_A::SPI0_RX)
}
#[doc = "`10`"]
#[inline(always)]
pub fn uart0_tx(self) -> &'a mut W {
self.variant(FUNCSEL_A::UART0_TX)
}
#[doc = "`11`"]
#[inline(always)]
pub fn i2c0_sda(self) -> &'a mut W {
self.variant(FUNCSEL_A::I2C0_SDA)
}
#[doc = "`100`"]
#[inline(always)]
pub fn pwm_a_0(self) -> &'a mut W {
self.variant(FUNCSEL_A::PWM_A_0)
}
#[doc = "`101`"]
#[inline(always)]
pub fn sio_0(self) -> &'a mut W {
self.variant(FUNCSEL_A::SIO_0)
}
#[doc = "`110`"]
#[inline(always)]
pub fn pio0_0(self) -> &'a mut W {
self.variant(FUNCSEL_A::PIO0_0)
}
#[doc = "`111`"]
#[inline(always)]
pub fn pio1_0(self) -> &'a mut W {
self.variant(FUNCSEL_A::PIO1_0)
}
#[doc = "`1001`"]
#[inline(always)]
pub fn usb_muxing_overcurr_detect(self) -> &'a mut W {
self.variant(FUNCSEL_A::USB_MUXING_OVERCURR_DETECT)
}
#[doc = "`11111`"]
#[inline(always)]
pub fn null(self) -> &'a mut W {
self.variant(FUNCSEL_A::NULL)
}
#[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 & !0x1f) | ((value as u32) & 0x1f);
self.w
}
}
impl R {
#[doc = "Bits 28:29"]
#[inline(always)]
pub fn irqover(&self) -> IRQOVER_R {
IRQOVER_R::new(((self.bits >> 28) & 0x03) as u8)
}
#[doc = "Bits 16:17"]
#[inline(always)]
pub fn inover(&self) -> INOVER_R {
INOVER_R::new(((self.bits >> 16) & 0x03) as u8)
}
#[doc = "Bits 12:13"]
#[inline(always)]
pub fn oeover(&self) -> OEOVER_R {
OEOVER_R::new(((self.bits >> 12) & 0x03) as u8)
}
#[doc = "Bits 8:9"]
#[inline(always)]
pub fn outover(&self) -> OUTOVER_R {
OUTOVER_R::new(((self.bits >> 8) & 0x03) as u8)
}
#[doc = "Bits 0:4 - 0-31 -> selects pin function according to the gpio table\\n 31 == NULL"]
#[inline(always)]
pub fn funcsel(&self) -> FUNCSEL_R {
FUNCSEL_R::new((self.bits & 0x1f) as u8)
}
}
impl W {
#[doc = "Bits 28:29"]
#[inline(always)]
pub fn irqover(&mut self) -> IRQOVER_W {
IRQOVER_W { w: self }
}
#[doc = "Bits 16:17"]
#[inline(always)]
pub fn inover(&mut self) -> INOVER_W {
INOVER_W { w: self }
}
#[doc = "Bits 12:13"]
#[inline(always)]
pub fn oeover(&mut self) -> OEOVER_W {
OEOVER_W { w: self }
}
#[doc = "Bits 8:9"]
#[inline(always)]
pub fn outover(&mut self) -> OUTOVER_W {
OUTOVER_W { w: self }
}
#[doc = "Bits 0:4 - 0-31 -> selects pin function according to the gpio table\\n 31 == NULL"]
#[inline(always)]
pub fn funcsel(&mut self) -> FUNCSEL_W {
FUNCSEL_W { w: self }
}
}
|
//! # howto
//!
//! Instant coding answers with Google and StackOverflow.
//! Inspired by [gleitz/howdoi](https://github.com/gleitz/howdoi).
//!
//! ## Usage
//!
//! ```
//! # use futures::prelude::*;
//! # async move {
//! let mut answers = howto::howto("file io rust").await;
//!
//! while let Some(answer) = answers.next().await {
//! println!("Answer from {}\n{}", answer.link, answer.instruction);
//! }
//! # };
//! ```
#[cfg(test)]
mod tests;
use failure::{ensure, format_err, Fallible};
use futures::prelude::*;
use lazy_static::lazy_static;
use scraper::{Html, Selector};
use std::pin::Pin;
/// Struct containing the answer of given query.
#[derive(Debug, Clone)]
pub struct Answer {
pub question_title: String,
pub link: String,
pub full_text: String,
pub instruction: String,
}
async fn get(url: &str) -> Fallible<String> {
let resp = reqwest::Client::new()
.get(url)
.header(
"User-Agent",
"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100 101 Firefox/22.0",
)
.send()
.await
.map_err(|e| failure::Error::from_boxed_compat(Box::new(e)))?;
ensure!(
resp.status().is_success(),
format_err!("Request error: {}", resp.status())
);
Ok(resp
.text()
.await
.map_err(|e| failure::Error::from_boxed_compat(Box::new(e)))?)
}
async fn get_stackoverflow_links(query: &str) -> Fallible<Vec<String>> {
lazy_static! {
static ref LINK_SELECTOR: Selector = Selector::parse(".r>a").unwrap();
}
let url = format!(
"https://www.google.com/search?q=site:stackoverflow.com {}",
query,
);
let content = get(&url).await?;
let html = Html::parse_document(&content);
let links: Vec<_> = html
.select(&LINK_SELECTOR)
.filter_map(|e| e.value().attr("href"))
.map(ToString::to_string)
.filter(|link| link.starts_with("https://stackoverflow.com/"))
.collect();
Ok(links)
}
async fn get_answer(link: &str) -> Fallible<Answer> {
lazy_static! {
static ref TITLE_SELECTOR: Selector = Selector::parse("#question-header>h1").unwrap();
static ref ANSWER_SELECTOR: Selector = Selector::parse(".answer").unwrap();
static ref TEXT_SELECTOR: Selector = Selector::parse(".post-text>*").unwrap();
static ref PRE_INSTRUCTION_SELECTOR: Selector = Selector::parse("pre").unwrap();
static ref CODE_INSTRUCTION_SELECTOR: Selector = Selector::parse("code").unwrap();
}
macro_rules! unwrap_or_bail {
($o:expr) => {
$o.ok_or_else(|| format_err!("Cannot parse StackOverflow"))?
};
};
let url = format!("{}?answerstab=votes", link);
let link = link.to_string();
let content = get(&url).await?;
let html = Html::parse_document(&content);
let title_html = unwrap_or_bail!(html.select(&TITLE_SELECTOR).next());
let question_title = title_html.text().collect::<Vec<_>>().join("");
let answer = unwrap_or_bail!(html.select(&ANSWER_SELECTOR).next());
let instruction_html = unwrap_or_bail!(answer
.select(&PRE_INSTRUCTION_SELECTOR)
.next()
.or_else(|| answer.select(&CODE_INSTRUCTION_SELECTOR).next()));
let instruction = instruction_html.text().collect::<Vec<_>>().join("");
let full_text = answer
.select(&TEXT_SELECTOR)
.flat_map(|e| e.text())
.collect::<Vec<_>>()
.join("");
Ok(Answer {
question_title,
link,
instruction,
full_text,
})
}
/// Query function. Give query to this function and thats it! Google and StackOverflow will do the rest.
pub async fn howto(query: &str) -> Pin<Box<dyn Stream<Item = Answer> + Send>> {
let links = get_stackoverflow_links(query).await.unwrap_or_default();
stream::iter(links)
.filter_map(move |link| async move { get_answer(&link).await.ok() })
.boxed()
}
/// Prefetch n queries with `FuturesOrdered`, and then others.
pub async fn prefetch_howto(query: &str, n: usize) -> Pin<Box<dyn Stream<Item = Answer> + Send>> {
let mut links = get_stackoverflow_links(query).await.unwrap_or_default();
let others = if links.len() < n {
vec![]
} else {
links.split_off(n)
};
let prefetch_stream = links
.into_iter()
.map(move |link| async move { get_answer(&link).await.ok() })
.collect::<stream::FuturesOrdered<_>>()
.filter_map(future::ready);
let others_stream =
stream::iter(others).filter_map(move |link| async move { get_answer(&link).await.ok() });
prefetch_stream.chain(others_stream).boxed()
}
|
extern crate serde_codegen;
extern crate syntex;
use std::env::var_os;
use std::fs::File;
use std::io::copy;
use std::path::Path;
use std::process::Command;
use serde_codegen::register;
use syntex::Registry;
fn main() {
let out_dir = var_os("OUT_DIR").expect("OUT_DIR not specified");
let out_path = Path::new(&out_dir);
let src_path = Path::new("src");
// DynamoDB
generate(
"codegen/botocore/botocore/data/dynamodb/2012-08-10/service-2.json",
"DynamoDBClient",
out_path,
"dynamodb",
);
serde_generate(
&src_path.join("kms_helpers.in.rs"),
&out_path.join("kms_helpers.rs"),
);
// ECS
generate(
"codegen/botocore/botocore/data/ecs/2014-11-13/service-2.json",
"ECSClient",
out_path,
"ecs",
);
serde_generate(
&src_path.join("ecs_helpers.in.rs"),
&out_path.join("ecs_helpers.rs"),
);
// KMS
generate(
"codegen/botocore/botocore/data/kms/2014-11-01/service-2.json",
"KMSClient",
out_path,
"kms",
);
serde_generate(
&src_path.join("dynamodb_helpers.in.rs"),
&out_path.join("dynamodb_helpers.rs"),
);
// SQS
generate(
"codegen/botocore/botocore/data/sqs/2012-11-05/service-2.json",
"SQSClient",
out_path,
"sqs",
)
}
fn botocore_generate(input: &str, type_name: &str, destination: &Path) {
let mut command = Command::new("codegen/botocore_parser.py");
command.args(&[input, type_name]);
let output = command.output().expect("couldn't get output of child process");
if !output.status.success() {
println!("{}", String::from_utf8_lossy(&output.stderr[..]));
panic!("child process was unsuccessful");
}
let mut file = File::create(destination).expect("couldn't open file for writing");
copy(&mut &output.stdout[..], &mut file).expect("failed to write generated code to file");
}
fn generate(
input: &str,
type_name: &str,
base_destination: &Path,
service_name: &str,
) {
let botocore_destination = base_destination.join(format!("{}_botocore.rs", service_name));
let serde_destination = base_destination.join(format!("{}.rs", service_name));
botocore_generate(input, type_name, botocore_destination.as_path());
serde_generate(botocore_destination.as_path(), serde_destination.as_path());
}
fn serde_generate(source: &Path, destination: &Path) {
let mut registry = Registry::new();
register(&mut registry);
registry.expand("", source, destination).expect("failed to generate code with Serde");
}
|
use std::sync::Arc;
use crate::bxdf::TransportMode;
use crate::primitive::Primitive;
use crate::interaction::SurfaceInteraction;
use crate::light::Light;
use crate::material::Material;
mod bvh;
pub use self::bvh::{ BvhAccel, SplitMethod };
pub trait Aggregate: Primitive { }
default impl<T> Primitive for T where T: Aggregate {
default fn get_area_light(&self) -> Option<Arc<dyn Light + Send + Sync>> {
panic!("Aggregate::get_area_light should never be called")
}
default fn get_material(&self) -> Option<&(dyn Material + Send + Sync)> {
panic!("Aggregate::get_material should never be called")
}
default fn compute_scattering_functions(&'a self, _: SurfaceInteraction<'a>, _: &(), _: TransportMode, _: bool) -> SurfaceInteraction<'a> {
panic!("Aggregate::compute_scattering_functions should never be called");
}
}
|
use std::env;
fn move_(disk:i32, from : i32 , to : i32 , via :i32 ,n : i32 )
{ // let mut i :i32=n;
if disk == n
{
println!("this is a thing")
}
if disk >0
{
move_ (disk -1 , from , to, via,n );
//println!("Move disk from pole {} to pole {}", from, to);
move_ (disk -1 , via, to , from,n);
}
}
fn main( )
{
let args : Vec<String> = env::args().collect();
let disks = if args.len() > 1 {args[1].parse::<i32>().unwrap()} else { 5 } ;
move_(disks,1,2,3,disks);
println!("hello");
}
|
//! Contains post processing logic for solution.
use crate::construction::heuristics::InsertionContext;
mod advance_departure;
pub use self::advance_departure::AdvanceDeparture;
/// A trait which specifies the logic to apply post processing to solution.
pub trait PostProcessing {
/// Applies post processing to given solution.
fn process(&self, insertion_ctx: InsertionContext) -> InsertionContext;
}
|
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use simple_socket::{PostServing, SocketClient, SocketServer};
use podo_core_driver::AliveFlag;
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
enum Request {
Hello(String),
Goodbye(String),
}
#[derive(Debug, Serialize, Deserialize)]
enum Response {
Echo(String),
}
fn main() {
const IP_V4: Ipv4Addr = Ipv4Addr::new(127, 0, 0, 1);
const IP: IpAddr = IpAddr::V4(IP_V4);
const PORT: u16 = 9804;
let socket = SocketAddr::new(IP, PORT);
let alive = AliveFlag::new(true);
let active = AliveFlag::new(false);
let server_alive = alive.clone();
let server_active = active.clone();
let server_thread = std::thread::spawn(move || {
let handler = |req| match req {
Request::Hello(name) => Response::Echo(format!("Hello, {}!", name)),
Request::Goodbye(name) => Response::Echo(format!("Goodbye, {}!", name)),
};
let backlog = Default::default();
let server = SocketServer::<Request, Response>::try_new(socket, backlog).unwrap();
server
.run(handler, |server| {
server_active.start().ok();
if server_alive.is_running() || server.has_connections() {
PostServing::Yield
} else {
PostServing::Stop
}
})
.unwrap();
});
while !active.is_running() {
std::thread::yield_now();
}
{
let name = "foo".to_string();
let client = SocketClient::<Request, Response>::try_new(socket).unwrap();
let response = client.request(&Request::Hello(name.clone())).unwrap();
dbg!(response);
let response = client.request(&Request::Goodbye(name)).unwrap();
dbg!(response);
}
alive.stop().unwrap();
server_thread.join().unwrap();
}
|
// ---------------------------------------------------------------------
// ZkConfig
// ---------------------------------------------------------------------
// Copyright (C) 2007-2021 The NOC Project
// See LICENSE for details
// ---------------------------------------------------------------------
use crate::collectors::CollectorConfig;
use serde::Deserialize;
#[derive(Deserialize, Debug)]
pub struct ZkConfig {
#[serde(rename = "$version")]
_version: String,
#[serde(rename = "$type")]
_type: String,
pub config: ZkConfigConfig,
pub collectors: Vec<ZkConfigCollector>,
}
#[derive(Deserialize, Debug)]
pub struct ZkConfigConfig {
pub zeroconf: ZkConfigConfigZeroconf,
}
#[derive(Deserialize, Debug)]
pub struct ZkConfigConfigZeroconf {
pub interval: u64,
}
#[derive(Deserialize, Debug)]
pub struct ZkConfigCollector {
pub id: String,
#[serde(default)]
pub service: Option<String>,
pub interval: u64,
#[serde(default)]
pub disabled: bool,
#[serde(default)]
pub labels: Vec<String>,
#[serde(flatten)]
pub config: CollectorConfig,
}
impl ZkConfigCollector {
pub fn get_id(&self) -> String {
self.id.clone()
}
pub fn get_service(&self) -> String {
match &self.service {
Some(x) => x.into(),
None => self.get_id(),
}
}
pub fn get_interval(&self) -> u64 {
self.interval
}
pub fn get_labels(&self) -> Vec<String> {
self.labels.clone()
}
}
|
use ethers::{
abi::{Function, ParamType, Token, Tokenizable},
types::{Address, Bytes, U256},
};
use proptest::prelude::*;
pub fn fuzz_calldata(func: &Function) -> impl Strategy<Value = Bytes> + '_ {
// We need to compose all the strategies generated for each parameter in all
// possible combinations
let strats = func.inputs.iter().map(|input| fuzz_param(&input.kind)).collect::<Vec<_>>();
strats.prop_map(move |tokens| func.encode_input(&tokens).unwrap().into())
}
fn fuzz_param(param: &ParamType) -> impl Strategy<Value = Token> {
match param {
ParamType::Address => {
// The key to making this work is the `boxed()` call which type erases everything
// https://altsysrq.github.io/proptest-book/proptest/tutorial/transforming-strategies.html
any::<[u8; 20]>().prop_map(|x| Address::from_slice(&x).into_token()).boxed()
}
ParamType::Uint(n) => match n / 8 {
1 => any::<u8>().prop_map(|x| x.into_token()).boxed(),
2 => any::<u16>().prop_map(|x| x.into_token()).boxed(),
3..=4 => any::<u32>().prop_map(|x| x.into_token()).boxed(),
5..=8 => any::<u64>().prop_map(|x| x.into_token()).boxed(),
9..=16 => any::<u128>().prop_map(|x| x.into_token()).boxed(),
17..=32 => any::<[u8; 32]>().prop_map(|x| U256::from(&x).into_token()).boxed(),
_ => panic!("unsupported solidity type uint{}", n),
},
ParamType::String => any::<String>().prop_map(|x| x.into_token()).boxed(),
ParamType::Bytes => any::<Vec<u8>>().prop_map(|x| Bytes::from(x).into_token()).boxed(),
// TODO: Implement the rest of the strategies
_ => unimplemented!(),
}
}
|
use crate::{keypair::PublicKey, result::Result};
use helium_crypto::{ecc_compact, ed25519, KeyType};
use io::{Read, Write};
use std::{convert::TryFrom, io};
pub trait ReadWrite {
fn read(reader: &mut dyn Read) -> Result<Self>
where
Self: std::marker::Sized;
fn write(&self, writer: &mut dyn Write) -> Result;
}
impl ReadWrite for PublicKey {
fn write(&self, writer: &mut dyn io::Write) -> Result {
Ok(writer.write_all(&self.to_vec())?)
}
fn read(reader: &mut dyn Read) -> Result<PublicKey> {
let mut data = vec![0u8; 1];
reader.read_exact(&mut data[0..1])?;
let key_size = match KeyType::try_from(data[0])? {
KeyType::Ed25519 => ed25519::PUBLIC_KEY_LENGTH,
KeyType::EccCompact => ecc_compact::PUBLIC_KEY_LENGTH,
};
data.resize(key_size, 0);
reader.read_exact(&mut data[1..])?;
Ok(PublicKey::from_bytes(data)?)
}
}
|
use crate::domain::model::{IPostRepository, NewPost, Post, User};
use diesel::pg::PgConnection;
use diesel::prelude::*;
use std::sync::{Arc, Mutex};
#[derive(Clone)]
pub struct PostRepository {
conn: Arc<Mutex<PgConnection>>,
}
impl PostRepository {
pub fn new(conn: Arc<Mutex<PgConnection>>) -> Self {
PostRepository { conn }
}
}
impl IPostRepository for PostRepository {
fn create<'a>(&self, body: &'a str, user: &'a User) -> QueryResult<Post> {
use crate::schema::posts;
let new_post = NewPost {
body,
user_id: &user.id,
};
diesel::insert_into(posts::table)
.values(&new_post)
.get_result(&*self.conn.lock().unwrap())
}
fn pagenate_posts_of_user<'a>(
&self,
user: &'a User,
limit: i64,
offset: i64,
) -> QueryResult<Vec<Post>> {
use crate::schema::posts;
use crate::schema::users;
posts::table
.inner_join(users::table)
.filter(users::id.eq(&user.id))
.select(posts::all_columns)
.order_by(posts::created_at.desc())
.limit(limit)
.offset(offset)
.load(&*self.conn.lock().unwrap())
}
}
|
use buttplug::{
client::{ButtplugClient, ButtplugClientDevice, VibrateCommand},
server::ButtplugServerOptions,
util::async_manager,
};
use futures::StreamExt;
use futures_timer::Delay;
use std::{sync::Arc, time::Duration};
fn main() {
println!("start...");
async_manager::block_on(async {
control().await;
});
}
async fn control() {
println!("running control");
let client = ButtplugClient::new("mowmow");
let mut events = client.event_stream();
println!("waiting for server");
client
.connect_in_process(&ButtplugServerOptions::default())
.await
.unwrap();
if let Err(err) = client.start_scanning().await {
println!("Client errored when starting scan! {}", err);
return;
}
let vibr = |dev: Arc<ButtplugClientDevice>| async move {
println!("{} should start vibrating!", dev.name);
loop {
dev.vibrate(VibrateCommand::Speed(0.9)).await.unwrap();
Delay::new(Duration::from_millis(500)).await;
dev.vibrate(VibrateCommand::Speed(0.5)).await.unwrap();
Delay::new(Duration::from_millis(500)).await;
}
};
println!("loop starting now");
loop {
match events.next().await.unwrap() {
buttplug::client::ButtplugClientEvent::ScanningFinished => {}
buttplug::client::ButtplugClientEvent::DeviceAdded(dev) => {
println!("Device {devname} added!", devname = dev.name);
vibr(dev).await;
}
buttplug::client::ButtplugClientEvent::DeviceRemoved(_) => {}
buttplug::client::ButtplugClientEvent::PingTimeout => {}
buttplug::client::ButtplugClientEvent::ServerConnect => {}
buttplug::client::ButtplugClientEvent::ServerDisconnect => {}
buttplug::client::ButtplugClientEvent::Error(_) => {}
}
}
}
|
use std::fs;
use std::ops::Deref;
use std::path::PathBuf;
use regex::Regex;
#[derive(Debug, Clone)]
pub struct Tokenizer {
token_data: Option<TokenData>,
tokens: Vec<String>,
idx: usize,
}
impl Tokenizer {
pub fn new(pb: &PathBuf) -> Self {
let jack = fs::read_to_string(pb).unwrap();
let jack = remove_comments(jack);
let (jack, string_consts) = get_string_consts(&jack);
let mut tokens: Vec<String> = jack.split_whitespace().map(|s| s.to_string()).collect();
let mut i = 0;
for token in &mut tokens {
if token == "/*STRING_CONST*/" {
let string_const = format!("\"{}\"", string_consts[i].clone());
*token = string_const;
i += 1;
}
}
Tokenizer {
token_data: None,
tokens,
idx: 0,
}
}
pub fn reset(&mut self) {
self.token_data = None;
self.idx = 0;
}
pub fn has_more_tokens(&self) -> bool {
self.tokens.len() > self.idx
}
pub fn advance(&mut self) {
if self.has_more_tokens() {
self.set_token_data();
self.idx += 1;
}
}
pub fn get_token_debug(&self) {
println!("{:?}", self.token_data);
}
pub fn get_token(&self) -> &Option<TokenData> {
&self.token_data
}
pub fn peek_token(&self) -> Option<TokenData> {
if self.idx < self.tokens.len() {
let token_data = TokenData::new(&self.tokens[self.idx]);
Some(token_data)
} else {
None
}
}
pub fn get_string_val(&self) -> Option<String> {
if let Some(TokenData::TStringVal(str)) = self.get_token() {
Some(str.to_string())
} else {
None
}
}
pub fn get_xml(&self) -> String {
if let Some(token) = &self.token_data {
match token {
TokenData::TKeyword(keyword) => {
xml_helper("keyword", &keyword.get_xml())
},
TokenData::TSymbol(symbol) => {
xml_helper("symbol", &symbol)
},
TokenData::TIdentifier(id) => {
xml_helper("identifier", &id)
},
TokenData::TIntVal(n) => {
xml_helper("integerConstant", &n.to_string())
}
TokenData::TStringVal(string) => {
xml_helper("stringConstant", &string)
}
}
} else {
"".to_string()
}
}
fn set_token_data(&mut self) {
let token_data = TokenData::new(&self.tokens[self.idx]);
self.token_data = Some(token_data);
}
// flag check
pub fn is_class_var_dec(&self) -> bool {
self.get_token() == &Some(TokenData::TKeyword(Keyword::Static))
|| self.get_token() == &Some(TokenData::TKeyword(Keyword::Field))
}
pub fn is_class_static(&self) -> bool {
self.get_token() == &Some(TokenData::TKeyword(Keyword::Static))
}
pub fn is_class_field(&self) -> bool {
self.get_token() == &Some(TokenData::TKeyword(Keyword::Field))
}
pub fn is_subroutine_dec(&self) -> bool {
self.get_token() == &Some(TokenData::TKeyword(Keyword::Constructor))
|| self.get_token() == &Some(TokenData::TKeyword(Keyword::Function))
|| self.get_token() == &Some(TokenData::TKeyword(Keyword::Method))
}
pub fn is_constructor(&self) -> bool {
self.get_token() == &Some(TokenData::TKeyword(Keyword::Constructor))
}
pub fn is_function(&self) -> bool {
self.get_token() == &Some(TokenData::TKeyword(Keyword::Function))
}
pub fn is_method(&self) -> bool {
self.get_token() == &Some(TokenData::TKeyword(Keyword::Method))
}
pub fn is_statement(&self) -> bool {
self.get_token() == &Some(TokenData::TKeyword(Keyword::Let))
|| self.get_token() == &Some(TokenData::TKeyword(Keyword::Do))
|| self.get_token() == &Some(TokenData::TKeyword(Keyword::If))
|| self.get_token() == &Some(TokenData::TKeyword(Keyword::While))
|| self.get_token() == &Some(TokenData::TKeyword(Keyword::Return))
}
pub fn is_keyword_constant(&self) -> bool {
self.get_token() == &Some(TokenData::TKeyword(Keyword::True))
|| self.get_token() == &Some(TokenData::TKeyword(Keyword::False))
|| self.get_token() == &Some(TokenData::TKeyword(Keyword::Null))
|| self.get_token() == &Some(TokenData::TKeyword(Keyword::This))
}
pub fn is_integer_const(&self) -> bool {
if let &Some(TokenData::TIntVal(_)) = self.get_token() {
true
} else {
false
}
}
pub fn is_string_constant(&self) -> bool {
if let &Some(TokenData::TStringVal(_)) = self.get_token() {
true
} else {
false
}
}
pub fn is_var_dec(&self) -> bool {
self.get_token() == &Some(TokenData::TKeyword(Keyword::Var))
}
pub fn is_close_paren(&self) -> bool {
self.get_token() == &Some(TokenData::TSymbol(")".to_string()))
}
pub fn is_open_paren(&self) -> bool {
self.get_token() == &Some(TokenData::TSymbol("(".to_string()))
}
pub fn is_open_sq(&self) -> bool {
self.get_token() == &Some(TokenData::TSymbol("[".to_string()))
}
pub fn is_comma(&self) -> bool {
self.get_token() == &Some(TokenData::TSymbol(",".to_string()))
}
pub fn is_semicolon(&self) -> bool {
self.get_token() == &Some(TokenData::TSymbol(";".to_string()))
}
pub fn is_else(&self) -> bool {
self.get_token() == &Some(TokenData::TKeyword(Keyword::Else))
}
pub fn is_class_method(&self) -> bool {
let next_token = self.peek_token();
next_token == Some(TokenData::TSymbol(".".to_string()))
}
pub fn is_op(&self) -> bool {
if let &Some(TokenData::TSymbol(symbol)) = &self.get_token() {
symbol == "+"
|| symbol == "-"
|| symbol == "*"
|| symbol == "/"
|| symbol == "&"
|| symbol == "|"
|| symbol == "<"
|| symbol == ">"
|| symbol == "="
} else {
false
}
}
pub fn is_unary_op(&self) -> bool {
self.get_token() == &Some(TokenData::TSymbol("-".to_string()))
|| self.get_token() == &Some(TokenData::TSymbol("~".to_string()))
}
pub fn next_is_dot(&self) -> bool {
self.peek_token() == Some(TokenData::TSymbol(".".to_string()))
}
}
#[derive(Debug, PartialEq, Clone)]
pub enum TokenData {
TKeyword(Keyword),
TSymbol(String),
TIdentifier(String),
TIntVal(u16),
TStringVal(String),
// TNotToken,
}
impl TokenData {
fn new(str: &str) -> Self {
match str {
"class" => TokenData::TKeyword(Keyword::Class),
"method" => TokenData::TKeyword(Keyword::Method),
"function" => TokenData::TKeyword(Keyword::Function),
"constructor" => TokenData::TKeyword(Keyword::Constructor),
"int" => TokenData::TKeyword(Keyword::Int),
"boolean" => TokenData::TKeyword(Keyword::Boolean),
"char" => TokenData::TKeyword(Keyword::Char),
"void" => TokenData::TKeyword(Keyword::Void),
"var" => TokenData::TKeyword(Keyword::Var),
"static" => TokenData::TKeyword(Keyword::Static),
"field" => TokenData::TKeyword(Keyword::Field),
"let" => TokenData::TKeyword(Keyword::Let),
"do" => TokenData::TKeyword(Keyword::Do),
"if" => TokenData::TKeyword(Keyword::If),
"else" => TokenData::TKeyword(Keyword::Else),
"while" => TokenData::TKeyword(Keyword::While),
"return" => TokenData::TKeyword(Keyword::Return),
"true" => TokenData::TKeyword(Keyword::True),
"false" => TokenData::TKeyword(Keyword::False),
"null" => TokenData::TKeyword(Keyword::Null),
"this" => TokenData::TKeyword(Keyword::This),
// "/*STRING_CONST*/" => TokenData::TStringVal(str.to_string()),
str => {
if let Ok(n) = str.parse::<u16>() {
TokenData::TIntVal(n)
} else if str.len() == 1 {
let c = str.chars().into_iter().next().unwrap();
match c {
c if c.is_alphabetic() => TokenData::TIdentifier(c.to_string()),
'<' => TokenData::TSymbol("<".to_string()),
'>' => TokenData::TSymbol(">".to_string()),
'&' => TokenData::TSymbol("&".to_string()),
_ => TokenData::TSymbol(c.to_string()),
}
} else if str.contains("\"") {
let str = str[1..(str.len() - 1)].to_string();
TokenData::TStringVal(str)
} else {
TokenData::TIdentifier(str.to_string())
}
}
}
}
}
#[derive(Debug, PartialEq, Clone)]
pub enum Keyword {
Class,
Method,
Function,
Constructor,
Int,
Boolean,
Char,
Void,
Var,
Static,
Field,
Let,
Do,
If,
Else,
While,
Return,
True,
False,
Null,
This,
}
impl Keyword {
fn get_xml(&self) -> String {
let keyword = match self {
Keyword::Class => "class",
Keyword::Method => "method",
Keyword::Function => "function",
Keyword::Constructor => "constructor",
Keyword::Int => "int",
Keyword::Boolean => "boolean",
Keyword::Char => "char",
Keyword::Void => "void",
Keyword::Var => "var",
Keyword::Static => "static",
Keyword::Field => "field",
Keyword::Let => "let",
Keyword::Do => "do",
Keyword::If => "if",
Keyword::Else => "else",
Keyword::While => "while",
Keyword::Return => "return",
Keyword::True => "true",
Keyword::False => "false",
Keyword::Null => "null",
Keyword::This => "this",
};
keyword.to_string()
}
}
fn remove_comments(contents: String) -> String {
let re_comment_line = Regex::new(r"//.*\n").unwrap();
let re_comment_block = Regex::new(r"/\*[\s\S]*?\*/").unwrap();
let contents = re_comment_line.replace_all(&contents, "");
let contents = re_comment_block.replace_all(&contents, "");
contents.deref().to_string()
}
fn get_string_consts(contents: &str) -> (String, Vec<String>) {
let re_string_const = Regex::new(r#"".*""#).unwrap();
let string_const_matches = re_string_const.find_iter(&contents);
let string_consts: Vec<String> = string_const_matches.map(|m| {
m.as_str().replace("\"","").to_string()
}).collect();
let re_alphanumeric = Regex::new(r"(?P<symbol>[^ 0-9a-zA-Z_])").unwrap();
let contents = re_alphanumeric.replace_all(&contents, " $symbol ");
let contents = re_string_const.replace_all(&contents, " /*STRING_CONST*/ ");
(contents.to_string(), string_consts)
}
fn xml_helper(tag: &str, content: &str) -> String {
format!("<{}> {} </{}>", tag, content, tag)
}
|
extern crate proc_macro;
use {
codespan_reporting::{
files::SimpleFiles,
term::{self, termcolor::NoColor, Config},
},
proc_macro::TokenStream,
rewryte_generator::{Format, FormatType},
rewryte_parser::parser::{parse, Context},
std::{
fs,
io::{BufWriter, ErrorKind},
path::PathBuf,
},
syn::{
parse::{Parse, ParseStream},
punctuated::Punctuated,
token::Comma,
LitStr, Result, Token,
},
};
fn error(path: LitStr, msg: impl std::fmt::Display) -> TokenStream {
TokenStream::from(syn::Error::new_spanned(path, msg).to_compile_error())
}
#[proc_macro]
pub fn schema(input: TokenStream) -> TokenStream {
let input = match syn::parse::<FormatInput>(input) {
Ok(syntax_tree) => syntax_tree,
Err(err) => return TokenStream::from(err.to_compile_error()),
};
let contents = match fs::read_to_string(&input.path) {
Ok(file) => file,
Err(err) if err.kind() == ErrorKind::NotFound => {
return error(
input.lit_path,
format!("File does not exist: {}", input.path.display()),
);
}
Err(err) => {
return error(input.lit_path, err);
}
};
let contents_str = contents.as_str();
let mut files = SimpleFiles::new();
let file_id = files.add("<inline>", contents_str);
let mut ctx = Context::new(file_id);
match parse(&mut ctx, contents_str) {
Ok(schema) => {
let mut writer = BufWriter::new(Vec::new());
if let Err(err) = schema.fmt(&mut writer, input.format) {
return error(input.lit_path, err);
}
let inner = match writer.into_inner() {
Ok(vec) => vec,
Err(err) => {
return error(input.lit_path, err);
}
};
let rendered = match String::from_utf8(inner) {
Ok(string) => string,
Err(err) => {
return error(input.lit_path, err);
}
};
TokenStream::from(quote::quote! {
#rendered
})
}
Err(err) => {
let config = Config::default();
let mut writer = NoColor::new(Vec::new());
for diag in ctx.diagnostics() {
if let Err(err) = term::emit(&mut writer, &config, &files, diag) {
return error(input.lit_path, err);
}
}
let emit_string = match String::from_utf8(writer.into_inner()) {
Ok(string) => string,
Err(err) => {
return error(input.lit_path, err);
}
};
TokenStream::from(
syn::Error::new_spanned(input.lit_path, format!("{}\n\n{}", err, emit_string))
.to_compile_error(),
)
}
}
}
struct FormatInput {
format: FormatType,
lit_path: LitStr,
path: PathBuf,
}
impl Parse for FormatInput {
fn parse(input: ParseStream) -> Result<Self> {
let lit_format = <LitStr as Parse>::parse(input)?;
let format = match lit_format.value().as_str() {
"mysql" => FormatType::MySQL,
"postgresql" => FormatType::PostgreSQL,
"sqlite" => FormatType::SQLite,
"rust" => FormatType::Rust,
_ => {
return Err(syn::Error::new_spanned(
lit_format,
"Only the values `mysql`, `postgresql`, `sqlite`, and `rust` are allowed",
))
}
};
let _ = input.parse::<Token![,]>()?;
let lit_path = <LitStr as Parse>::parse(input)?;
let crate_root = std::env::var("CARGO_MANIFEST_DIR").unwrap();
let path = PathBuf::from(crate_root).join(lit_path.value());
Ok(FormatInput {
format,
lit_path,
path,
})
}
}
#[proc_macro]
pub fn models(input: TokenStream) -> TokenStream {
let input = match syn::parse::<ModelInput>(input) {
Ok(syntax_tree) => syntax_tree,
Err(err) => return TokenStream::from(err.to_compile_error()),
};
let contents = match fs::read_to_string(&input.path) {
Ok(file) => file,
Err(err) if err.kind() == ErrorKind::NotFound => {
return error(
input.lit_path,
format!("File does not exist: {}", input.path.display()),
);
}
Err(err) => {
return error(input.lit_path, err);
}
};
let contents_str = contents.as_str();
let mut files = SimpleFiles::new();
let file_id = files.add("<inline>", contents_str);
let mut ctx = Context::new(file_id);
match parse(&mut ctx, contents_str) {
Ok(schema) => {
let mut writer = BufWriter::new(Vec::new());
let mut options = rewryte_generator::rust::Options::default();
if let Some(extra) = input.extra {
let mut mapped = extra.iter().map(LitStr::value);
if mapped.by_ref().any(|value| &*value == "juniper") {
options.juniper = true;
}
if mapped.by_ref().any(|value| &*value == "serde") {
options.serde = true;
}
if mapped.by_ref().any(|value| &*value == "sqlx") {
options.sqlx = true;
}
}
if let Err(err) = rewryte_generator::rust::write_schema(&schema, &mut writer, options) {
return error(input.lit_path, err);
}
let inner = match writer.into_inner() {
Ok(vec) => vec,
Err(err) => {
return error(input.lit_path, err);
}
};
let rendered = match String::from_utf8(inner) {
Ok(string) => string,
Err(err) => {
return error(input.lit_path, err);
}
};
match rendered.parse() {
Ok(stream) => stream,
Err(err) => error(input.lit_path, err),
}
}
Err(err) => {
let config = Config::default();
let mut writer = NoColor::new(Vec::new());
for diag in ctx.diagnostics() {
if let Err(err) = term::emit(&mut writer, &config, &files, diag) {
return error(input.lit_path, err);
}
}
let emit_string = match String::from_utf8(writer.into_inner()) {
Ok(string) => string,
Err(err) => {
return error(input.lit_path, err);
}
};
error(input.lit_path, format!("{}\n\n{}", err, emit_string))
}
}
}
struct ModelInput {
lit_path: LitStr,
path: PathBuf,
extra: Option<Vec<LitStr>>,
}
impl Parse for ModelInput {
fn parse(input: ParseStream) -> Result<Self> {
let lit_path = <LitStr as Parse>::parse(input)?;
let crate_root = std::env::var("CARGO_MANIFEST_DIR").unwrap();
let path = PathBuf::from(crate_root).join(lit_path.value());
let extra = if input.peek(syn::token::Comma) {
let _comma = <Comma as Parse>::parse(input)?;
if input.peek(syn::token::Bracket) {
let content;
let _bracket = syn::bracketed!(content in input);
let parsed = Punctuated::<LitStr, Comma>::parse_terminated(&content)?;
let mut items = Vec::with_capacity(parsed.len());
for item in parsed {
items.push(item);
}
Some(items)
} else {
None
}
} else {
None
};
Ok(ModelInput {
lit_path,
path,
extra,
})
}
}
|
use crate::core;
use crate::core::{Error, Service, User, UserKey, UserToken};
use crate::driver;
// TODO(feature): Warning logs for bad requests.
/// User authentication using email address and password.
pub fn login(
driver: &driver::Driver,
service: &Service,
email: &str,
password: &str,
token_exp: i64,
) -> Result<UserToken, Error> {
let user = user_read_by_email(driver, Some(service), email)?;
core::check_password(user.password_hash.as_ref().map(|x| &**x), &password)?;
let key = core::key::read_by_user(driver, service, &user)?.ok_or_else(|| Error::BadRequest)?;
jwt::encode_user_token(service.id, user.id, &key.value, token_exp)
}
/// User reset password request.
pub fn reset_password(
driver: &driver::Driver,
service: &Service,
email: &str,
token_exp: i64,
) -> Result<(User, UserToken), Error> {
let user = user_read_by_email(driver, Some(service), email)?;
let password_revision = user.password_revision.ok_or_else(|| Error::BadRequest)?;
let key = core::key::read_by_user(driver, service, &user)?.ok_or_else(|| Error::BadRequest)?;
let reset_token = jwt::encode_reset_token(
service.id,
user.id,
password_revision,
&key.value,
token_exp,
)?;
Ok((user, reset_token))
}
/// User reset password confirm.
pub fn reset_password_confirm(
driver: &driver::Driver,
service: &Service,
token: &str,
password: &str,
) -> Result<usize, Error> {
// Unsafely decode token to get user identifier, used to read key for safe token decode.
let user_id = jwt::decode_unsafe(token, service.id)?;
let user =
core::user::read_by_id(driver, Some(service), user_id)?.ok_or_else(|| Error::BadRequest)?;
let user_password_revision = user.password_revision.ok_or_else(|| Error::BadRequest)?;
let key = core::key::read_by_user(driver, service, &user)?.ok_or_else(|| Error::BadRequest)?;
let password_revision = jwt::decode_reset_token(service.id, user.id, &key.value, token)?;
// If password revisions do not match, token has been used or password has been changed.
if password_revision != user_password_revision {
Err(Error::BadRequest)
} else {
core::user::update_password_by_id(
driver,
Some(service),
user.id,
password,
password_revision,
)
}
}
/// Verify user key.
pub fn key_verify(driver: &driver::Driver, service: &Service, key: &str) -> Result<UserKey, Error> {
let key =
core::key::read_by_user_value(driver, service, key)?.ok_or_else(|| Error::BadRequest)?;
let user_id = key.user_id.ok_or_else(|| Error::BadRequest)?;
Ok(UserKey {
user_id,
key: key.value,
})
}
/// Revoke user key.
pub fn key_revoke(driver: &driver::Driver, service: &Service, key: &str) -> Result<usize, Error> {
let key =
core::key::read_by_user_value(driver, service, key)?.ok_or_else(|| Error::BadRequest)?;
core::key::delete_by_id(driver, Some(service), key.id)
}
/// Verify user token.
pub fn token_verify(
driver: &driver::Driver,
service: &Service,
token: &str,
) -> Result<UserToken, Error> {
// Unsafely decode token to get user identifier, used to read key for safe token decode.
let user_id = jwt::decode_unsafe(token, service.id)?;
let user =
core::user::read_by_id(driver, Some(service), user_id)?.ok_or_else(|| Error::BadRequest)?;
let key = core::key::read_by_user(driver, service, &user)?.ok_or_else(|| Error::BadRequest)?;
jwt::decode_user_token(service.id, user.id, &key.value, token)
}
/// Refresh user token.
pub fn token_refresh(
driver: &driver::Driver,
service: &Service,
token: &str,
token_exp: i64,
) -> Result<UserToken, Error> {
// Unsafely decode token to get user identifier, used to read key for safe token decode.
let user_id = jwt::decode_unsafe(token, service.id)?;
let user =
core::user::read_by_id(driver, Some(service), user_id)?.ok_or_else(|| Error::BadRequest)?;
let key = core::key::read_by_user(driver, service, &user)?.ok_or_else(|| Error::BadRequest)?;
jwt::decode_user_token(service.id, user.id, &key.value, token)?;
jwt::encode_user_token(service.id, user.id, &key.value, token_exp)
}
/// Revoke user token.
pub fn token_revoke(
driver: &driver::Driver,
service: &Service,
token: &str,
) -> Result<usize, Error> {
// Unsafely decode token to get user identifier, used to read key for safe token decode.
let user_id = jwt::decode_unsafe(token, service.id)?;
let user =
core::user::read_by_id(driver, Some(service), user_id)?.ok_or_else(|| Error::BadRequest)?;
let key = core::key::read_by_user(driver, service, &user)?.ok_or_else(|| Error::BadRequest)?;
core::key::delete_by_id(driver, Some(service), key.id)
}
/// OAuth2 user login.
pub fn oauth2_login(
driver: &driver::Driver,
service_id: i64,
email: &str,
token_exp: i64,
) -> Result<(Service, UserToken), Error> {
let service = driver
.service_read_by_id(service_id)
.map_err(Error::Driver)?
.ok_or_else(|| Error::BadRequest)?;
let user = user_read_by_email(driver, Some(&service), email)?;
let key = core::key::read_by_user(driver, &service, &user)?.ok_or_else(|| Error::BadRequest)?;
let user_token = jwt::encode_user_token(service.id, user.id, &key.value, token_exp)?;
Ok((service, user_token))
}
/// Read user by email address.
/// Also checks user is active, returns bad request if inactive.
fn user_read_by_email(
driver: &driver::Driver,
service_mask: Option<&Service>,
email: &str,
) -> Result<User, Error> {
let user =
core::user::read_by_email(driver, service_mask, email)?.ok_or_else(|| Error::BadRequest)?;
if !user.active {
return Err(Error::BadRequest);
}
Ok(user)
}
mod jwt {
use crate::core::{Error, UserToken};
use jsonwebtoken::{dangerous_unsafe_decode, decode, encode, Header, Validation};
#[derive(Debug, Serialize, Deserialize)]
struct Claims {
iss: String,
sub: String,
exp: usize,
}
impl Claims {
pub fn new(iss: i64, sub: i64, exp: i64) -> Self {
let dt = chrono::Utc::now();
let exp = dt.timestamp() as usize + exp as usize;
Claims {
iss: iss.to_string(),
sub: sub.to_string(),
exp,
}
}
pub fn validation(iss: i64, sub: i64) -> Validation {
Validation {
iss: Some(iss.to_string()),
sub: Some(sub.to_string()),
..Validation::default()
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ResetClaims {
iss: String,
sub: String,
exp: usize,
password_revision: i64,
}
impl ResetClaims {
pub fn new(iss: i64, sub: i64, exp: i64, password_revision: i64) -> Self {
let dt = chrono::Utc::now();
let exp = dt.timestamp() as usize + exp as usize;
ResetClaims {
iss: iss.to_string(),
sub: sub.to_string(),
exp,
password_revision,
}
}
pub fn validation(iss: i64, sub: i64) -> Validation {
Validation {
iss: Some(iss.to_string()),
sub: Some(sub.to_string()),
..Validation::default()
}
}
}
pub fn encode_user_token(
service_id: i64,
user_id: i64,
key_value: &str,
exp: i64,
) -> Result<UserToken, Error> {
let claims = Claims::new(service_id, user_id, exp);
let token = encode(&Header::default(), &claims, key_value.as_bytes())
.map_err(Error::Jsonwebtoken)?;
Ok(UserToken {
user_id,
token,
token_expires: claims.exp,
})
}
/// Safely decodes a user token.
pub fn decode_user_token(
service_id: i64,
user_id: i64,
key_value: &str,
token: &str,
) -> Result<UserToken, Error> {
let validation = Claims::validation(service_id, user_id);
let data = decode::<Claims>(token, key_value.as_bytes(), &validation)
.map_err(Error::Jsonwebtoken)?;
Ok(UserToken {
user_id,
token: token.to_owned(),
token_expires: data.claims.exp,
})
}
pub fn encode_reset_token(
service_id: i64,
user_id: i64,
password_revision: i64,
key_value: &str,
exp: i64,
) -> Result<UserToken, Error> {
let claims = ResetClaims::new(service_id, user_id, exp, password_revision);
let token = encode(&Header::default(), &claims, key_value.as_bytes())
.map_err(Error::Jsonwebtoken)?;
Ok(UserToken {
user_id,
token,
token_expires: claims.exp,
})
}
/// Safely decodes a reset token and returns the password revision.
pub fn decode_reset_token(
service_id: i64,
user_id: i64,
key_value: &str,
token: &str,
) -> Result<i64, Error> {
let validation = ResetClaims::validation(service_id, user_id);
let data = decode::<ResetClaims>(token, key_value.as_bytes(), &validation)
.map_err(Error::Jsonwebtoken)?;
Ok(data.claims.password_revision)
}
/// Unsafely decodes a token, checks if service ID matches `iss` claim.
/// If matched, returns the `sub` claim, which may be a user ID.
/// The user ID must then be used safely decode the token to proceed.
pub fn decode_unsafe(token: &str, service_id: i64) -> Result<i64, Error> {
let claims: Claims = dangerous_unsafe_decode(token)
.map_err(Error::Jsonwebtoken)?
.claims;
let issuer = claims
.iss
.parse::<i64>()
.map_err(|_err| Error::BadRequest)?;
let subject = claims
.sub
.parse::<i64>()
.map_err(|_err| Error::BadRequest)?;
if service_id != issuer {
return Err(Error::BadRequest);
}
Ok(subject)
}
}
|
use crate::memory::phys_to_virt;
/// Mask all external interrupt except serial.
pub unsafe fn init_external_interrupt() {
// By default:
// riscv-pk (bbl) enables all S-Mode IRQs (ref: machine/minit.c)
// OpenSBI v0.3 disables all IRQs (ref: platform/common/irqchip/plic.c)
const HART0_S_MODE_INTERRUPT_ENABLES: *mut u32 = phys_to_virt(0x0C00_2080) as *mut u32;
const SERIAL: u32 = 0xa;
HART0_S_MODE_INTERRUPT_ENABLES.write_volatile(1 << SERIAL);
const SERIAL_PRIO: *mut u32 = phys_to_virt(0x0C000000 + (SERIAL as usize) * 4) as *mut u32;
SERIAL_PRIO.write_volatile(7); // QEMU: priority[irq] <- value & 0x7, hence the 7 here.
const HART0_S_MODE_PRIO_THRESH: *mut u32 = phys_to_virt(0x0C00_0000 + 0x20_1000) as *mut u32;
HART0_S_MODE_PRIO_THRESH.write_volatile(0); // Permits everything
}
pub unsafe fn enable_serial_interrupt() {
const UART16550: *mut u8 = phys_to_virt(0x10000000) as *mut u8;
UART16550.add(4).write_volatile(0x0B);
UART16550.add(1).write_volatile(0x01);
}
|
extern crate adventofcode;
use adventofcode::d4::Filter;
use std::io;
fn main() -> io::Result<()> {
println!("{}", (240_298..784_956).filter(|&n| Filter::validate_p1(n)).count());
println!("{}", (240_298..784_956).filter(|&n| Filter::validate_p2(n)).count());
Ok(())
}
|
use std::marker::PhantomData;
use esp_idf_bindgen::*;
#[derive(Debug)]
pub struct Heap {
_marker: PhantomData<()>,
}
impl Heap {
#[cfg(target_device = "esp32")]
pub fn total_size() -> usize {
unsafe { heap_caps_get_total_size(MALLOC_CAP_32BIT) as usize }
}
pub fn free_size() -> usize {
unsafe { heap_caps_get_free_size(MALLOC_CAP_32BIT) as usize }
}
}
|
use date_tuple::DateTuple;
use month_tuple::MonthTuple;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use time_tuple::TimeTuple;
const UNIX_EPOCH_START_YEAR: u16 = 1970;
const SECONDS_IN_A_YEAR: u64 = 31557600;
const SECONDS_IN_A_MONTH: u64 = 2629800;
const SECONDS_IN_A_DAY: u64 = 86400;
/// Takes a year as a u16 and returns whether it is a leap year.
pub fn is_leap_year(year: u16) -> bool {
(year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))
}
/// Gets the current date as a `DateTuple`
pub fn now_as_datetuple() -> DateTuple {
let mut seconds = duration_since_unix_epoch().as_secs();
let parts = extract_year_and_month_from_duration(seconds);
seconds = parts.2;
let days = seconds / SECONDS_IN_A_DAY + 1; //Days past plus current
DateTuple::new(parts.0, parts.1, days as u8).unwrap()
}
/// Gets the current month as a `MonthTuple`
pub fn now_as_monthtuple() -> MonthTuple {
let seconds = duration_since_unix_epoch().as_secs();
let parts = extract_year_and_month_from_duration(seconds);
MonthTuple::new(parts.0, parts.1).unwrap()
}
/// Gets the current time of day from `std::time::SystemTime` as a TimeTuple
pub fn now_as_timetuple() -> TimeTuple {
let seconds = duration_since_unix_epoch().as_secs();
TimeTuple::from_seconds(seconds)
}
/// Takes a duration in seconds and removes the year and month parts from it, returning
/// a tuple of the year, month, and remaining seconds.
///
/// Month is returned zero-based
fn extract_year_and_month_from_duration(mut seconds: u64) -> (u16, u8, u64) {
let years = seconds / SECONDS_IN_A_YEAR;
seconds -= years * SECONDS_IN_A_YEAR;
let months = seconds / SECONDS_IN_A_MONTH;
seconds -= months * SECONDS_IN_A_MONTH;
(years as u16 + UNIX_EPOCH_START_YEAR, months as u8, seconds)
}
/// Gets a duration using `std::time::SystemTime::now()` since the
/// unix epoch.
fn duration_since_unix_epoch() -> Duration {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_else(|_| Duration::new(0, 0))
}
#[cfg(test)]
mod tests {
#[test]
fn test_leap_years() {
let valid: [u16; 3] = [2000, 2012, 2016];
let invalid: [u16; 3] = [2100, 2018, 2013];
for v in valid.iter() {
assert!(super::is_leap_year(*v));
}
for i in invalid.iter() {
assert!(!super::is_leap_year(*i));
}
}
}
|
use crate::mock::{new_test_ext, Header, MockStorage, PosTable};
use crate::{
ChainConstants, DigestError, HashOf, HeaderExt, HeaderImporter, ImportError, NextDigestItems,
NumberOf, Storage, StorageBound,
};
use frame_support::{assert_err, assert_ok};
use futures::executor::block_on;
use rand::rngs::StdRng;
use rand::{Rng, SeedableRng};
use schnorrkel::Keypair;
use sp_consensus_slots::Slot;
use sp_consensus_subspace::digests::{
derive_next_global_randomness, derive_next_solution_range, extract_pre_digest,
extract_subspace_digest_items, CompatibleDigestItem, DeriveNextSolutionRangeParams,
ErrorDigestType, PreDigest,
};
use sp_consensus_subspace::{FarmerPublicKey, FarmerSignature};
use sp_runtime::app_crypto::UncheckedFrom;
use sp_runtime::testing::H256;
use sp_runtime::traits::Header as HeaderT;
use sp_runtime::{Digest, DigestItem};
use std::iter;
use std::num::{NonZeroU64, NonZeroUsize};
use subspace_archiving::archiver::{Archiver, NewArchivedSegment};
use subspace_core_primitives::crypto::kzg;
use subspace_core_primitives::crypto::kzg::Kzg;
use subspace_core_primitives::{
BlockWeight, HistorySize, PublicKey, Randomness, Record, RecordedHistorySegment,
SegmentCommitment, SegmentIndex, Solution, SolutionRange,
};
use subspace_erasure_coding::ErasureCoding;
use subspace_farmer_components::auditing::audit_sector;
use subspace_farmer_components::plotting::{plot_sector, PieceGetterRetryPolicy};
use subspace_farmer_components::sector::{sector_size, SectorMetadataChecksummed};
use subspace_farmer_components::FarmerProtocolInfo;
use subspace_proof_of_space::Table;
use subspace_solving::REWARD_SIGNING_CONTEXT;
use subspace_verification::{
calculate_block_weight, derive_randomness, verify_solution, VerifySolutionParams,
};
fn default_randomness() -> Randomness {
Randomness::from([1u8; 32])
}
fn default_test_constants() -> ChainConstants<Header> {
let global_randomness = default_randomness();
ChainConstants {
k_depth: 7,
genesis_digest_items: NextDigestItems {
next_global_randomness: global_randomness,
next_solution_range: Default::default(),
},
genesis_segment_commitments: Default::default(),
global_randomness_interval: 20,
era_duration: 20,
slot_probability: (1, 6),
storage_bound: Default::default(),
recent_segments: HistorySize::from(NonZeroU64::new(5).unwrap()),
recent_history_fraction: (
HistorySize::from(NonZeroU64::new(1).unwrap()),
HistorySize::from(NonZeroU64::new(10).unwrap()),
),
min_sector_lifetime: HistorySize::from(NonZeroU64::new(4).unwrap()),
}
}
fn archived_segment(kzg: Kzg) -> NewArchivedSegment {
// we don't care about the block data
let mut rng = StdRng::seed_from_u64(0);
let mut block = vec![0u8; RecordedHistorySegment::SIZE];
rng.fill(block.as_mut_slice());
let mut archiver = Archiver::new(kzg).unwrap();
archiver
.add_block(block, Default::default(), true)
.into_iter()
.next()
.unwrap()
}
struct FarmerParameters {
kzg: Kzg,
erasure_coding: ErasureCoding,
archived_segment: NewArchivedSegment,
farmer_protocol_info: FarmerProtocolInfo,
}
impl FarmerParameters {
fn new() -> Self {
let kzg = Kzg::new(kzg::embedded_kzg_settings());
let erasure_coding = ErasureCoding::new(
NonZeroUsize::new(Record::NUM_S_BUCKETS.next_power_of_two().ilog2() as usize).unwrap(),
)
.unwrap();
let archived_segment = archived_segment(kzg.clone());
let farmer_protocol_info = FarmerProtocolInfo {
history_size: HistorySize::from(SegmentIndex::ZERO),
max_pieces_in_sector: 1,
recent_segments: HistorySize::from(NonZeroU64::new(5).unwrap()),
recent_history_fraction: (
HistorySize::from(NonZeroU64::new(1).unwrap()),
HistorySize::from(NonZeroU64::new(10).unwrap()),
),
min_sector_lifetime: HistorySize::from(NonZeroU64::new(4).unwrap()),
};
Self {
kzg,
erasure_coding,
archived_segment,
farmer_protocol_info,
}
}
}
struct ValidHeaderParams<'a> {
parent_hash: HashOf<Header>,
number: NumberOf<Header>,
slot: u64,
keypair: &'a Keypair,
global_randomness: Randomness,
farmer_parameters: &'a FarmerParameters,
}
fn valid_header(
params: ValidHeaderParams<'_>,
) -> (
Header,
SolutionRange,
BlockWeight,
SegmentIndex,
SegmentCommitment,
) {
let ValidHeaderParams {
parent_hash,
number,
slot,
keypair,
global_randomness,
farmer_parameters,
} = params;
let segment_index = farmer_parameters
.archived_segment
.segment_header
.segment_index();
let segment_commitment = farmer_parameters
.archived_segment
.segment_header
.segment_commitment();
let public_key = PublicKey::from(keypair.public.to_bytes());
let pieces_in_sector = farmer_parameters.farmer_protocol_info.max_pieces_in_sector;
let sector_size = sector_size(pieces_in_sector);
let mut table_generator = PosTable::generator();
for sector_index in iter::from_fn(|| Some(rand::random())) {
let mut plotted_sector_bytes = vec![0; sector_size];
let mut plotted_sector_metadata_bytes = vec![0; SectorMetadataChecksummed::encoded_size()];
let plotted_sector = block_on(plot_sector::<_, PosTable>(
&public_key,
sector_index,
&farmer_parameters.archived_segment.pieces,
PieceGetterRetryPolicy::default(),
&farmer_parameters.farmer_protocol_info,
&farmer_parameters.kzg,
&farmer_parameters.erasure_coding,
pieces_in_sector,
&mut plotted_sector_bytes,
&mut plotted_sector_metadata_bytes,
&mut table_generator,
))
.unwrap();
let global_challenge = global_randomness.derive_global_challenge(slot);
let maybe_solution_candidates = audit_sector(
&public_key,
sector_index,
&global_challenge,
SolutionRange::MAX,
&plotted_sector_bytes,
&plotted_sector.sector_metadata,
);
let Some(solution_candidates) = maybe_solution_candidates else {
// Sector didn't have any solutions
continue;
};
let solution = solution_candidates
.into_iter::<_, PosTable>(
&public_key,
&farmer_parameters.kzg,
&farmer_parameters.erasure_coding,
&mut table_generator,
)
.unwrap()
.next()
.unwrap()
.unwrap();
let solution = Solution {
public_key: FarmerPublicKey::unchecked_from(keypair.public.to_bytes()),
reward_address: solution.reward_address,
sector_index: solution.sector_index,
history_size: solution.history_size,
piece_offset: solution.piece_offset,
record_commitment: solution.record_commitment,
record_witness: solution.record_witness,
chunk: solution.chunk,
chunk_witness: solution.chunk_witness,
audit_chunk_offset: solution.audit_chunk_offset,
proof_of_space: solution.proof_of_space,
};
let solution_distance = verify_solution::<PosTable, _, _>(
&solution,
slot,
&VerifySolutionParams {
global_randomness,
solution_range: SolutionRange::MAX,
piece_check_params: None,
},
&farmer_parameters.kzg,
)
.unwrap();
let solution_range = solution_distance * 2;
let block_weight = calculate_block_weight(solution_range);
let pre_digest = PreDigest {
slot: slot.into(),
solution,
#[cfg(feature = "pot")]
proof_of_time: Default::default(),
};
let digests = vec![
DigestItem::global_randomness(global_randomness),
DigestItem::solution_range(solution_range),
DigestItem::subspace_pre_digest(&pre_digest),
];
let header = Header {
parent_hash,
number,
state_root: Default::default(),
extrinsics_root: Default::default(),
digest: Digest { logs: digests },
};
return (
header,
solution_range,
block_weight,
segment_index,
segment_commitment,
);
}
unreachable!("Will find solution before exhausting u64")
}
fn seal_header(keypair: &Keypair, header: &mut Header) {
let ctx = schnorrkel::context::signing_context(REWARD_SIGNING_CONTEXT);
let pre_hash = header.hash();
let signature =
FarmerSignature::unchecked_from(keypair.sign(ctx.bytes(pre_hash.as_bytes())).to_bytes());
header
.digest
.logs
.push(DigestItem::subspace_seal(signature));
}
fn remove_seal(header: &mut Header) {
let digests = header.digest_mut();
digests.pop();
}
fn next_slot(slot_probability: (u64, u64), current_slot: Slot) -> Slot {
let mut rng = StdRng::seed_from_u64(current_slot.into());
current_slot + rng.gen_range(slot_probability.0..=slot_probability.1)
}
fn initialize_store(
constants: ChainConstants<Header>,
should_adjust_solution_range: bool,
maybe_root_plot_public_key: Option<FarmerPublicKey>,
) -> (MockStorage, HashOf<Header>) {
let mut store = MockStorage::new(constants);
let mut rng = StdRng::seed_from_u64(0);
let mut state_root = vec![0u8; 32];
rng.fill(state_root.as_mut_slice());
let genesis_header = Header {
parent_hash: Default::default(),
number: 0,
state_root: H256::from_slice(&state_root),
extrinsics_root: Default::default(),
digest: Default::default(),
};
let genesis_hash = genesis_header.hash();
let header = HeaderExt {
header: genesis_header,
total_weight: 0,
era_start_slot: Default::default(),
should_adjust_solution_range,
maybe_current_solution_range_override: None,
maybe_next_solution_range_override: None,
maybe_root_plot_public_key,
test_overrides: Default::default(),
};
store.store_header(header, true);
(store, genesis_hash)
}
fn add_next_digests(store: &MockStorage, number: NumberOf<Header>, header: &mut Header) {
let constants = store.chain_constants();
let parent_header = store.header(*header.parent_hash()).unwrap();
let digests =
extract_subspace_digest_items::<_, FarmerPublicKey, FarmerPublicKey, FarmerSignature>(
header,
)
.unwrap();
let digest_logs = header.digest_mut();
if let Some(next_randomness) = derive_next_global_randomness::<Header>(
number,
constants.global_randomness_interval,
&digests.pre_digest,
) {
digest_logs.push(DigestItem::next_global_randomness(next_randomness));
}
if let Some(next_solution_range) =
derive_next_solution_range::<Header>(DeriveNextSolutionRangeParams {
number,
era_duration: constants.era_duration,
slot_probability: constants.slot_probability,
current_slot: digests.pre_digest.slot,
current_solution_range: digests.solution_range,
era_start_slot: parent_header.era_start_slot,
should_adjust_solution_range: true,
maybe_next_solution_range_override: None,
})
.unwrap()
{
digest_logs.push(DigestItem::next_solution_range(next_solution_range));
}
}
struct ForkAt {
parent_hash: HashOf<Header>,
// if None, fork chain cumulative weight is equal to canonical chain weight
is_best: Option<bool>,
}
fn add_headers_to_chain(
importer: &mut HeaderImporter<Header, MockStorage>,
keypair: &Keypair,
headers_to_add: NumberOf<Header>,
maybe_fork_chain: Option<ForkAt>,
farmer_parameters: &FarmerParameters,
) -> HashOf<Header> {
let best_header_ext = importer.store.best_header();
let constants = importer.store.chain_constants();
let (parent_hash, number, slot) = if let Some(ForkAt { parent_hash, .. }) = maybe_fork_chain {
let header = importer.store.header(parent_hash).unwrap();
let digests = extract_pre_digest(&header.header).unwrap();
(parent_hash, *header.header.number(), digests.slot)
} else {
let digests = extract_pre_digest(&best_header_ext.header).unwrap();
(
best_header_ext.header.hash(),
*best_header_ext.header.number(),
digests.slot,
)
};
let until_number = number + headers_to_add;
let mut parent_hash = parent_hash;
let mut number = number + 1;
let mut slot = next_slot(constants.slot_probability, slot);
let mut best_header_hash = best_header_ext.header.hash();
while number <= until_number {
let (global_randomness, override_next_solution) = if number == 1 {
let randomness = default_randomness();
(randomness, false)
} else {
let header = importer.store.header(parent_hash).unwrap();
let digests = extract_subspace_digest_items::<
_,
FarmerPublicKey,
FarmerPublicKey,
FarmerSignature,
>(&header.header)
.unwrap();
let randomness = digests
.next_global_randomness
.unwrap_or(digests.global_randomness);
(randomness, digests.next_global_randomness.is_some())
};
let (mut header, solution_range, block_weight, segment_index, segment_commitment) =
valid_header(ValidHeaderParams {
parent_hash,
number,
slot: slot.into(),
keypair,
global_randomness,
farmer_parameters,
});
importer.store.override_cumulative_weight(parent_hash, 0);
if number == 1 {
// adjust Chain constants for Block #1
let mut constants = importer.store.chain_constants();
constants.genesis_digest_items.next_solution_range = solution_range;
importer.store.override_constants(constants)
} else if override_next_solution {
importer
.store
.override_next_solution_range(parent_hash, solution_range);
} else {
importer
.store
.override_solution_range(parent_hash, solution_range);
}
importer
.store
.store_segment_commitment(segment_index, segment_commitment);
if let Some(ForkAt {
is_best: maybe_best,
..
}) = maybe_fork_chain
{
if let Some(is_best) = maybe_best {
if is_best {
importer
.store
.override_cumulative_weight(best_header_hash, block_weight - 1)
} else {
importer
.store
.override_cumulative_weight(best_header_hash, block_weight + 1)
}
} else {
importer
.store
.override_cumulative_weight(best_header_hash, block_weight)
}
}
add_next_digests(&importer.store, number, &mut header);
seal_header(keypair, &mut header);
parent_hash = header.hash();
slot = next_slot(constants.slot_probability, slot);
number += 1;
assert_ok!(importer.import_header(header.clone()));
if let Some(ForkAt {
is_best: maybe_best,
..
}) = maybe_fork_chain
{
if let Some(is_best) = maybe_best {
if is_best {
best_header_hash = header.hash()
}
}
} else {
best_header_hash = header.hash()
}
assert_eq!(importer.store.best_header().header.hash(), best_header_hash);
}
parent_hash
}
fn ensure_finalized_heads_have_no_forks(store: &MockStorage, finalized_number: NumberOf<Header>) {
let finalized_header = store.finalized_header();
let (expected_finalized_number, hash) = (
finalized_header.header.number,
finalized_header.header.hash(),
);
assert_eq!(expected_finalized_number, finalized_number);
assert_eq!(store.headers_at_number(finalized_number).len(), 1);
if finalized_number < 1 {
return;
}
let header = store.header(hash).unwrap();
let mut parent_hash = header.header.parent_hash;
let mut finalized_number = finalized_number - 1;
while finalized_number > 0 {
assert_eq!(store.headers_at_number(finalized_number).len(), 1);
let hash = store.headers_at_number(finalized_number)[0].header.hash();
assert_eq!(parent_hash, hash);
parent_hash = store.header(hash).unwrap().header.parent_hash;
finalized_number -= 1;
}
}
#[test]
fn test_header_import_missing_parent() {
new_test_ext().execute_with(|| {
let keypair = Keypair::generate();
let farmer_parameters = FarmerParameters::new();
let constants = default_test_constants();
let (mut store, _genesis_hash) = initialize_store(constants, true, None);
let global_randomness = default_randomness();
let (header, _solution_range, _block_weight, segment_index, segment_commitment) =
valid_header(ValidHeaderParams {
parent_hash: Default::default(),
number: 1,
slot: 1,
keypair: &keypair,
global_randomness,
farmer_parameters: &farmer_parameters,
});
store.store_segment_commitment(segment_index, segment_commitment);
let mut importer = HeaderImporter::new(store);
assert_err!(
importer.import_header(header.clone()),
ImportError::MissingParent(header.hash())
);
});
}
#[test]
fn test_header_import_non_canonical() {
new_test_ext().execute_with(|| {
let keypair = Keypair::generate();
let farmer = FarmerParameters::new();
let constants = default_test_constants();
let (store, _genesis_hash) = initialize_store(constants, true, None);
let mut importer = HeaderImporter::new(store);
let hash_of_2 = add_headers_to_chain(&mut importer, &keypair, 2, None, &farmer);
let best_header = importer.store.best_header();
assert_eq!(best_header.header.hash(), hash_of_2);
// import canonical block 3
let hash_of_3 = add_headers_to_chain(&mut importer, &keypair, 1, None, &farmer);
let best_header = importer.store.best_header();
assert_eq!(best_header.header.hash(), hash_of_3);
let best_header = importer.store.header(hash_of_3).unwrap();
assert_eq!(importer.store.headers_at_number(3).len(), 1);
// import non canonical block 3
add_headers_to_chain(
&mut importer,
&keypair,
1,
Some(ForkAt {
parent_hash: hash_of_2,
is_best: Some(false),
}),
&farmer,
);
let best_header_ext = importer.store.best_header();
assert_eq!(best_header_ext.header, best_header.header);
// we still track the forks
assert_eq!(importer.store.headers_at_number(3).len(), 2);
});
}
#[test]
fn test_header_import_canonical() {
new_test_ext().execute_with(|| {
let keypair = Keypair::generate();
let farmer = FarmerParameters::new();
let constants = default_test_constants();
let (store, _genesis_hash) = initialize_store(constants, true, None);
let mut importer = HeaderImporter::new(store);
let hash_of_5 = add_headers_to_chain(&mut importer, &keypair, 5, None, &farmer);
let best_header = importer.store.best_header();
assert_eq!(best_header.header.hash(), hash_of_5);
// import some more canonical blocks
let hash_of_25 = add_headers_to_chain(&mut importer, &keypair, 20, None, &farmer);
let best_header = importer.store.best_header();
assert_eq!(best_header.header.hash(), hash_of_25);
assert_eq!(importer.store.headers_at_number(25).len(), 1);
});
}
#[test]
fn test_header_import_non_canonical_with_equal_block_weight() {
new_test_ext().execute_with(|| {
let keypair = Keypair::generate();
let farmer = FarmerParameters::new();
let constants = default_test_constants();
let (store, _genesis_hash) = initialize_store(constants, true, None);
let mut importer = HeaderImporter::new(store);
let hash_of_2 = add_headers_to_chain(&mut importer, &keypair, 2, None, &farmer);
let best_header = importer.store.best_header();
assert_eq!(best_header.header.hash(), hash_of_2);
// import canonical block 3
let hash_of_3 = add_headers_to_chain(&mut importer, &keypair, 1, None, &farmer);
let best_header = importer.store.best_header();
assert_eq!(best_header.header.hash(), hash_of_3);
let best_header = importer.store.header(hash_of_3).unwrap();
assert_eq!(importer.store.headers_at_number(3).len(), 1);
// import non canonical block 3
add_headers_to_chain(
&mut importer,
&keypair,
1,
Some(ForkAt {
parent_hash: hash_of_2,
is_best: None,
}),
&farmer,
);
let best_header_ext = importer.store.best_header();
assert_eq!(best_header_ext.header, best_header.header);
// we still track the forks
assert_eq!(importer.store.headers_at_number(3).len(), 2);
});
}
// TODO: This test doesn't actually reorg, but probably should
#[test]
fn test_chain_reorg_to_heavier_chain() {
new_test_ext().execute_with(|| {
let keypair = Keypair::generate();
let farmer = FarmerParameters::new();
let mut constants = default_test_constants();
constants.k_depth = 4;
let (store, genesis_hash) = initialize_store(constants, true, None);
let mut importer = HeaderImporter::new(store);
assert_eq!(
importer.store.finalized_header().header.hash(),
genesis_hash
);
let hash_of_4 = add_headers_to_chain(&mut importer, &keypair, 4, None, &farmer);
let best_header = importer.store.best_header();
assert_eq!(best_header.header.hash(), hash_of_4);
assert_eq!(
importer.store.finalized_header().header.hash(),
genesis_hash
);
// create a fork chain of 4 headers from number 1
add_headers_to_chain(
&mut importer,
&keypair,
4,
Some(ForkAt {
parent_hash: genesis_hash,
is_best: Some(false),
}),
&farmer,
);
assert_eq!(best_header.header.hash(), hash_of_4);
// block 0 is still finalized
assert_eq!(
importer.store.finalized_header().header.hash(),
genesis_hash
);
ensure_finalized_heads_have_no_forks(&importer.store, 0);
// add new best header at 5
let hash_of_5 = add_headers_to_chain(&mut importer, &keypair, 1, None, &farmer);
let best_header = importer.store.best_header();
assert_eq!(best_header.header.hash(), hash_of_5);
// block 1 should be finalized
assert_eq!(importer.store.finalized_header().header.number, 1);
ensure_finalized_heads_have_no_forks(&importer.store, 1);
// create a fork chain from number 5 with block until 8
let fork_hash_of_8 = add_headers_to_chain(
&mut importer,
&keypair,
4,
Some(ForkAt {
parent_hash: hash_of_4,
is_best: Some(false),
}),
&farmer,
);
// best header should still be the same
assert_eq!(best_header.header, importer.store.best_header().header);
// there must be 2 heads at 5
assert_eq!(importer.store.headers_at_number(5).len(), 2);
// block 1 should be finalized
assert_eq!(importer.store.finalized_header().header.number, 1);
ensure_finalized_heads_have_no_forks(&importer.store, 1);
// import a new head to the fork chain and make it the best.
let hash_of_9 = add_headers_to_chain(
&mut importer,
&keypair,
1,
Some(ForkAt {
parent_hash: fork_hash_of_8,
is_best: Some(true),
}),
&farmer,
);
assert_eq!(importer.store.best_header().header.hash(), hash_of_9);
// now the finalized header must be 5
ensure_finalized_heads_have_no_forks(&importer.store, 5);
});
}
#[test]
fn test_reorg_to_heavier_smaller_chain() {
new_test_ext().execute_with(|| {
let keypair = Keypair::generate();
let farmer_parameters = FarmerParameters::new();
let mut constants = default_test_constants();
constants.k_depth = 4;
let (store, genesis_hash) = initialize_store(constants, true, None);
let mut importer = HeaderImporter::new(store);
assert_eq!(
importer.store.finalized_header().header.hash(),
genesis_hash
);
let hash_of_5 = add_headers_to_chain(&mut importer, &keypair, 5, None, &farmer_parameters);
let best_header = importer.store.best_header();
assert_eq!(best_header.header.hash(), hash_of_5);
assert_eq!(importer.store.finalized_header().header.number, 1);
// header count at the finalized head must be 1
ensure_finalized_heads_have_no_forks(&importer.store, 1);
// now import a fork header 3 that becomes canonical
let constants = importer.store.chain_constants();
let header_at_2 = importer
.store
.headers_at_number(2)
.first()
.cloned()
.unwrap();
let digests_at_2 =
extract_subspace_digest_items::<_, FarmerPublicKey, FarmerPublicKey, FarmerSignature>(
&header_at_2.header,
)
.unwrap();
let (mut header, solution_range, block_weight, segment_index, segment_commitment) =
valid_header(ValidHeaderParams {
parent_hash: header_at_2.header.hash(),
number: 3,
slot: next_slot(constants.slot_probability, digests_at_2.pre_digest.slot).into(),
keypair: &keypair,
global_randomness: digests_at_2.global_randomness,
farmer_parameters: &farmer_parameters,
});
seal_header(&keypair, &mut header);
importer
.store
.override_solution_range(header_at_2.header.hash(), solution_range);
importer
.store
.store_segment_commitment(segment_index, segment_commitment);
importer.store.override_cumulative_weight(
importer.store.best_header().header.hash(),
block_weight - 1,
);
// override parent weight to 0
importer
.store
.override_cumulative_weight(header_at_2.header.hash(), 0);
let res = importer.import_header(header);
assert_err!(res, ImportError::SwitchedToForkBelowArchivingDepth);
});
}
#[test]
fn test_next_global_randomness_digest() {
new_test_ext().execute_with(|| {
let keypair = Keypair::generate();
let farmer_parameters = FarmerParameters::new();
let mut constants = default_test_constants();
constants.global_randomness_interval = 5;
let (store, genesis_hash) = initialize_store(constants, true, None);
let mut importer = HeaderImporter::new(store);
assert_eq!(
importer.store.finalized_header().header.hash(),
genesis_hash
);
let hash_of_4 = add_headers_to_chain(&mut importer, &keypair, 4, None, &farmer_parameters);
assert_eq!(importer.store.best_header().header.hash(), hash_of_4);
// try to import header with out next global randomness
let constants = importer.store.chain_constants();
let header_at_4 = importer.store.header(hash_of_4).unwrap();
let digests_at_4 =
extract_subspace_digest_items::<_, FarmerPublicKey, FarmerPublicKey, FarmerSignature>(
&header_at_4.header,
)
.unwrap();
let (mut header, solution_range, _block_weight, segment_index, segment_commitment) =
valid_header(ValidHeaderParams {
parent_hash: header_at_4.header.hash(),
number: 5,
slot: next_slot(constants.slot_probability, digests_at_4.pre_digest.slot).into(),
keypair: &keypair,
global_randomness: digests_at_4.global_randomness,
farmer_parameters: &farmer_parameters,
});
seal_header(&keypair, &mut header);
importer
.store
.override_solution_range(header_at_4.header.hash(), solution_range);
importer
.store
.store_segment_commitment(segment_index, segment_commitment);
importer
.store
.override_cumulative_weight(header_at_4.header.hash(), 0);
let res = importer.import_header(header.clone());
assert_err!(
res,
ImportError::DigestError(DigestError::NextDigestVerificationError(
ErrorDigestType::NextGlobalRandomness
))
);
assert_eq!(importer.store.best_header().header.hash(), hash_of_4);
// add next global randomness
remove_seal(&mut header);
let pre_digest = extract_pre_digest(&header).unwrap();
let randomness = derive_randomness(&pre_digest.solution, pre_digest.slot.into());
let digests = header.digest_mut();
digests.push(DigestItem::next_global_randomness(randomness));
seal_header(&keypair, &mut header);
let res = importer.import_header(header.clone());
assert_ok!(res);
assert_eq!(importer.store.best_header().header.hash(), header.hash());
});
}
#[test]
fn test_next_solution_range_digest_with_adjustment_enabled() {
new_test_ext().execute_with(|| {
let keypair = Keypair::generate();
let farmer_parameters = FarmerParameters::new();
let mut constants = default_test_constants();
constants.era_duration = 5;
let (store, genesis_hash) = initialize_store(constants, true, None);
let mut importer = HeaderImporter::new(store);
assert_eq!(
importer.store.finalized_header().header.hash(),
genesis_hash
);
let hash_of_4 = add_headers_to_chain(&mut importer, &keypair, 4, None, &farmer_parameters);
assert_eq!(importer.store.best_header().header.hash(), hash_of_4);
// try to import header with out next global randomness
let constants = importer.store.chain_constants();
let header_at_4 = importer.store.header(hash_of_4).unwrap();
let digests_at_4 =
extract_subspace_digest_items::<_, FarmerPublicKey, FarmerPublicKey, FarmerSignature>(
&header_at_4.header,
)
.unwrap();
let (mut header, solution_range, _block_weight, segment_index, segment_commitment) =
valid_header(ValidHeaderParams {
parent_hash: header_at_4.header.hash(),
number: 5,
slot: next_slot(constants.slot_probability, digests_at_4.pre_digest.slot).into(),
keypair: &keypair,
global_randomness: digests_at_4.global_randomness,
farmer_parameters: &farmer_parameters,
});
seal_header(&keypair, &mut header);
importer
.store
.override_solution_range(header_at_4.header.hash(), solution_range);
importer
.store
.store_segment_commitment(segment_index, segment_commitment);
importer
.store
.override_cumulative_weight(header_at_4.header.hash(), 0);
let pre_digest = extract_pre_digest(&header).unwrap();
let res = importer.import_header(header.clone());
assert_err!(
res,
ImportError::DigestError(DigestError::NextDigestVerificationError(
ErrorDigestType::NextSolutionRange
))
);
assert_eq!(importer.store.best_header().header.hash(), hash_of_4);
// add next solution range
remove_seal(&mut header);
let next_solution_range = subspace_verification::derive_next_solution_range(
u64::from(header_at_4.era_start_slot),
u64::from(pre_digest.slot),
constants.slot_probability,
solution_range,
constants.era_duration,
);
let digests = header.digest_mut();
digests.push(DigestItem::next_solution_range(next_solution_range));
seal_header(&keypair, &mut header);
let res = importer.import_header(header.clone());
assert_ok!(res);
assert_eq!(importer.store.best_header().header.hash(), header.hash());
});
}
#[test]
fn test_next_solution_range_digest_with_adjustment_disabled() {
new_test_ext().execute_with(|| {
let keypair = Keypair::generate();
let farmer_parameters = FarmerParameters::new();
let mut constants = default_test_constants();
constants.era_duration = 5;
let (store, genesis_hash) = initialize_store(constants, false, None);
let mut importer = HeaderImporter::new(store);
assert_eq!(
importer.store.finalized_header().header.hash(),
genesis_hash
);
let hash_of_4 = add_headers_to_chain(&mut importer, &keypair, 4, None, &farmer_parameters);
assert_eq!(importer.store.best_header().header.hash(), hash_of_4);
// try to import header with out next global randomness
let constants = importer.store.chain_constants();
let header_at_4 = importer.store.header(hash_of_4).unwrap();
let digests_at_4 =
extract_subspace_digest_items::<_, FarmerPublicKey, FarmerPublicKey, FarmerSignature>(
&header_at_4.header,
)
.unwrap();
let (mut header, solution_range, _block_weight, segment_index, segment_commitment) =
valid_header(ValidHeaderParams {
parent_hash: header_at_4.header.hash(),
number: 5,
slot: next_slot(constants.slot_probability, digests_at_4.pre_digest.slot).into(),
keypair: &keypair,
global_randomness: digests_at_4.global_randomness,
farmer_parameters: &farmer_parameters,
});
importer
.store
.override_solution_range(header_at_4.header.hash(), solution_range);
importer
.store
.store_segment_commitment(segment_index, segment_commitment);
importer
.store
.override_cumulative_weight(header_at_4.header.hash(), 0);
// since solution range adjustment is disabled
// current solution range is used as next
let next_solution_range = solution_range;
let digests = header.digest_mut();
digests.push(DigestItem::next_solution_range(next_solution_range));
seal_header(&keypair, &mut header);
let res = importer.import_header(header.clone());
assert_ok!(res);
assert_eq!(importer.store.best_header().header.hash(), header.hash());
assert!(!importer.store.best_header().should_adjust_solution_range);
});
}
#[test]
fn test_enable_solution_range_adjustment_without_override() {
new_test_ext().execute_with(|| {
let keypair = Keypair::generate();
let farmer_parameters = FarmerParameters::new();
let mut constants = default_test_constants();
constants.era_duration = 5;
let (store, genesis_hash) = initialize_store(constants, false, None);
let mut importer = HeaderImporter::new(store);
assert_eq!(
importer.store.finalized_header().header.hash(),
genesis_hash
);
let hash_of_4 = add_headers_to_chain(&mut importer, &keypair, 4, None, &farmer_parameters);
assert_eq!(importer.store.best_header().header.hash(), hash_of_4);
// solution range adjustment is disabled
assert!(!importer.store.best_header().should_adjust_solution_range);
// enable solution range adjustment in this header
let constants = importer.store.chain_constants();
let header_at_4 = importer.store.header(hash_of_4).unwrap();
let digests_at_4 =
extract_subspace_digest_items::<_, FarmerPublicKey, FarmerPublicKey, FarmerSignature>(
&header_at_4.header,
)
.unwrap();
let (mut header, solution_range, _block_weight, segment_index, segment_commitment) =
valid_header(ValidHeaderParams {
parent_hash: header_at_4.header.hash(),
number: 5,
slot: next_slot(constants.slot_probability, digests_at_4.pre_digest.slot).into(),
keypair: &keypair,
global_randomness: digests_at_4.global_randomness,
farmer_parameters: &farmer_parameters,
});
importer
.store
.override_solution_range(header_at_4.header.hash(), solution_range);
importer
.store
.store_segment_commitment(segment_index, segment_commitment);
importer
.store
.override_cumulative_weight(header_at_4.header.hash(), 0);
let pre_digest = extract_pre_digest(&header).unwrap();
let next_solution_range = subspace_verification::derive_next_solution_range(
u64::from(header_at_4.era_start_slot),
u64::from(pre_digest.slot),
constants.slot_probability,
solution_range,
constants.era_duration,
);
let digests = header.digest_mut();
digests.push(DigestItem::next_solution_range(next_solution_range));
digests.push(DigestItem::enable_solution_range_adjustment_and_override(
None,
));
seal_header(&keypair, &mut header);
let res = importer.import_header(header.clone());
assert_ok!(res);
assert_eq!(importer.store.best_header().header.hash(), header.hash());
assert!(importer.store.best_header().should_adjust_solution_range);
assert_eq!(header_at_4.maybe_current_solution_range_override, None);
assert_eq!(header_at_4.maybe_next_solution_range_override, None);
});
}
#[test]
fn test_enable_solution_range_adjustment_with_override_between_update_intervals() {
new_test_ext().execute_with(|| {
let keypair = Keypair::generate();
let farmer_parameters = FarmerParameters::new();
let mut constants = default_test_constants();
constants.era_duration = 5;
let (store, genesis_hash) = initialize_store(constants, false, None);
let mut importer = HeaderImporter::new(store);
assert_eq!(
importer.store.finalized_header().header.hash(),
genesis_hash
);
let hash_of_3 = add_headers_to_chain(&mut importer, &keypair, 3, None, &farmer_parameters);
assert_eq!(importer.store.best_header().header.hash(), hash_of_3);
// solution range adjustment is disabled
assert!(!importer.store.best_header().should_adjust_solution_range);
// enable solution range adjustment with override in this header
let constants = importer.store.chain_constants();
let header_at_3 = importer.store.header(hash_of_3).unwrap();
let digests_at_3 =
extract_subspace_digest_items::<_, FarmerPublicKey, FarmerPublicKey, FarmerSignature>(
&header_at_3.header,
)
.unwrap();
let (mut header, solution_range, _block_weight, segment_index, segment_commitment) =
valid_header(ValidHeaderParams {
parent_hash: header_at_3.header.hash(),
number: 4,
slot: next_slot(constants.slot_probability, digests_at_3.pre_digest.slot).into(),
keypair: &keypair,
global_randomness: digests_at_3.global_randomness,
farmer_parameters: &farmer_parameters,
});
importer
.store
.override_solution_range(header_at_3.header.hash(), solution_range);
importer
.store
.store_segment_commitment(segment_index, segment_commitment);
importer
.store
.override_cumulative_weight(header_at_3.header.hash(), 0);
let digests = header.digest_mut();
let solution_range_override = 100;
digests.push(DigestItem::enable_solution_range_adjustment_and_override(
Some(solution_range_override),
));
seal_header(&keypair, &mut header);
let res = importer.import_header(header.clone());
assert_ok!(res);
let header_at_4 = importer.store.best_header();
assert_eq!(header_at_4.header.hash(), header.hash());
assert!(header_at_4.should_adjust_solution_range);
// current solution range override and next solution range overrides are updated
assert_eq!(
header_at_4.maybe_current_solution_range_override,
Some(solution_range_override)
);
assert_eq!(
header_at_4.maybe_next_solution_range_override,
Some(solution_range_override)
);
});
}
#[test]
fn test_enable_solution_range_adjustment_with_override_at_interval_change() {
new_test_ext().execute_with(|| {
let keypair = Keypair::generate();
let farmer_parameters = FarmerParameters::new();
let mut constants = default_test_constants();
constants.era_duration = 5;
let (store, genesis_hash) = initialize_store(constants, false, None);
let mut importer = HeaderImporter::new(store);
assert_eq!(
importer.store.finalized_header().header.hash(),
genesis_hash
);
let hash_of_4 = add_headers_to_chain(&mut importer, &keypair, 4, None, &farmer_parameters);
assert_eq!(importer.store.best_header().header.hash(), hash_of_4);
// solution range adjustment is disabled
assert!(!importer.store.best_header().should_adjust_solution_range);
// enable solution range adjustment in this header
let constants = importer.store.chain_constants();
let header_at_4 = importer.store.header(hash_of_4).unwrap();
let digests_at_4 =
extract_subspace_digest_items::<_, FarmerPublicKey, FarmerPublicKey, FarmerSignature>(
&header_at_4.header,
)
.unwrap();
let (mut header, solution_range, _block_weight, segment_index, segment_commitment) =
valid_header(ValidHeaderParams {
parent_hash: header_at_4.header.hash(),
number: 5,
slot: next_slot(constants.slot_probability, digests_at_4.pre_digest.slot).into(),
keypair: &keypair,
global_randomness: digests_at_4.global_randomness,
farmer_parameters: &farmer_parameters,
});
importer
.store
.override_solution_range(header_at_4.header.hash(), solution_range);
importer
.store
.store_segment_commitment(segment_index, segment_commitment);
importer
.store
.override_cumulative_weight(header_at_4.header.hash(), 0);
let solution_range_override = 100;
let next_solution_range = solution_range_override;
let digests = header.digest_mut();
digests.push(DigestItem::next_solution_range(next_solution_range));
digests.push(DigestItem::enable_solution_range_adjustment_and_override(
Some(solution_range_override),
));
seal_header(&keypair, &mut header);
let res = importer.import_header(header.clone());
assert_ok!(res);
assert_eq!(importer.store.best_header().header.hash(), header.hash());
assert!(importer.store.best_header().should_adjust_solution_range);
assert_eq!(header_at_4.maybe_current_solution_range_override, None);
assert_eq!(header_at_4.maybe_next_solution_range_override, None);
});
}
#[test]
fn test_disallow_enable_solution_range_digest_when_solution_range_adjustment_is_already_enabled() {
new_test_ext().execute_with(|| {
let keypair = Keypair::generate();
let farmer_parameters = FarmerParameters::new();
let mut constants = default_test_constants();
constants.era_duration = 5;
let (store, genesis_hash) = initialize_store(constants, true, None);
let mut importer = HeaderImporter::new(store);
assert_eq!(
importer.store.finalized_header().header.hash(),
genesis_hash
);
let hash_of_4 = add_headers_to_chain(&mut importer, &keypair, 4, None, &farmer_parameters);
assert_eq!(importer.store.best_header().header.hash(), hash_of_4);
// try to import header with enable solution range adjustment digest
let constants = importer.store.chain_constants();
let header_at_4 = importer.store.header(hash_of_4).unwrap();
let digests_at_4 =
extract_subspace_digest_items::<_, FarmerPublicKey, FarmerPublicKey, FarmerSignature>(
&header_at_4.header,
)
.unwrap();
let (mut header, solution_range, _block_weight, segment_index, segment_commitment) =
valid_header(ValidHeaderParams {
parent_hash: header_at_4.header.hash(),
number: 5,
slot: next_slot(constants.slot_probability, digests_at_4.pre_digest.slot).into(),
keypair: &keypair,
global_randomness: digests_at_4.global_randomness,
farmer_parameters: &farmer_parameters,
});
importer
.store
.override_solution_range(header_at_4.header.hash(), solution_range);
importer
.store
.store_segment_commitment(segment_index, segment_commitment);
importer
.store
.override_cumulative_weight(header_at_4.header.hash(), 0);
let digests = header.digest_mut();
digests.push(DigestItem::enable_solution_range_adjustment_and_override(
None,
));
seal_header(&keypair, &mut header);
let res = importer.import_header(header.clone());
assert_err!(
res,
ImportError::DigestError(DigestError::NextDigestVerificationError(
ErrorDigestType::EnableSolutionRangeAdjustmentAndOverride
))
);
});
}
fn ensure_store_is_storage_bounded(headers_to_keep_beyond_k_depth: NumberOf<Header>) {
new_test_ext().execute_with(|| {
let keypair = Keypair::generate();
let farmer = FarmerParameters::new();
let mut constants = default_test_constants();
constants.k_depth = 7;
constants.storage_bound =
StorageBound::NumberOfHeaderToKeepBeyondKDepth(headers_to_keep_beyond_k_depth);
let (store, _genesis_hash) = initialize_store(constants, true, None);
let mut importer = HeaderImporter::new(store);
// import some more canonical blocks
let hash_of_50 = add_headers_to_chain(&mut importer, &keypair, 50, None, &farmer);
let best_header = importer.store.best_header();
assert_eq!(best_header.header.hash(), hash_of_50);
// check storage bound
let finalized_head = importer.store.finalized_header();
assert_eq!(finalized_head.header.number, 43);
// there should be headers at and below (finalized_head - bound - 1)
let mut pruned_number = 43 - headers_to_keep_beyond_k_depth - 1;
while pruned_number != 0 {
assert!(importer.store.headers_at_number(pruned_number).is_empty());
pruned_number -= 1;
}
assert!(importer.store.headers_at_number(0).is_empty());
});
}
#[test]
fn test_storage_bound_with_headers_beyond_k_depth_is_zero() {
ensure_store_is_storage_bounded(0)
}
#[test]
fn test_storage_bound_with_headers_beyond_k_depth_is_one() {
ensure_store_is_storage_bounded(1)
}
#[test]
fn test_storage_bound_with_headers_beyond_k_depth_is_more_than_one() {
ensure_store_is_storage_bounded(5)
}
#[test]
fn test_block_author_different_farmer() {
new_test_ext().execute_with(|| {
let farmer_parameters = FarmerParameters::new();
let mut constants = default_test_constants();
let keypair_allowed = Keypair::generate();
let pub_key = FarmerPublicKey::unchecked_from(keypair_allowed.public.to_bytes());
let (store, genesis_hash) = initialize_store(constants.clone(), true, Some(pub_key));
let mut importer = HeaderImporter::new(store);
// try to import header authored by different farmer
let keypair_disallowed = Keypair::generate();
let global_randomness = default_randomness();
let (mut header, solution_range, _block_weight, segment_index, segment_commitment) =
valid_header(ValidHeaderParams {
parent_hash: genesis_hash,
number: 1,
slot: 1,
keypair: &keypair_disallowed,
global_randomness,
farmer_parameters: &farmer_parameters,
});
seal_header(&keypair_disallowed, &mut header);
constants.genesis_digest_items.next_solution_range = solution_range;
importer.store.override_constants(constants);
importer
.store
.store_segment_commitment(segment_index, segment_commitment);
importer.store.override_cumulative_weight(genesis_hash, 0);
let res = importer.import_header(header);
assert_err!(
res,
ImportError::IncorrectBlockAuthor(FarmerPublicKey::unchecked_from(
keypair_disallowed.public.to_bytes()
))
);
});
}
#[test]
fn test_block_author_first_farmer() {
new_test_ext().execute_with(|| {
let keypair = Keypair::generate();
let farmer_parameters = FarmerParameters::new();
let mut constants = default_test_constants();
let pub_key = FarmerPublicKey::unchecked_from(keypair.public.to_bytes());
let (store, genesis_hash) = initialize_store(constants.clone(), true, None);
let mut importer = HeaderImporter::new(store);
// try import header with first farmer
let global_randomness = default_randomness();
let (mut header, solution_range, _block_weight, segment_index, segment_commitment) =
valid_header(ValidHeaderParams {
parent_hash: genesis_hash,
number: 1,
slot: 1,
keypair: &keypair,
global_randomness,
farmer_parameters: &farmer_parameters,
});
header
.digest
.logs
.push(DigestItem::root_plot_public_key_update(Some(
pub_key.clone(),
)));
seal_header(&keypair, &mut header);
constants.genesis_digest_items.next_solution_range = solution_range;
importer.store.override_constants(constants);
importer
.store
.store_segment_commitment(segment_index, segment_commitment);
importer.store.override_cumulative_weight(genesis_hash, 0);
let res = importer.import_header(header.clone());
assert_ok!(res);
let best_header = importer.store.best_header();
assert_eq!(header.hash(), best_header.header.hash());
assert_eq!(best_header.maybe_root_plot_public_key, Some(pub_key));
});
}
#[test]
fn test_block_author_allow_any_farmer() {
new_test_ext().execute_with(|| {
let keypair = Keypair::generate();
let farmer_parameters = FarmerParameters::new();
let mut constants = default_test_constants();
let pub_key = FarmerPublicKey::unchecked_from(keypair.public.to_bytes());
let (store, genesis_hash) = initialize_store(constants.clone(), true, Some(pub_key));
let mut importer = HeaderImporter::new(store);
// try to import header authored by different farmer
let global_randomness = default_randomness();
let (mut header, solution_range, _block_weight, segment_index, segment_commitment) =
valid_header(ValidHeaderParams {
parent_hash: genesis_hash,
number: 1,
slot: 1,
keypair: &keypair,
global_randomness,
farmer_parameters: &farmer_parameters,
});
header
.digest
.logs
.push(DigestItem::root_plot_public_key_update(None));
seal_header(&keypair, &mut header);
constants.genesis_digest_items.next_solution_range = solution_range;
importer.store.override_constants(constants);
importer
.store
.store_segment_commitment(segment_index, segment_commitment);
importer.store.override_cumulative_weight(genesis_hash, 0);
let res = importer.import_header(header.clone());
assert_ok!(res);
let best_header = importer.store.best_header();
assert_eq!(header.hash(), best_header.header.hash());
assert_eq!(best_header.maybe_root_plot_public_key, None);
});
}
#[test]
fn test_disallow_root_plot_public_key_override() {
new_test_ext().execute_with(|| {
let farmer_parameters = FarmerParameters::new();
let mut constants = default_test_constants();
let keypair_allowed = Keypair::generate();
let pub_key = FarmerPublicKey::unchecked_from(keypair_allowed.public.to_bytes());
let (store, genesis_hash) = initialize_store(constants.clone(), true, Some(pub_key));
let mut importer = HeaderImporter::new(store);
// try to import header that contains root plot public key override
let global_randomness = default_randomness();
let (mut header, solution_range, _block_weight, segment_index, segment_commitment) =
valid_header(ValidHeaderParams {
parent_hash: genesis_hash,
number: 1,
slot: 1,
keypair: &keypair_allowed,
global_randomness,
farmer_parameters: &farmer_parameters,
});
let keypair_disallowed = Keypair::generate();
let pub_key = FarmerPublicKey::unchecked_from(keypair_disallowed.public.to_bytes());
header
.digest
.logs
.push(DigestItem::root_plot_public_key_update(Some(pub_key)));
seal_header(&keypair_allowed, &mut header);
constants.genesis_digest_items.next_solution_range = solution_range;
importer.store.override_constants(constants);
importer
.store
.store_segment_commitment(segment_index, segment_commitment);
importer.store.override_cumulative_weight(genesis_hash, 0);
let res = importer.import_header(header);
assert_err!(
res,
ImportError::DigestError(DigestError::NextDigestVerificationError(
ErrorDigestType::RootPlotPublicKeyUpdate
))
);
});
}
// TODO: Test for expired sector
|
pub mod load;
|
#![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<AvailableProviderOperationList, list::Error> {
let client = &operation_config.client;
let uri_str = &format!("{}/providers/Microsoft.StorSimple/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: AvailableProviderOperationList = 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 managers {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list(operation_config: &crate::OperationConfig, subscription_id: &str) -> std::result::Result<ManagerList, list::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.StorSimple/managers",
&operation_config.base_path, subscription_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)]);
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: ManagerList = 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 async fn list_by_resource_group(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
) -> std::result::Result<ManagerList, list_by_resource_group::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers",
&operation_config.base_path, subscription_id, resource_group_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_by_resource_group::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_resource_group::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_by_resource_group::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_resource_group::ResponseBytesError)?;
let rsp_value: ManagerList = serde_json::from_slice(&body).context(list_by_resource_group::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_resource_group::ResponseBytesError)?;
list_by_resource_group::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod list_by_resource_group {
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 async fn get(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<Manager, get::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}",
&operation_config.base_path, subscription_id, resource_group_name, manager_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: Manager = serde_json::from_slice(&body).context(get::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?;
get::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod get {
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 async fn create_or_update(
operation_config: &crate::OperationConfig,
parameters: &Manager,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<create_or_update::Response, create_or_update::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}",
&operation_config.base_path, subscription_id, resource_group_name, manager_name
);
let mut req_builder = client.put(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(create_or_update::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.json(parameters);
let req = req_builder.build().context(create_or_update::BuildRequestError)?;
let rsp = client.execute(req).await.context(create_or_update::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?;
let rsp_value: Manager = 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: Manager = 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)?;
create_or_update::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod create_or_update {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(Manager),
Created201(Manager),
}
#[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 async fn update(
operation_config: &crate::OperationConfig,
parameters: &ManagerPatch,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<Manager, update::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}",
&operation_config.base_path, subscription_id, resource_group_name, manager_name
);
let mut req_builder = client.patch(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(parameters);
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: Manager = serde_json::from_slice(&body).context(update::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?;
update::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod update {
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 async fn delete(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<delete::Response, delete::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}",
&operation_config.base_path, subscription_id, resource_group_name, manager_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)?;
delete::UnexpectedResponse { status_code, body: body }.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 {
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 async fn get_device_public_encryption_key(
operation_config: &crate::OperationConfig,
device_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<PublicKey, get_device_public_encryption_key::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/publicEncryptionKey",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_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(get_device_public_encryption_key::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(get_device_public_encryption_key::BuildRequestError)?;
let rsp = client
.execute(req)
.await
.context(get_device_public_encryption_key::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(get_device_public_encryption_key::ResponseBytesError)?;
let rsp_value: PublicKey =
serde_json::from_slice(&body).context(get_device_public_encryption_key::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get_device_public_encryption_key::ResponseBytesError)?;
get_device_public_encryption_key::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod get_device_public_encryption_key {
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 async fn get_encryption_settings(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<EncryptionSettings, get_encryption_settings::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/encryptionSettings/default",
&operation_config.base_path, subscription_id, resource_group_name, manager_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_encryption_settings::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_encryption_settings::BuildRequestError)?;
let rsp = client.execute(req).await.context(get_encryption_settings::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(get_encryption_settings::ResponseBytesError)?;
let rsp_value: EncryptionSettings =
serde_json::from_slice(&body).context(get_encryption_settings::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get_encryption_settings::ResponseBytesError)?;
get_encryption_settings::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod get_encryption_settings {
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 async fn get_extended_info(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<ManagerExtendedInfo, get_extended_info::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/extendedInformation/vaultExtendedInfo",
&operation_config.base_path, subscription_id, resource_group_name, manager_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_extended_info::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_extended_info::BuildRequestError)?;
let rsp = client.execute(req).await.context(get_extended_info::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(get_extended_info::ResponseBytesError)?;
let rsp_value: ManagerExtendedInfo = serde_json::from_slice(&body).context(get_extended_info::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get_extended_info::ResponseBytesError)?;
get_extended_info::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod get_extended_info {
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 async fn create_extended_info(
operation_config: &crate::OperationConfig,
parameters: &ManagerExtendedInfo,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<ManagerExtendedInfo, create_extended_info::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/extendedInformation/vaultExtendedInfo",
&operation_config.base_path, subscription_id, resource_group_name, manager_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_extended_info::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.json(parameters);
let req = req_builder.build().context(create_extended_info::BuildRequestError)?;
let rsp = client.execute(req).await.context(create_extended_info::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(create_extended_info::ResponseBytesError)?;
let rsp_value: ManagerExtendedInfo =
serde_json::from_slice(&body).context(create_extended_info::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(create_extended_info::ResponseBytesError)?;
create_extended_info::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod create_extended_info {
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 async fn update_extended_info(
operation_config: &crate::OperationConfig,
parameters: &ManagerExtendedInfo,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
if_match: &str,
) -> std::result::Result<ManagerExtendedInfo, update_extended_info::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/extendedInformation/vaultExtendedInfo",
&operation_config.base_path, subscription_id, resource_group_name, manager_name
);
let mut req_builder = client.patch(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_extended_info::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);
req_builder = req_builder.header("If-Match", if_match);
let req = req_builder.build().context(update_extended_info::BuildRequestError)?;
let rsp = client.execute(req).await.context(update_extended_info::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(update_extended_info::ResponseBytesError)?;
let rsp_value: ManagerExtendedInfo =
serde_json::from_slice(&body).context(update_extended_info::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(update_extended_info::ResponseBytesError)?;
update_extended_info::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod update_extended_info {
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 async fn delete_extended_info(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<(), delete_extended_info::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/extendedInformation/vaultExtendedInfo",
&operation_config.base_path, subscription_id, resource_group_name, manager_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_extended_info::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_extended_info::BuildRequestError)?;
let rsp = client.execute(req).await.context(delete_extended_info::ExecuteRequestError)?;
match rsp.status() {
StatusCode::NO_CONTENT => Ok(()),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(delete_extended_info::ResponseBytesError)?;
delete_extended_info::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod delete_extended_info {
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 async fn list_feature_support_status(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
filter: Option<&str>,
) -> std::result::Result<FeatureList, list_feature_support_status::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/features",
&operation_config.base_path, subscription_id, resource_group_name, manager_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_feature_support_status::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)]);
}
let req = req_builder.build().context(list_feature_support_status::BuildRequestError)?;
let rsp = client
.execute(req)
.await
.context(list_feature_support_status::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_feature_support_status::ResponseBytesError)?;
let rsp_value: FeatureList =
serde_json::from_slice(&body).context(list_feature_support_status::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_feature_support_status::ResponseBytesError)?;
list_feature_support_status::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod list_feature_support_status {
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 async fn get_activation_key(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<Key, get_activation_key::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/listActivationKey",
&operation_config.base_path, subscription_id, resource_group_name, manager_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(get_activation_key::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(get_activation_key::BuildRequestError)?;
let rsp = client.execute(req).await.context(get_activation_key::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(get_activation_key::ResponseBytesError)?;
let rsp_value: Key = serde_json::from_slice(&body).context(get_activation_key::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get_activation_key::ResponseBytesError)?;
get_activation_key::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod get_activation_key {
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 async fn get_public_encryption_key(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<SymmetricEncryptedSecret, get_public_encryption_key::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/listPublicEncryptionKey",
&operation_config.base_path, subscription_id, resource_group_name, manager_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(get_public_encryption_key::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(get_public_encryption_key::BuildRequestError)?;
let rsp = client.execute(req).await.context(get_public_encryption_key::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(get_public_encryption_key::ResponseBytesError)?;
let rsp_value: SymmetricEncryptedSecret =
serde_json::from_slice(&body).context(get_public_encryption_key::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get_public_encryption_key::ResponseBytesError)?;
get_public_encryption_key::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod get_public_encryption_key {
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 async fn list_metrics(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
filter: &str,
) -> std::result::Result<MetricList, list_metrics::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/metrics",
&operation_config.base_path, subscription_id, resource_group_name, manager_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_metrics::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.query(&[("$filter", filter)]);
let req = req_builder.build().context(list_metrics::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_metrics::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_metrics::ResponseBytesError)?;
let rsp_value: MetricList = serde_json::from_slice(&body).context(list_metrics::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_metrics::ResponseBytesError)?;
list_metrics::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod list_metrics {
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 async fn list_metric_definition(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<MetricDefinitionList, list_metric_definition::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/metricsDefinitions",
&operation_config.base_path, subscription_id, resource_group_name, manager_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_metric_definition::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_metric_definition::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_metric_definition::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_metric_definition::ResponseBytesError)?;
let rsp_value: MetricDefinitionList =
serde_json::from_slice(&body).context(list_metric_definition::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_metric_definition::ResponseBytesError)?;
list_metric_definition::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod list_metric_definition {
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 async fn regenerate_activation_key(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<Key, regenerate_activation_key::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/regenerateActivationKey",
&operation_config.base_path, subscription_id, resource_group_name, manager_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(regenerate_activation_key::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(regenerate_activation_key::BuildRequestError)?;
let rsp = client.execute(req).await.context(regenerate_activation_key::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(regenerate_activation_key::ResponseBytesError)?;
let rsp_value: Key = serde_json::from_slice(&body).context(regenerate_activation_key::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(regenerate_activation_key::ResponseBytesError)?;
regenerate_activation_key::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod regenerate_activation_key {
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 access_control_records {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list_by_manager(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<AccessControlRecordList, list_by_manager::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/accessControlRecords",
&operation_config.base_path, subscription_id, resource_group_name, manager_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_by_manager::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_manager::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_by_manager::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_manager::ResponseBytesError)?;
let rsp_value: AccessControlRecordList =
serde_json::from_slice(&body).context(list_by_manager::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_manager::ResponseBytesError)?;
list_by_manager::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod list_by_manager {
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 async fn get(
operation_config: &crate::OperationConfig,
access_control_record_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<AccessControlRecord, get::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/accessControlRecords/{}",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, access_control_record_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: AccessControlRecord = serde_json::from_slice(&body).context(get::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?;
get::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod get {
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 async fn create_or_update(
operation_config: &crate::OperationConfig,
access_control_record_name: &str,
parameters: &AccessControlRecord,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<create_or_update::Response, create_or_update::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/accessControlRecords/{}",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, access_control_record_name
);
let mut req_builder = client.put(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(create_or_update::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.json(parameters);
let req = req_builder.build().context(create_or_update::BuildRequestError)?;
let rsp = client.execute(req).await.context(create_or_update::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?;
let rsp_value: AccessControlRecord = serde_json::from_slice(&body).context(create_or_update::DeserializeError { body })?;
Ok(create_or_update::Response::Ok200(rsp_value))
}
StatusCode::ACCEPTED => Ok(create_or_update::Response::Accepted202),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?;
create_or_update::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod create_or_update {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(AccessControlRecord),
Accepted202,
}
#[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 async fn delete(
operation_config: &crate::OperationConfig,
access_control_record_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<delete::Response, delete::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/accessControlRecords/{}",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, access_control_record_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::ACCEPTED => Ok(delete::Response::Accepted202),
StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(delete::ResponseBytesError)?;
delete::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod delete {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Accepted202,
NoContent204,
}
#[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 alerts {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list_by_manager(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
filter: Option<&str>,
) -> std::result::Result<AlertList, list_by_manager::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/alerts",
&operation_config.base_path, subscription_id, resource_group_name, manager_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_by_manager::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)]);
}
let req = req_builder.build().context(list_by_manager::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_by_manager::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_manager::ResponseBytesError)?;
let rsp_value: AlertList = serde_json::from_slice(&body).context(list_by_manager::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_manager::ResponseBytesError)?;
list_by_manager::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod list_by_manager {
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 async fn clear(
operation_config: &crate::OperationConfig,
parameters: &ClearAlertRequest,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<(), clear::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/clearAlerts",
&operation_config.base_path, subscription_id, resource_group_name, manager_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(clear::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(clear::BuildRequestError)?;
let rsp = client.execute(req).await.context(clear::ExecuteRequestError)?;
match rsp.status() {
StatusCode::NO_CONTENT => Ok(()),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(clear::ResponseBytesError)?;
clear::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod clear {
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 async fn send_test_email(
operation_config: &crate::OperationConfig,
device_name: &str,
parameters: &SendTestAlertEmailRequest,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<(), send_test_email::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/sendTestAlertEmail",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_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(send_test_email::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(send_test_email::BuildRequestError)?;
let rsp = client.execute(req).await.context(send_test_email::ExecuteRequestError)?;
match rsp.status() {
StatusCode::NO_CONTENT => Ok(()),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(send_test_email::ResponseBytesError)?;
send_test_email::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod send_test_email {
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 bandwidth_settings {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list_by_manager(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<BandwidthSettingList, list_by_manager::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/bandwidthSettings",
&operation_config.base_path, subscription_id, resource_group_name, manager_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_by_manager::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_manager::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_by_manager::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_manager::ResponseBytesError)?;
let rsp_value: BandwidthSettingList = serde_json::from_slice(&body).context(list_by_manager::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_manager::ResponseBytesError)?;
list_by_manager::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod list_by_manager {
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 async fn get(
operation_config: &crate::OperationConfig,
bandwidth_setting_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<BandwidthSetting, get::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/bandwidthSettings/{}",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, bandwidth_setting_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: BandwidthSetting = serde_json::from_slice(&body).context(get::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?;
get::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod get {
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 async fn create_or_update(
operation_config: &crate::OperationConfig,
bandwidth_setting_name: &str,
parameters: &BandwidthSetting,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<create_or_update::Response, create_or_update::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/bandwidthSettings/{}",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, bandwidth_setting_name
);
let mut req_builder = client.put(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(create_or_update::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.json(parameters);
let req = req_builder.build().context(create_or_update::BuildRequestError)?;
let rsp = client.execute(req).await.context(create_or_update::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?;
let rsp_value: BandwidthSetting = serde_json::from_slice(&body).context(create_or_update::DeserializeError { body })?;
Ok(create_or_update::Response::Ok200(rsp_value))
}
StatusCode::ACCEPTED => Ok(create_or_update::Response::Accepted202),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?;
create_or_update::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod create_or_update {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(BandwidthSetting),
Accepted202,
}
#[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 async fn delete(
operation_config: &crate::OperationConfig,
bandwidth_setting_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<delete::Response, delete::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/bandwidthSettings/{}",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, bandwidth_setting_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::ACCEPTED => Ok(delete::Response::Accepted202),
StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(delete::ResponseBytesError)?;
delete::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod delete {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Accepted202,
NoContent204,
}
#[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 cloud_appliances {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list_supported_configurations(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<CloudApplianceConfigurationList, list_supported_configurations::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/cloudApplianceConfigurations",
&operation_config.base_path, subscription_id, resource_group_name, manager_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_supported_configurations::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_supported_configurations::BuildRequestError)?;
let rsp = client
.execute(req)
.await
.context(list_supported_configurations::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_supported_configurations::ResponseBytesError)?;
let rsp_value: CloudApplianceConfigurationList =
serde_json::from_slice(&body).context(list_supported_configurations::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_supported_configurations::ResponseBytesError)?;
list_supported_configurations::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod list_supported_configurations {
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 async fn provision(
operation_config: &crate::OperationConfig,
parameters: &CloudAppliance,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<provision::Response, provision::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/provisionCloudAppliance",
&operation_config.base_path, subscription_id, resource_group_name, manager_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(provision::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(provision::BuildRequestError)?;
let rsp = client.execute(req).await.context(provision::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => Ok(provision::Response::Ok200),
StatusCode::ACCEPTED => Ok(provision::Response::Accepted202),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(provision::ResponseBytesError)?;
provision::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod provision {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200,
Accepted202,
}
#[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 devices {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn configure(
operation_config: &crate::OperationConfig,
parameters: &ConfigureDeviceRequest,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<configure::Response, configure::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/configureDevice",
&operation_config.base_path, subscription_id, resource_group_name, manager_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(configure::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(configure::BuildRequestError)?;
let rsp = client.execute(req).await.context(configure::ExecuteRequestError)?;
match rsp.status() {
StatusCode::ACCEPTED => Ok(configure::Response::Accepted202),
StatusCode::NO_CONTENT => Ok(configure::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(configure::ResponseBytesError)?;
configure::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod configure {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Accepted202,
NoContent204,
}
#[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 async fn list_by_manager(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
expand: Option<&str>,
) -> std::result::Result<DeviceList, list_by_manager::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices",
&operation_config.base_path, subscription_id, resource_group_name, manager_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_by_manager::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(expand) = expand {
req_builder = req_builder.query(&[("$expand", expand)]);
}
let req = req_builder.build().context(list_by_manager::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_by_manager::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_manager::ResponseBytesError)?;
let rsp_value: DeviceList = serde_json::from_slice(&body).context(list_by_manager::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_manager::ResponseBytesError)?;
list_by_manager::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod list_by_manager {
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 async fn get(
operation_config: &crate::OperationConfig,
device_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
expand: Option<&str>,
) -> std::result::Result<Device, get::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_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(expand) = expand {
req_builder = req_builder.query(&[("$expand", expand)]);
}
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: Device = serde_json::from_slice(&body).context(get::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?;
get::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod get {
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 async fn update(
operation_config: &crate::OperationConfig,
device_name: &str,
parameters: &DevicePatch,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<Device, update::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_name
);
let mut req_builder = client.patch(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(parameters);
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: Device = serde_json::from_slice(&body).context(update::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?;
update::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod update {
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 async fn delete(
operation_config: &crate::OperationConfig,
device_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<delete::Response, delete::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_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::ACCEPTED => Ok(delete::Response::Accepted202),
StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(delete::ResponseBytesError)?;
delete::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod delete {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Accepted202,
NoContent204,
}
#[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 async fn authorize_for_service_encryption_key_rollover(
operation_config: &crate::OperationConfig,
device_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<(), authorize_for_service_encryption_key_rollover::Error> {
let client = &operation_config.client;
let uri_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/authorizeForServiceEncryptionKeyRollover" , & operation_config . base_path , subscription_id , resource_group_name , manager_name , device_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(authorize_for_service_encryption_key_rollover::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(authorize_for_service_encryption_key_rollover::BuildRequestError)?;
let rsp = client
.execute(req)
.await
.context(authorize_for_service_encryption_key_rollover::ExecuteRequestError)?;
match rsp.status() {
StatusCode::NO_CONTENT => Ok(()),
status_code => {
let body: bytes::Bytes = rsp
.bytes()
.await
.context(authorize_for_service_encryption_key_rollover::ResponseBytesError)?;
authorize_for_service_encryption_key_rollover::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod authorize_for_service_encryption_key_rollover {
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 async fn deactivate(
operation_config: &crate::OperationConfig,
device_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<deactivate::Response, deactivate::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/deactivate",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_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(deactivate::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(deactivate::BuildRequestError)?;
let rsp = client.execute(req).await.context(deactivate::ExecuteRequestError)?;
match rsp.status() {
StatusCode::ACCEPTED => Ok(deactivate::Response::Accepted202),
StatusCode::NO_CONTENT => Ok(deactivate::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(deactivate::ResponseBytesError)?;
deactivate::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod deactivate {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Accepted202,
NoContent204,
}
#[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 async fn install_updates(
operation_config: &crate::OperationConfig,
device_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<install_updates::Response, install_updates::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/installUpdates",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_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(install_updates::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(install_updates::BuildRequestError)?;
let rsp = client.execute(req).await.context(install_updates::ExecuteRequestError)?;
match rsp.status() {
StatusCode::ACCEPTED => Ok(install_updates::Response::Accepted202),
StatusCode::NO_CONTENT => Ok(install_updates::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(install_updates::ResponseBytesError)?;
install_updates::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod install_updates {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Accepted202,
NoContent204,
}
#[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 async fn list_failover_sets(
operation_config: &crate::OperationConfig,
device_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<FailoverSetsList, list_failover_sets::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/listFailoverSets",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_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(list_failover_sets::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_failover_sets::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_failover_sets::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_failover_sets::ResponseBytesError)?;
let rsp_value: FailoverSetsList = serde_json::from_slice(&body).context(list_failover_sets::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_failover_sets::ResponseBytesError)?;
list_failover_sets::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod list_failover_sets {
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 async fn list_metrics(
operation_config: &crate::OperationConfig,
device_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
filter: &str,
) -> std::result::Result<MetricList, list_metrics::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/metrics",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_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_metrics::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.query(&[("$filter", filter)]);
let req = req_builder.build().context(list_metrics::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_metrics::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_metrics::ResponseBytesError)?;
let rsp_value: MetricList = serde_json::from_slice(&body).context(list_metrics::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_metrics::ResponseBytesError)?;
list_metrics::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod list_metrics {
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 async fn list_metric_definition(
operation_config: &crate::OperationConfig,
device_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<MetricDefinitionList, list_metric_definition::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/metricsDefinitions",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_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_metric_definition::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_metric_definition::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_metric_definition::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_metric_definition::ResponseBytesError)?;
let rsp_value: MetricDefinitionList =
serde_json::from_slice(&body).context(list_metric_definition::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_metric_definition::ResponseBytesError)?;
list_metric_definition::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod list_metric_definition {
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 async fn scan_for_updates(
operation_config: &crate::OperationConfig,
device_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<scan_for_updates::Response, scan_for_updates::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/scanForUpdates",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_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(scan_for_updates::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(scan_for_updates::BuildRequestError)?;
let rsp = client.execute(req).await.context(scan_for_updates::ExecuteRequestError)?;
match rsp.status() {
StatusCode::ACCEPTED => Ok(scan_for_updates::Response::Accepted202),
StatusCode::NO_CONTENT => Ok(scan_for_updates::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(scan_for_updates::ResponseBytesError)?;
scan_for_updates::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod scan_for_updates {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Accepted202,
NoContent204,
}
#[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 async fn get_update_summary(
operation_config: &crate::OperationConfig,
device_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<Updates, get_update_summary::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/updateSummary/default",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_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_update_summary::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_update_summary::BuildRequestError)?;
let rsp = client.execute(req).await.context(get_update_summary::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(get_update_summary::ResponseBytesError)?;
let rsp_value: Updates = serde_json::from_slice(&body).context(get_update_summary::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get_update_summary::ResponseBytesError)?;
get_update_summary::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod get_update_summary {
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 async fn failover(
operation_config: &crate::OperationConfig,
source_device_name: &str,
parameters: &FailoverRequest,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<failover::Response, failover::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/failover",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, source_device_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(failover::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(failover::BuildRequestError)?;
let rsp = client.execute(req).await.context(failover::ExecuteRequestError)?;
match rsp.status() {
StatusCode::ACCEPTED => Ok(failover::Response::Accepted202),
StatusCode::NO_CONTENT => Ok(failover::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(failover::ResponseBytesError)?;
failover::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod failover {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Accepted202,
NoContent204,
}
#[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 async fn list_failover_targets(
operation_config: &crate::OperationConfig,
source_device_name: &str,
parameters: &ListFailoverTargetsRequest,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<FailoverTargetsList, list_failover_targets::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/listFailoverTargets",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, source_device_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(list_failover_targets::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_failover_targets::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_failover_targets::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_failover_targets::ResponseBytesError)?;
let rsp_value: FailoverTargetsList =
serde_json::from_slice(&body).context(list_failover_targets::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_failover_targets::ResponseBytesError)?;
list_failover_targets::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod list_failover_targets {
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 device_settings {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn get_alert_settings(
operation_config: &crate::OperationConfig,
device_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<AlertSettings, get_alert_settings::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/alertSettings/default",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_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_alert_settings::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_alert_settings::BuildRequestError)?;
let rsp = client.execute(req).await.context(get_alert_settings::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(get_alert_settings::ResponseBytesError)?;
let rsp_value: AlertSettings = serde_json::from_slice(&body).context(get_alert_settings::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get_alert_settings::ResponseBytesError)?;
get_alert_settings::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod get_alert_settings {
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 async fn create_or_update_alert_settings(
operation_config: &crate::OperationConfig,
device_name: &str,
parameters: &AlertSettings,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<create_or_update_alert_settings::Response, create_or_update_alert_settings::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/alertSettings/default",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_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_alert_settings::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.json(parameters);
let req = req_builder.build().context(create_or_update_alert_settings::BuildRequestError)?;
let rsp = client
.execute(req)
.await
.context(create_or_update_alert_settings::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update_alert_settings::ResponseBytesError)?;
let rsp_value: AlertSettings =
serde_json::from_slice(&body).context(create_or_update_alert_settings::DeserializeError { body })?;
Ok(create_or_update_alert_settings::Response::Ok200(rsp_value))
}
StatusCode::ACCEPTED => Ok(create_or_update_alert_settings::Response::Accepted202),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update_alert_settings::ResponseBytesError)?;
create_or_update_alert_settings::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod create_or_update_alert_settings {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(AlertSettings),
Accepted202,
}
#[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 async fn get_network_settings(
operation_config: &crate::OperationConfig,
device_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<NetworkSettings, get_network_settings::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/networkSettings/default",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_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_network_settings::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_network_settings::BuildRequestError)?;
let rsp = client.execute(req).await.context(get_network_settings::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(get_network_settings::ResponseBytesError)?;
let rsp_value: NetworkSettings = serde_json::from_slice(&body).context(get_network_settings::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get_network_settings::ResponseBytesError)?;
get_network_settings::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod get_network_settings {
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 async fn update_network_settings(
operation_config: &crate::OperationConfig,
device_name: &str,
parameters: &NetworkSettingsPatch,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<update_network_settings::Response, update_network_settings::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/networkSettings/default",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_name
);
let mut req_builder = client.patch(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_network_settings::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(update_network_settings::BuildRequestError)?;
let rsp = client.execute(req).await.context(update_network_settings::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(update_network_settings::ResponseBytesError)?;
let rsp_value: NetworkSettings =
serde_json::from_slice(&body).context(update_network_settings::DeserializeError { body })?;
Ok(update_network_settings::Response::Ok200(rsp_value))
}
StatusCode::ACCEPTED => Ok(update_network_settings::Response::Accepted202),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(update_network_settings::ResponseBytesError)?;
update_network_settings::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod update_network_settings {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(NetworkSettings),
Accepted202,
}
#[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 async fn get_security_settings(
operation_config: &crate::OperationConfig,
device_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<SecuritySettings, get_security_settings::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/securitySettings/default",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_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_security_settings::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_security_settings::BuildRequestError)?;
let rsp = client.execute(req).await.context(get_security_settings::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(get_security_settings::ResponseBytesError)?;
let rsp_value: SecuritySettings =
serde_json::from_slice(&body).context(get_security_settings::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get_security_settings::ResponseBytesError)?;
get_security_settings::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod get_security_settings {
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 async fn update_security_settings(
operation_config: &crate::OperationConfig,
device_name: &str,
parameters: &SecuritySettingsPatch,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<update_security_settings::Response, update_security_settings::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/securitySettings/default",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_name
);
let mut req_builder = client.patch(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_security_settings::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(update_security_settings::BuildRequestError)?;
let rsp = client.execute(req).await.context(update_security_settings::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(update_security_settings::ResponseBytesError)?;
let rsp_value: SecuritySettings =
serde_json::from_slice(&body).context(update_security_settings::DeserializeError { body })?;
Ok(update_security_settings::Response::Ok200(rsp_value))
}
StatusCode::ACCEPTED => Ok(update_security_settings::Response::Accepted202),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(update_security_settings::ResponseBytesError)?;
update_security_settings::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod update_security_settings {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(SecuritySettings),
Accepted202,
}
#[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 async fn sync_remotemanagement_certificate(
operation_config: &crate::OperationConfig,
device_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<sync_remotemanagement_certificate::Response, sync_remotemanagement_certificate::Error> {
let client = &operation_config.client;
let uri_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/securitySettings/default/syncRemoteManagementCertificate" , & operation_config . base_path , subscription_id , resource_group_name , manager_name , device_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(sync_remotemanagement_certificate::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(sync_remotemanagement_certificate::BuildRequestError)?;
let rsp = client
.execute(req)
.await
.context(sync_remotemanagement_certificate::ExecuteRequestError)?;
match rsp.status() {
StatusCode::ACCEPTED => Ok(sync_remotemanagement_certificate::Response::Accepted202),
StatusCode::NO_CONTENT => Ok(sync_remotemanagement_certificate::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(sync_remotemanagement_certificate::ResponseBytesError)?;
sync_remotemanagement_certificate::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod sync_remotemanagement_certificate {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Accepted202,
NoContent204,
}
#[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 async fn get_time_settings(
operation_config: &crate::OperationConfig,
device_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<TimeSettings, get_time_settings::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/timeSettings/default",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_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_time_settings::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_time_settings::BuildRequestError)?;
let rsp = client.execute(req).await.context(get_time_settings::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(get_time_settings::ResponseBytesError)?;
let rsp_value: TimeSettings = serde_json::from_slice(&body).context(get_time_settings::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get_time_settings::ResponseBytesError)?;
get_time_settings::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod get_time_settings {
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 async fn create_or_update_time_settings(
operation_config: &crate::OperationConfig,
device_name: &str,
parameters: &TimeSettings,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<create_or_update_time_settings::Response, create_or_update_time_settings::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/timeSettings/default",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_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_time_settings::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.json(parameters);
let req = req_builder.build().context(create_or_update_time_settings::BuildRequestError)?;
let rsp = client
.execute(req)
.await
.context(create_or_update_time_settings::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update_time_settings::ResponseBytesError)?;
let rsp_value: TimeSettings =
serde_json::from_slice(&body).context(create_or_update_time_settings::DeserializeError { body })?;
Ok(create_or_update_time_settings::Response::Ok200(rsp_value))
}
StatusCode::ACCEPTED => Ok(create_or_update_time_settings::Response::Accepted202),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update_time_settings::ResponseBytesError)?;
create_or_update_time_settings::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod create_or_update_time_settings {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(TimeSettings),
Accepted202,
}
#[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 backup_policies {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list_by_device(
operation_config: &crate::OperationConfig,
device_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<BackupPolicyList, list_by_device::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/backupPolicies",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_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_by_device::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_device::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_by_device::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_device::ResponseBytesError)?;
let rsp_value: BackupPolicyList = serde_json::from_slice(&body).context(list_by_device::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_device::ResponseBytesError)?;
list_by_device::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod list_by_device {
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 async fn get(
operation_config: &crate::OperationConfig,
device_name: &str,
backup_policy_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<BackupPolicy, get::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/backupPolicies/{}",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_name, backup_policy_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: BackupPolicy = serde_json::from_slice(&body).context(get::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?;
get::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod get {
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 async fn create_or_update(
operation_config: &crate::OperationConfig,
device_name: &str,
backup_policy_name: &str,
parameters: &BackupPolicy,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<create_or_update::Response, create_or_update::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/backupPolicies/{}",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_name, backup_policy_name
);
let mut req_builder = client.put(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(create_or_update::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.json(parameters);
let req = req_builder.build().context(create_or_update::BuildRequestError)?;
let rsp = client.execute(req).await.context(create_or_update::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?;
let rsp_value: BackupPolicy = serde_json::from_slice(&body).context(create_or_update::DeserializeError { body })?;
Ok(create_or_update::Response::Ok200(rsp_value))
}
StatusCode::ACCEPTED => Ok(create_or_update::Response::Accepted202),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?;
create_or_update::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod create_or_update {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(BackupPolicy),
Accepted202,
}
#[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 async fn delete(
operation_config: &crate::OperationConfig,
device_name: &str,
backup_policy_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<delete::Response, delete::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/backupPolicies/{}",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_name, backup_policy_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::ACCEPTED => Ok(delete::Response::Accepted202),
StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(delete::ResponseBytesError)?;
delete::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod delete {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Accepted202,
NoContent204,
}
#[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 async fn backup_now(
operation_config: &crate::OperationConfig,
device_name: &str,
backup_policy_name: &str,
backup_type: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<backup_now::Response, backup_now::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/backupPolicies/{}/backup",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_name, backup_policy_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(backup_now::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.query(&[("backupType", backup_type)]);
req_builder = req_builder.header(reqwest::header::CONTENT_LENGTH, 0);
let req = req_builder.build().context(backup_now::BuildRequestError)?;
let rsp = client.execute(req).await.context(backup_now::ExecuteRequestError)?;
match rsp.status() {
StatusCode::ACCEPTED => Ok(backup_now::Response::Accepted202),
StatusCode::NO_CONTENT => Ok(backup_now::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(backup_now::ResponseBytesError)?;
backup_now::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod backup_now {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Accepted202,
NoContent204,
}
#[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 backup_schedules {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list_by_backup_policy(
operation_config: &crate::OperationConfig,
device_name: &str,
backup_policy_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<BackupScheduleList, list_by_backup_policy::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/backupPolicies/{}/schedules",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_name, backup_policy_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_by_backup_policy::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_backup_policy::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_by_backup_policy::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_backup_policy::ResponseBytesError)?;
let rsp_value: BackupScheduleList =
serde_json::from_slice(&body).context(list_by_backup_policy::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_backup_policy::ResponseBytesError)?;
list_by_backup_policy::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod list_by_backup_policy {
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 async fn get(
operation_config: &crate::OperationConfig,
device_name: &str,
backup_policy_name: &str,
backup_schedule_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<BackupSchedule, get::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/backupPolicies/{}/schedules/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
manager_name,
device_name,
backup_policy_name,
backup_schedule_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: BackupSchedule = serde_json::from_slice(&body).context(get::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?;
get::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod get {
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 async fn create_or_update(
operation_config: &crate::OperationConfig,
device_name: &str,
backup_policy_name: &str,
backup_schedule_name: &str,
parameters: &BackupSchedule,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<create_or_update::Response, create_or_update::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/backupPolicies/{}/schedules/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
manager_name,
device_name,
backup_policy_name,
backup_schedule_name
);
let mut req_builder = client.put(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(create_or_update::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.json(parameters);
let req = req_builder.build().context(create_or_update::BuildRequestError)?;
let rsp = client.execute(req).await.context(create_or_update::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?;
let rsp_value: BackupSchedule = serde_json::from_slice(&body).context(create_or_update::DeserializeError { body })?;
Ok(create_or_update::Response::Ok200(rsp_value))
}
StatusCode::ACCEPTED => Ok(create_or_update::Response::Accepted202),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?;
create_or_update::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod create_or_update {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(BackupSchedule),
Accepted202,
}
#[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 async fn delete(
operation_config: &crate::OperationConfig,
device_name: &str,
backup_policy_name: &str,
backup_schedule_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<delete::Response, delete::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/backupPolicies/{}/schedules/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
manager_name,
device_name,
backup_policy_name,
backup_schedule_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::ACCEPTED => Ok(delete::Response::Accepted202),
StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(delete::ResponseBytesError)?;
delete::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod delete {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Accepted202,
NoContent204,
}
#[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 backups {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list_by_device(
operation_config: &crate::OperationConfig,
device_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
filter: Option<&str>,
) -> std::result::Result<BackupList, list_by_device::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/backups",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_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_by_device::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)]);
}
let req = req_builder.build().context(list_by_device::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_by_device::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_device::ResponseBytesError)?;
let rsp_value: BackupList = serde_json::from_slice(&body).context(list_by_device::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_device::ResponseBytesError)?;
list_by_device::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod list_by_device {
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 async fn delete(
operation_config: &crate::OperationConfig,
device_name: &str,
backup_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<delete::Response, delete::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/backups/{}",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_name, backup_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::ACCEPTED => Ok(delete::Response::Accepted202),
StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(delete::ResponseBytesError)?;
delete::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod delete {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Accepted202,
NoContent204,
}
#[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 async fn clone(
operation_config: &crate::OperationConfig,
device_name: &str,
backup_name: &str,
backup_element_name: &str,
parameters: &CloneRequest,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<clone::Response, clone::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/backups/{}/elements/{}/clone",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_name, backup_name, backup_element_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(clone::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(clone::BuildRequestError)?;
let rsp = client.execute(req).await.context(clone::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => Ok(clone::Response::Ok200),
StatusCode::ACCEPTED => Ok(clone::Response::Accepted202),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(clone::ResponseBytesError)?;
clone::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod clone {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200,
Accepted202,
}
#[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 async fn restore(
operation_config: &crate::OperationConfig,
device_name: &str,
backup_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<restore::Response, restore::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/backups/{}/restore",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_name, backup_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(restore::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(restore::BuildRequestError)?;
let rsp = client.execute(req).await.context(restore::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => Ok(restore::Response::Ok200),
StatusCode::ACCEPTED => Ok(restore::Response::Accepted202),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(restore::ResponseBytesError)?;
restore::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod restore {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200,
Accepted202,
}
#[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 hardware_component_groups {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list_by_device(
operation_config: &crate::OperationConfig,
device_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<HardwareComponentGroupList, list_by_device::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/hardwareComponentGroups",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_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_by_device::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_device::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_by_device::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_device::ResponseBytesError)?;
let rsp_value: HardwareComponentGroupList =
serde_json::from_slice(&body).context(list_by_device::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_device::ResponseBytesError)?;
list_by_device::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod list_by_device {
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 async fn change_controller_power_state(
operation_config: &crate::OperationConfig,
device_name: &str,
hardware_component_group_name: &str,
parameters: &ControllerPowerStateChangeRequest,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<change_controller_power_state::Response, change_controller_power_state::Error> {
let client = &operation_config.client;
let uri_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/hardwareComponentGroups/{}/changeControllerPowerState" , & operation_config . base_path , subscription_id , resource_group_name , manager_name , device_name , hardware_component_group_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(change_controller_power_state::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(change_controller_power_state::BuildRequestError)?;
let rsp = client
.execute(req)
.await
.context(change_controller_power_state::ExecuteRequestError)?;
match rsp.status() {
StatusCode::ACCEPTED => Ok(change_controller_power_state::Response::Accepted202),
StatusCode::NO_CONTENT => Ok(change_controller_power_state::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(change_controller_power_state::ResponseBytesError)?;
change_controller_power_state::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod change_controller_power_state {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Accepted202,
NoContent204,
}
#[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 jobs {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list_by_device(
operation_config: &crate::OperationConfig,
device_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
filter: Option<&str>,
) -> std::result::Result<JobList, list_by_device::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/jobs",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_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_by_device::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)]);
}
let req = req_builder.build().context(list_by_device::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_by_device::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_device::ResponseBytesError)?;
let rsp_value: JobList = serde_json::from_slice(&body).context(list_by_device::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_device::ResponseBytesError)?;
list_by_device::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod list_by_device {
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 async fn get(
operation_config: &crate::OperationConfig,
device_name: &str,
job_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<Job, get::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/jobs/{}",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_name, job_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: Job = serde_json::from_slice(&body).context(get::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?;
get::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod get {
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 async fn cancel(
operation_config: &crate::OperationConfig,
device_name: &str,
job_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<cancel::Response, cancel::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/jobs/{}/cancel",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_name, job_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(cancel::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(cancel::BuildRequestError)?;
let rsp = client.execute(req).await.context(cancel::ExecuteRequestError)?;
match rsp.status() {
StatusCode::ACCEPTED => Ok(cancel::Response::Accepted202),
StatusCode::NO_CONTENT => Ok(cancel::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(cancel::ResponseBytesError)?;
cancel::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod cancel {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Accepted202,
NoContent204,
}
#[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 async fn list_by_manager(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
filter: Option<&str>,
) -> std::result::Result<JobList, list_by_manager::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/jobs",
&operation_config.base_path, subscription_id, resource_group_name, manager_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_by_manager::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)]);
}
let req = req_builder.build().context(list_by_manager::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_by_manager::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_manager::ResponseBytesError)?;
let rsp_value: JobList = serde_json::from_slice(&body).context(list_by_manager::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_manager::ResponseBytesError)?;
list_by_manager::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod list_by_manager {
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 volume_containers {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list_by_device(
operation_config: &crate::OperationConfig,
device_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<VolumeContainerList, list_by_device::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/volumeContainers",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_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_by_device::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_device::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_by_device::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_device::ResponseBytesError)?;
let rsp_value: VolumeContainerList = serde_json::from_slice(&body).context(list_by_device::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_device::ResponseBytesError)?;
list_by_device::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod list_by_device {
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 async fn get(
operation_config: &crate::OperationConfig,
device_name: &str,
volume_container_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<VolumeContainer, get::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/volumeContainers/{}",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_name, volume_container_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: VolumeContainer = serde_json::from_slice(&body).context(get::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?;
get::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod get {
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 async fn create_or_update(
operation_config: &crate::OperationConfig,
device_name: &str,
volume_container_name: &str,
parameters: &VolumeContainer,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<create_or_update::Response, create_or_update::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/volumeContainers/{}",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_name, volume_container_name
);
let mut req_builder = client.put(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(create_or_update::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.json(parameters);
let req = req_builder.build().context(create_or_update::BuildRequestError)?;
let rsp = client.execute(req).await.context(create_or_update::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?;
let rsp_value: VolumeContainer = serde_json::from_slice(&body).context(create_or_update::DeserializeError { body })?;
Ok(create_or_update::Response::Ok200(rsp_value))
}
StatusCode::ACCEPTED => Ok(create_or_update::Response::Accepted202),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?;
create_or_update::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod create_or_update {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(VolumeContainer),
Accepted202,
}
#[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 async fn delete(
operation_config: &crate::OperationConfig,
device_name: &str,
volume_container_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<delete::Response, delete::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/volumeContainers/{}",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_name, volume_container_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::ACCEPTED => Ok(delete::Response::Accepted202),
StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(delete::ResponseBytesError)?;
delete::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod delete {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Accepted202,
NoContent204,
}
#[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 async fn list_metrics(
operation_config: &crate::OperationConfig,
device_name: &str,
volume_container_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
filter: &str,
) -> std::result::Result<MetricList, list_metrics::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/volumeContainers/{}/metrics",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_name, volume_container_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_metrics::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.query(&[("$filter", filter)]);
let req = req_builder.build().context(list_metrics::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_metrics::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_metrics::ResponseBytesError)?;
let rsp_value: MetricList = serde_json::from_slice(&body).context(list_metrics::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_metrics::ResponseBytesError)?;
list_metrics::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod list_metrics {
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 async fn list_metric_definition(
operation_config: &crate::OperationConfig,
device_name: &str,
volume_container_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<MetricDefinitionList, list_metric_definition::Error> {
let client = &operation_config.client;
let uri_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/volumeContainers/{}/metricsDefinitions" , & operation_config . base_path , subscription_id , resource_group_name , manager_name , device_name , volume_container_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_metric_definition::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_metric_definition::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_metric_definition::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_metric_definition::ResponseBytesError)?;
let rsp_value: MetricDefinitionList =
serde_json::from_slice(&body).context(list_metric_definition::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_metric_definition::ResponseBytesError)?;
list_metric_definition::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod list_metric_definition {
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 volumes {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list_by_volume_container(
operation_config: &crate::OperationConfig,
device_name: &str,
volume_container_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<VolumeList, list_by_volume_container::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/volumeContainers/{}/volumes",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_name, volume_container_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_by_volume_container::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_volume_container::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_by_volume_container::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_volume_container::ResponseBytesError)?;
let rsp_value: VolumeList = serde_json::from_slice(&body).context(list_by_volume_container::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_volume_container::ResponseBytesError)?;
list_by_volume_container::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod list_by_volume_container {
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 async fn get(
operation_config: &crate::OperationConfig,
device_name: &str,
volume_container_name: &str,
volume_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<Volume, get::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/volumeContainers/{}/volumes/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
manager_name,
device_name,
volume_container_name,
volume_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: Volume = serde_json::from_slice(&body).context(get::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?;
get::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod get {
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 async fn create_or_update(
operation_config: &crate::OperationConfig,
device_name: &str,
volume_container_name: &str,
volume_name: &str,
parameters: &Volume,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<create_or_update::Response, create_or_update::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/volumeContainers/{}/volumes/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
manager_name,
device_name,
volume_container_name,
volume_name
);
let mut req_builder = client.put(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(create_or_update::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.json(parameters);
let req = req_builder.build().context(create_or_update::BuildRequestError)?;
let rsp = client.execute(req).await.context(create_or_update::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?;
let rsp_value: Volume = serde_json::from_slice(&body).context(create_or_update::DeserializeError { body })?;
Ok(create_or_update::Response::Ok200(rsp_value))
}
StatusCode::ACCEPTED => Ok(create_or_update::Response::Accepted202),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?;
create_or_update::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod create_or_update {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(Volume),
Accepted202,
}
#[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 async fn delete(
operation_config: &crate::OperationConfig,
device_name: &str,
volume_container_name: &str,
volume_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<delete::Response, delete::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/volumeContainers/{}/volumes/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
manager_name,
device_name,
volume_container_name,
volume_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::ACCEPTED => Ok(delete::Response::Accepted202),
StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(delete::ResponseBytesError)?;
delete::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod delete {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Accepted202,
NoContent204,
}
#[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 async fn list_metrics(
operation_config: &crate::OperationConfig,
device_name: &str,
volume_container_name: &str,
volume_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
filter: &str,
) -> std::result::Result<MetricList, list_metrics::Error> {
let client = &operation_config.client;
let uri_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/volumeContainers/{}/volumes/{}/metrics" , & operation_config . base_path , subscription_id , resource_group_name , manager_name , device_name , volume_container_name , volume_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_metrics::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.query(&[("$filter", filter)]);
let req = req_builder.build().context(list_metrics::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_metrics::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_metrics::ResponseBytesError)?;
let rsp_value: MetricList = serde_json::from_slice(&body).context(list_metrics::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_metrics::ResponseBytesError)?;
list_metrics::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod list_metrics {
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 async fn list_metric_definition(
operation_config: &crate::OperationConfig,
device_name: &str,
volume_container_name: &str,
volume_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<MetricDefinitionList, list_metric_definition::Error> {
let client = &operation_config.client;
let uri_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/volumeContainers/{}/volumes/{}/metricsDefinitions" , & operation_config . base_path , subscription_id , resource_group_name , manager_name , device_name , volume_container_name , volume_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_metric_definition::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_metric_definition::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_metric_definition::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_metric_definition::ResponseBytesError)?;
let rsp_value: MetricDefinitionList =
serde_json::from_slice(&body).context(list_metric_definition::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_metric_definition::ResponseBytesError)?;
list_metric_definition::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod list_metric_definition {
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 async fn list_by_device(
operation_config: &crate::OperationConfig,
device_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<VolumeList, list_by_device::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/devices/{}/volumes",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, device_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_by_device::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_device::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_by_device::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_device::ResponseBytesError)?;
let rsp_value: VolumeList = serde_json::from_slice(&body).context(list_by_device::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_device::ResponseBytesError)?;
list_by_device::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod list_by_device {
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 storage_account_credentials {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list_by_manager(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<StorageAccountCredentialList, list_by_manager::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/storageAccountCredentials",
&operation_config.base_path, subscription_id, resource_group_name, manager_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_by_manager::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_manager::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_by_manager::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_manager::ResponseBytesError)?;
let rsp_value: StorageAccountCredentialList =
serde_json::from_slice(&body).context(list_by_manager::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_manager::ResponseBytesError)?;
list_by_manager::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod list_by_manager {
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 async fn get(
operation_config: &crate::OperationConfig,
storage_account_credential_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<StorageAccountCredential, get::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/storageAccountCredentials/{}",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, storage_account_credential_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: StorageAccountCredential = serde_json::from_slice(&body).context(get::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?;
get::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod get {
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 async fn create_or_update(
operation_config: &crate::OperationConfig,
storage_account_credential_name: &str,
parameters: &StorageAccountCredential,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<create_or_update::Response, create_or_update::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/storageAccountCredentials/{}",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, storage_account_credential_name
);
let mut req_builder = client.put(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(create_or_update::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.json(parameters);
let req = req_builder.build().context(create_or_update::BuildRequestError)?;
let rsp = client.execute(req).await.context(create_or_update::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?;
let rsp_value: StorageAccountCredential =
serde_json::from_slice(&body).context(create_or_update::DeserializeError { body })?;
Ok(create_or_update::Response::Ok200(rsp_value))
}
StatusCode::ACCEPTED => Ok(create_or_update::Response::Accepted202),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?;
create_or_update::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod create_or_update {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(StorageAccountCredential),
Accepted202,
}
#[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 async fn delete(
operation_config: &crate::OperationConfig,
storage_account_credential_name: &str,
subscription_id: &str,
resource_group_name: &str,
manager_name: &str,
) -> std::result::Result<delete::Response, delete::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorSimple/managers/{}/storageAccountCredentials/{}",
&operation_config.base_path, subscription_id, resource_group_name, manager_name, storage_account_credential_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::ACCEPTED => Ok(delete::Response::Accepted202),
StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(delete::ResponseBytesError)?;
delete::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod delete {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Accepted202,
NoContent204,
}
#[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 },
}
}
}
|
use crate::ebr::{Arc, AtomicArc, Barrier, Ptr, Tag};
use std::sync::atomic::Ordering::{self, Relaxed, Release};
/// [`LinkedList`] is a wait-free self-referential singly linked list.
pub trait LinkedList: 'static + Sized {
/// Returns a reference to the forward link.
///
/// The pointer value may be tagged if [`Self::mark`] or [`Self::delete_self`] has been
/// invoked.
fn link_ref(&self) -> &AtomicArc<Self>;
/// Returns `true` if `self` is reachable and not marked.
///
/// # Examples
///
/// ```
/// use scc::ebr::{AtomicArc, Tag};
/// use scc::LinkedList;
/// use std::sync::atomic::Ordering::Relaxed;
///
/// #[derive(Default)]
/// struct L(AtomicArc<L>, usize);
/// impl LinkedList for L {
/// fn link_ref(&self) -> &AtomicArc<L> {
/// &self.0
/// }
/// }
///
/// let head: L = L::default();
/// assert!(head.is_clear(Relaxed));
/// assert!(head.mark(Relaxed));
/// assert!(!head.is_clear(Relaxed));
/// assert!(head.delete_self(Relaxed));
/// assert!(!head.is_clear(Relaxed));
/// ```
fn is_clear(&self, order: Ordering) -> bool {
self.link_ref().tag(order) == Tag::None
}
/// Marks `self` with an internal flag to denote that `self` is in a special state.
///
/// It returns `false` if a flag has already been marked on `self`.
///
/// # Examples
///
/// ```
/// use scc::ebr::AtomicArc;
/// use scc::LinkedList;
/// use std::sync::atomic::Ordering::Relaxed;
///
/// #[derive(Default)]
/// struct L(AtomicArc<L>, usize);
/// impl LinkedList for L {
/// fn link_ref(&self) -> &AtomicArc<L> {
/// &self.0
/// }
/// }
///
/// let head: L = L::default();
/// assert!(head.mark(Relaxed));
/// ```
fn mark(&self, order: Ordering) -> bool {
self.link_ref()
.update_tag_if(Tag::First, |t| t == Tag::None, order)
}
/// Removes marks from `self`.
///
/// It returns `false` if no flag has been marked on `self`.
///
/// # Examples
///
/// ```
/// use scc::ebr::AtomicArc;
/// use scc::LinkedList;
/// use std::sync::atomic::Ordering::Relaxed;
///
/// #[derive(Default)]
/// struct L(AtomicArc<L>, usize);
/// impl LinkedList for L {
/// fn link_ref(&self) -> &AtomicArc<L> {
/// &self.0
/// }
/// }
///
/// let head: L = L::default();
/// assert!(!head.unmark(Relaxed));
/// assert!(head.mark(Relaxed));
/// assert!(head.unmark(Relaxed));
/// assert!(!head.is_marked(Relaxed));
/// ```
fn unmark(&self, order: Ordering) -> bool {
self.link_ref()
.update_tag_if(Tag::None, |t| t == Tag::First, order)
}
/// Returns `true` if `self` has a mark on it.
///
/// # Examples
///
/// ```
/// use scc::ebr::AtomicArc;
/// use scc::LinkedList;
/// use std::sync::atomic::Ordering::Relaxed;
///
/// #[derive(Default)]
/// struct L(AtomicArc<L>, usize);
/// impl LinkedList for L {
/// fn link_ref(&self) -> &AtomicArc<L> {
/// &self.0
/// }
/// }
///
/// let head: L = L::default();
/// assert!(!head.is_marked(Relaxed));
/// assert!(head.mark(Relaxed));
/// assert!(head.is_marked(Relaxed));
/// ```
fn is_marked(&self, order: Ordering) -> bool {
self.link_ref().tag(order) == Tag::First
}
/// Deletes `self`.
///
/// It returns `false` if `self` already has `deleted` marked on it.
///
/// # Examples
///
/// ```
/// use scc::ebr::{Arc, AtomicArc, Barrier};
/// use scc::LinkedList;
/// use std::sync::atomic::Ordering::Relaxed;
///
/// #[derive(Default)]
/// struct L(AtomicArc<L>, usize);
/// impl LinkedList for L {
/// fn link_ref(&self) -> &AtomicArc<L> {
/// &self.0
/// }
/// }
///
/// let barrier = Barrier::new();
///
/// let head: L = L::default();
/// let tail: Arc<L> = Arc::new(L::default());
/// assert!(head.push_back(tail.clone(), false, Relaxed, &barrier).is_ok());
///
/// tail.delete_self(Relaxed);
/// assert!(head.next_ptr(Relaxed, &barrier).as_ref().is_none());
/// ```
fn delete_self(&self, order: Ordering) -> bool {
self.link_ref()
.update_tag_if(Tag::Second, |t| t != Tag::Second, order)
}
/// Returns `true` if `self` has been deleted.
///
/// # Examples
///
/// ```
/// use scc::ebr::AtomicArc;
/// use scc::LinkedList;
/// use std::sync::atomic::Ordering::Relaxed;
///
/// #[derive(Default)]
/// struct L(AtomicArc<L>, usize);
/// impl LinkedList for L {
/// fn link_ref(&self) -> &AtomicArc<L> {
/// &self.0
/// }
/// }
///
/// let entry: L = L::default();
/// assert!(!entry.is_deleted(Relaxed));
/// entry.delete_self(Relaxed);
/// assert!(entry.is_deleted(Relaxed));
/// ```
fn is_deleted(&self, order: Ordering) -> bool {
self.link_ref().tag(order) == Tag::Second
}
/// Appends the given entry after `self` and returns a pointer to the entry.
///
/// If `mark` is given `true`, it atomically marks an internal flag on `self` when updating
/// the linked list, otherwise it removes marks.
///
/// # Errors
///
/// It returns the supplied [`Arc`] when it finds `self` deleted.
///
/// # Examples
///
/// ```
/// use scc::ebr::{Arc, AtomicArc, Barrier};
/// use scc::LinkedList;
/// use std::sync::atomic::Ordering::Relaxed;
///
/// #[derive(Default)]
/// struct L(AtomicArc<L>, usize);
/// impl LinkedList for L {
/// fn link_ref(&self) -> &AtomicArc<L> {
/// &self.0
/// }
/// }
///
/// let barrier = Barrier::new();
///
/// let head: L = L::default();
/// assert!(head.push_back(Arc::new(L::default()), true, Relaxed, &barrier).is_ok());
/// assert!(head.is_marked(Relaxed));
/// assert!(head.push_back(Arc::new(L::default()), false, Relaxed, &barrier).is_ok());
/// assert!(!head.is_marked(Relaxed));
///
/// head.delete_self(Relaxed);
/// assert!(!head.is_marked(Relaxed));
/// assert!(head.push_back(Arc::new(L::default()), false, Relaxed, &barrier).is_err());
/// ```
fn push_back<'b>(
&self,
mut entry: Arc<Self>,
mark: bool,
order: Ordering,
barrier: &'b Barrier,
) -> Result<Ptr<'b, Self>, Arc<Self>> {
let new_tag = if mark { Tag::First } else { Tag::None };
let mut next_ptr = self.link_ref().load(Relaxed, barrier);
while next_ptr.tag() != Tag::Second {
entry
.link_ref()
.swap((next_ptr.try_into_arc(), Tag::None), Relaxed);
match self
.link_ref()
.compare_exchange(next_ptr, (Some(entry), new_tag), order, Relaxed)
{
Ok((_, updated)) => {
return Ok(updated);
}
Err((passed, actual)) => {
entry = passed.unwrap();
next_ptr = actual;
}
}
}
// `self` has been deleted.
Err(entry)
}
/// Returns the closest next valid entry.
///
/// It unlinks deleted entries until it reaches a valid one.
///
/// # Examples
///
/// ```
/// use scc::ebr::{Arc, AtomicArc, Barrier};
/// use scc::LinkedList;
/// use std::sync::atomic::Ordering::Relaxed;
///
/// #[derive(Default)]
/// struct L(AtomicArc<L>, usize);
/// impl LinkedList for L {
/// fn link_ref(&self) -> &AtomicArc<L> {
/// &self.0
/// }
/// }
///
/// let barrier = Barrier::new();
///
/// let head: L = L::default();
/// assert!(head.push_back(Arc::new(L(AtomicArc::null(), 1)), false, Relaxed, &barrier).is_ok());
/// head.mark(Relaxed);
///
/// let next_ptr = head.next_ptr(Relaxed, &barrier);
/// assert_eq!(next_ptr.as_ref().unwrap().1, 1);
/// assert!(head.is_marked(Relaxed));
/// ```
fn next_ptr<'b>(&self, order: Ordering, barrier: &'b Barrier) -> Ptr<'b, Self> {
let self_next_ptr = self.link_ref().load(order, barrier);
let self_tag = self_next_ptr.tag();
let mut next_ptr = self_next_ptr;
let mut update_self = false;
let next_valid_ptr = loop {
if let Some(next_ref) = next_ptr.as_ref() {
let next_next_ptr = next_ref.link_ref().load(order, barrier);
if next_next_ptr.tag() != Tag::Second {
break next_ptr;
}
if !update_self {
update_self = true;
}
next_ptr = next_next_ptr;
} else {
break Ptr::null();
}
};
// Updates its link if an invalid entry has been found, and `self` is a valid one.
if update_self && self_tag != Tag::Second {
let _result = self.link_ref().compare_exchange(
self_next_ptr,
(next_valid_ptr.try_into_arc(), self_tag),
Release,
Relaxed,
);
}
next_valid_ptr
}
}
|
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use futures03::{stream::unfold, FutureExt, Stream, StreamExt};
use futures_timer::Delay;
use std::time::Duration;
pub fn interval(duration: Duration) -> impl Stream<Item = ()> + Unpin {
unfold((), move |_| Delay::new(duration).map(|_| Some(((), ())))).map(drop)
}
|
#[cfg(all(unix, not(target_env = "musl")))]
#[global_allocator]
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
use fnd::cli;
fn main() -> cli::Result<()> {
cli::run()
}
|
extern crate libc;
use libc::{c_int, c_uchar, c_char, c_void, timeval};
use std::ptr;
use std::ffi::CStr;
use std::collections::HashMap;
use std::slice;
pub mod codes;
// Define the structs used by the ldap c library.
#[repr(C)]
struct LDAP;
#[repr(C)]
struct LDAPMessage;
#[repr(C)]
struct LDAPControl;
#[repr(C)]
struct BerElement;
#[link(name = "lber")]
#[allow(improper_ctypes)]
extern {
fn ber_free(ber: *const BerElement, freebuf: c_int);
}
#[link(name = "ldap")]
#[allow(improper_ctypes)]
extern {
fn ldap_initialize(ldap: *const *mut LDAP, uri: *const c_uchar) -> c_int;
fn ldap_memfree(p: *const c_void);
fn ldap_err2string(err: c_int) -> *mut c_char;
fn ldap_first_entry(ldap: *const LDAP, result: *const LDAPMessage) -> *const LDAPMessage;
fn ldap_next_entry(ldap: *const LDAP, entry: *const LDAPMessage) -> *const LDAPMessage;
fn ldap_get_values(ldap: *const LDAP, entry: *const LDAPMessage, attr: *const c_char) -> *const *const c_char;
fn ldap_count_values(vals: *const *const c_char) -> c_int;
fn ldap_value_free(vals: *const *const c_char);
fn ldap_simple_bind_s(ldap: *const LDAP, who: *const c_uchar, pass: *const c_uchar) -> c_int;
fn ldap_first_attribute(ldap: *const LDAP, entry: *const LDAPMessage, berptr: *const *const BerElement) -> *const c_char;
fn ldap_next_attribute(ldap: *const LDAP, entry: *const LDAPMessage, berptr: *const BerElement) -> *const c_char;
fn ldap_search_ext_s(ldap: *const LDAP, base: *const c_uchar, scope: c_int,
filter: *const c_uchar, attrs: *const *const c_uchar,
attrsonly: c_int, serverctrls: *const *const LDAPControl,
clientctrls: *const *const LDAPControl, timeout: *const timeval,
sizelimit: c_int, res: *const *mut LDAPMessage) -> c_int;
}
pub struct RustLDAP {
// Have a heap allocated box for our LDAP instance
_ldap: Box<LDAP>,
// Have the raw pointer to it so we can pass it into internal functions
ldap_ptr: *const LDAP,
}
impl RustLDAP {
/// Create a new RustLDAP struct and use an ffi call to ldap_initialize to
/// allocate and init a c LDAP struct. All of that is hidden inside of
/// RustLDAP.
pub fn new(uri: &str) -> Result<RustLDAP, &str> {
unsafe {
let cldap = Box::from_raw(ptr::null_mut());
let ldap_ptr_ptr: *const *mut LDAP = &Box::into_raw(cldap);
let res = ldap_initialize(ldap_ptr_ptr, uri.as_ptr());
if res != codes::results::LDAP_SUCCESS {
let raw_estr = ldap_err2string(res as c_int);
return Err(CStr::from_ptr(raw_estr)
.to_str()
.unwrap());
}
let new_ldap = RustLDAP {
_ldap: Box::from_raw(*ldap_ptr_ptr),
ldap_ptr: *ldap_ptr_ptr,
};
Ok(new_ldap)
}
}
/// Perform a synchronos simple bind (ldap_simple_bind_s). The result is
/// either Ok(LDAP_SUCCESS) or Err(ldap_err2string).
pub fn simple_bind(&self, who: &str, pass: &str) -> Result<i64, &str> {
let res = unsafe { ldap_simple_bind_s(self.ldap_ptr, who.as_ptr(), pass.as_ptr()) as i64};
if res < 0 {
let raw_estr = unsafe { ldap_err2string(res as c_int) };
return Err(unsafe { CStr::from_ptr(raw_estr).to_str().unwrap() });
}
Ok(res)
}
pub fn simple_search(&self, base: &str, scope: i32) -> Result<Vec<HashMap<String,Vec<String>>>, &str> {
self.ldap_search(base, scope, None, None, false, None, None, ptr::null(), -1)
}
/// Expose a not very 'rust-y' api for ldap_search_ext_s. Ideally this will
/// be used mainly internally and a simpler api is exposed to users.
fn ldap_search(&self, base: &str, scope: i32, filter: Option<&str>, attrs: Option<Vec<&str>>, attrsonly: bool, serverctrls: Option<*const *const LDAPControl>, clientctrls: Option<*const *const LDAPControl>, timeout: *const timeval, sizelimit: i32) -> Result<Vec<HashMap<String,Vec<String>>>, &str> {
// Allocate a boxed pointer for our ldap message. We will need to call
// ldap_msgfree on the raw pointer after we are done, and then
// make sure the box is deallocated
let ldap_msg = unsafe { Box::from_raw(ptr::null_mut()) };
let raw_msg: *const *mut LDAPMessage = &Box::into_raw(ldap_msg);
let r_filter = match filter {
Some(fs) => fs.as_ptr(),
None => ptr::null()
};
let r_attrs = match attrs {
Some(avec) => avec.iter().map(|a| { (*a).as_ptr() }).collect::<Vec<*const u8>>().as_ptr(),
None => ptr::null()
};
let r_serverctrls = match serverctrls {
Some(sc) => sc,
None => ptr::null()
};
let r_clientctrls = match clientctrls {
Some(cc) => cc,
None => ptr::null()
};
let res: i32 = unsafe { ldap_search_ext_s(self.ldap_ptr,
base.as_ptr(),
scope as c_int,
r_filter,
r_attrs,
attrsonly as c_int,
r_serverctrls,
r_clientctrls,
timeout,
sizelimit as c_int,
raw_msg) };
if res != codes::results::LDAP_SUCCESS {
let raw_estr = unsafe { ldap_err2string(res as c_int) };
return Err(unsafe { CStr::from_ptr(raw_estr).to_str().unwrap() });
}
let mut resvec: Vec<HashMap<String,Vec<String>>> = vec![];
let mut entry = unsafe { ldap_first_entry(self.ldap_ptr, *raw_msg) };
loop {
if entry.is_null() {
break;
}
let mut map: HashMap<String,Vec<String>> = HashMap::new();
let ber: *const BerElement = ptr::null();
let mut attr: *const c_char = unsafe {
ldap_first_attribute(self.ldap_ptr, entry, &ber)
};
loop {
if attr.is_null() {
break;
}
unsafe {
// This fun bit of code ensures that we copy the c string for
// the attribute into an owned string. This is important since
// we use ldap_memfree just below this to free the memory on the
// c side of things.
let tmp: String = CStr::from_ptr(attr)
.to_str()
.unwrap()
.to_owned();
let raw_vals: *const *const c_char = ldap_get_values(
self.ldap_ptr,
entry,
attr);
let raw_vals_len = ldap_count_values(raw_vals) as usize;
let val_slice: &[*const c_char] = slice::from_raw_parts(
raw_vals,
raw_vals_len);
let values: Vec<String> = val_slice.iter().map(|ptr| {
CStr::from_ptr(*ptr)
.to_str()
.unwrap()
.to_owned()}).collect();
map.insert(tmp, values);
ldap_value_free(raw_vals);
ldap_memfree(attr as *const c_void);
attr = ldap_next_attribute(self.ldap_ptr, entry, ber)
}
}
unsafe { ber_free(ber, 0) };
resvec.push(map);
entry = unsafe { ldap_next_entry(self.ldap_ptr, entry) };
}
Ok(resvec)
}
}
#[cfg(test)]
mod tests {
use codes;
/// Test creating a RustLDAP struct with a valid uri.
#[test]
fn test_ldap_new() {
let ldap = super::RustLDAP::new("ldap://ldapproxy1.csh.rit.edu");
match ldap {
Ok(_) => assert!(true),
Err(_) => {
assert!(false);
}
}
}
/// Test creating a RustLDAP struct with an invalid uri.
#[test]
fn test_invalid_ldap_new() {
let ldap = super::RustLDAP::new("lda://localhost");
match ldap {
Ok(_) => assert!(false),
Err(es) => {
assert_eq!("Bad parameter to an ldap routine", es);
}
}
}
#[test]
fn test_simple_bind() {
let ldap_res = super::RustLDAP::new("ldaps://ldap.csh.rit.edu");
match ldap_res {
Ok(ldap) => {
let res = ldap.simple_bind("uid=test4,ou=Users,dc=csh,dc=rit,dc=edu", "fakepass");
println!("{:?}", res);
}
Err(_) => {
assert!(false);
}
}
}
#[test]
fn test_simple_search() {
println!("Testing search");
let ldap_res = super::RustLDAP::new("ldap://ldapproxy1.csh.rit.edu");
match ldap_res {
Ok(ldap) => {
let res = ldap.simple_bind("uid=test4,ou=Users,dc=csh,dc=rit,dc=edu", "fake");
println!("{:?}", res);
let search_res = ldap.simple_search("uid=rossdylan,ou=Users,dc=csh,dc=rit,dc=edu", codes::scopes::LDAP_SCOPE_BASE);
println!("{:?}", search_res);
}
Err(_) => {
assert!(false);
}
}
}
}
|
struct Solution;
impl Solution {
pub fn combine(n: i32, k: i32) -> Vec<Vec<i32>> {
let mut ans = Vec::new();
Self::helper(n, k, 1, &mut Vec::with_capacity(k as usize), &mut ans);
ans
}
fn helper(n: i32, k: i32, next: i32, tmp: &mut Vec<i32>, ans: &mut Vec<Vec<i32>>) {
if k == 0 {
ans.push(tmp.clone());
return;
}
// [next, n] 中已经不够 k 个了
if n - next + 1 < k {
return;
}
for i in next..=n {
tmp.push(i);
Self::helper(n, k - 1, i + 1, tmp, ans);
tmp.pop();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_combine() {
let mut ans = Solution::combine(4, 2);
let mut want = vec![
vec![2, 4],
vec![3, 4],
vec![2, 3],
vec![1, 2],
vec![1, 3],
vec![1, 4],
];
ans.sort_by(|a, b| {
for (i, n) in a.iter().enumerate() {
if *n != b[i] {
return n.cmp(&b[i]);
}
}
return std::cmp::Ordering::Equal;
});
want.sort_by(|a, b| {
for (i, n) in a.iter().enumerate() {
if *n != b[i] {
return n.cmp(&b[i]);
}
}
return std::cmp::Ordering::Equal;
});
assert_eq!(ans, want);
}
}
|
use super::SocketAddr;
use super::Stream;
use std::io::Error;
use std::io::ErrorKind;
use tokio::net::{TcpListener, UnixListener};
pub enum Listener {
Unix(UnixListener),
Tcp(TcpListener),
}
impl Listener {
pub async fn bind(protocol: &str, addr: &str) -> std::io::Result<Self> {
match protocol {
"unix" => Ok(Listener::Unix(UnixListener::bind(addr)?)),
"tcp" => Ok(Listener::Tcp(TcpListener::bind(addr).await?)),
_ => Err(Error::new(ErrorKind::InvalidInput, addr)),
}
}
pub async fn accept(&self) -> std::io::Result<(Stream, SocketAddr)> {
match self {
Listener::Unix(l) => {
let (stream, addr) = l.accept().await?;
Ok((stream.into(), SocketAddr::Unix(addr)))
}
Listener::Tcp(l) => {
let (stream, addr) = l.accept().await?;
//stream.set_nodelay(true)?;
Ok((stream.into(), SocketAddr::Tcp(addr)))
}
}
}
}
|
#[doc = "Register `TX_SINGLE_COLLISION_GOOD_PACKETS` reader"]
pub type R = crate::R<TX_SINGLE_COLLISION_GOOD_PACKETS_SPEC>;
#[doc = "Field `TXSNGLCOLG` reader - Tx Single Collision Good Packets This field indicates the number of successfully transmitted packets after a single collision in the Half-duplex mode."]
pub type TXSNGLCOLG_R = crate::FieldReader<u32>;
impl R {
#[doc = "Bits 0:31 - Tx Single Collision Good Packets This field indicates the number of successfully transmitted packets after a single collision in the Half-duplex mode."]
#[inline(always)]
pub fn txsnglcolg(&self) -> TXSNGLCOLG_R {
TXSNGLCOLG_R::new(self.bits)
}
}
#[doc = "Tx single collision good packets register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tx_single_collision_good_packets::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct TX_SINGLE_COLLISION_GOOD_PACKETS_SPEC;
impl crate::RegisterSpec for TX_SINGLE_COLLISION_GOOD_PACKETS_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`tx_single_collision_good_packets::R`](R) reader structure"]
impl crate::Readable for TX_SINGLE_COLLISION_GOOD_PACKETS_SPEC {}
#[doc = "`reset()` method sets TX_SINGLE_COLLISION_GOOD_PACKETS to value 0"]
impl crate::Resettable for TX_SINGLE_COLLISION_GOOD_PACKETS_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
extern crate ws;
use std::path::Path;
use std::thread;
use std::io::{Read, Write, self};
use std::net::TcpStream;
use std::sync::mpsc::Sender;
use std::sync::mpsc::Receiver;
use std::ops::Deref;
use std::collections::HashSet;
use std::sync::{RwLock, Arc, Mutex};
use std::collections::HashMap;
use encoding::{Encoding, EncoderTrap, DecoderTrap};
use encoding::all::WINDOWS_1251;
pub struct WebsocketServer {
sessions: HashMap<ws::util::Token, ws::Sender>,
mudstream: TcpStream
}
struct WsHandler {
ws: ws::Sender,
server: Arc<Mutex<WebsocketServer>>,
}
impl ws::Handler for WsHandler {
fn on_open(&mut self, shake: ws::Handshake) -> ws::Result<()> {
{
let mut serv = self.server.lock().unwrap();
serv.sessions.insert(self.ws.token(), self.ws.clone());
}
println!("Connected");
Ok(())
}
fn on_message(&mut self, msg : ws::Message) -> ws::Result<()> {
{
let mut serv = self.server.lock().unwrap();
serv.sendToMud(msg.to_string().replace("я","яя"));
}
Ok(())
}
fn on_error(&mut self, error: ws::Error) {
//TODO: log it
println!("Error: {}", error);
}
fn on_close(&mut self, code: ws::CloseCode, reason: &str) {
{
let mut serv = self.server.lock().unwrap();
serv.sessions.remove(&self.ws.token());
}
println!("Closing: {}", reason);
//start_webserver(self.receiver);
}
}
impl WebsocketServer {
pub fn new(stream: TcpStream) -> WebsocketServer {
WebsocketServer {
sessions: HashMap::new(),
mudstream: stream
}
}
pub fn sendToMud(&mut self, text: String) {
println!("Sending: {}", text);
self.mudstream.write(WINDOWS_1251.encode(&(text + "\n"), EncoderTrap::Ignore).unwrap().as_slice());
}
pub fn sendToAll(&self, text: String) {
{
for key in self.sessions.keys() {
self.sessions[key].send(text.clone());
}
}
}
}
pub fn start_webserver(server: Arc<Mutex<WebsocketServer>>) {
thread::spawn(move || {
println!("Listening on 3012");
ws::listen("localhost:3012", move|out| {
WsHandler {
server: server.clone(),
ws: out,
}
}).unwrap();
});
}
|
use std::collections::HashMap;
struct Game {
round: u32,
history: HashMap<u32, u32>,
last: u32,
}
impl Game {
fn new(start: &[u32]) -> Game {
// Insert all except last, last will be inserted when stepping.
let mut history = HashMap::new();
for (r, &n) in start.iter().take(start.len() - 1).enumerate() {
assert!(!history.contains_key(&n));
history.insert(n, r as u32 + 1 /* start at round 1 */);
}
Game {
round: start.len() as u32,
history,
last: *start.last().expect("Must have some input"),
}
}
fn step(&mut self) -> u32 {
// Check if `self.last` was already spoken and compute distance else speak `0`.
let new_last = if let Some(last_occured) = self.history.get(&self.last) {
self.round - last_occured
} else {
0
};
// Insert previous last into history.
self.history.insert(self.last, self.round);
// Advance last spoken.
self.last = new_last;
// Advance next round.
self.round += 1;
self.last
}
fn round(&self) -> u32 {
self.round
}
}
fn challenge1(input: &[u32]) -> u32 {
let mut g = Game::new(input);
// Step until one before round 2020.
for _ in g.round()..2020 - 1 {
g.step();
}
g.step()
}
fn challenge2(input: &[u32]) -> u32 {
let mut g = Game::new(input);
// Step until one before round 30000000.
for _ in g.round()..30000000 - 1 {
g.step();
}
g.step()
}
fn main() {
println!("{}", challenge1(&[1, 0, 15, 2, 10, 13]));
println!("{}", challenge2(&[1, 0, 15, 2, 10, 13]));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn check_challenge1() {
assert_eq!(challenge1(&[1, 0, 15, 2, 10, 13]), 211);
}
#[test]
fn check_challenge2() {
assert_eq!(challenge2(&[1, 0, 15, 2, 10, 13]), 2159626);
}
}
|
use tic_tac_toe::{GameState, Player};
use std::collections::HashMap;
use sdl2::event::Event;
use sdl2::gfx::primitives::DrawRenderer;
use sdl2::keyboard::Keycode;
use sdl2::pixels::Color;
use sdl2::rect::{Point, Rect};
use sdl2::render;
use nalgebra as na;
// Base constants
const MARGIN: u32 = 10;
const CELL_SIZE: u32 = 200;
const BORDER_WIDTH: u32 = 20;
// Derived constants
const CONTENT_SIZE: u32 = 3 * CELL_SIZE + 2 * BORDER_WIDTH;
const SCREEN_SIZE: u32 = CONTENT_SIZE + 2 * MARGIN;
fn get_rect(idx: u32) -> Rect {
let idx = idx as i32;
let (i, j) = (idx / 3, idx % 3);
Rect::new(
MARGIN as i32 + (CELL_SIZE + BORDER_WIDTH) as i32 * j,
MARGIN as i32 + (CELL_SIZE + BORDER_WIDTH) as i32 * i,
CELL_SIZE,
CELL_SIZE,
)
}
fn get_id(p: Point) -> Option<u32> {
for idx in 0..9 {
if get_rect(idx).contains_point(p) {
return Some(idx);
}
}
None
}
fn draw_grid<T: render::RenderTarget>(canvas: &mut render::Canvas<T>) -> Result<(), String> {
let grid_lines = [
Rect::new(
(MARGIN + CELL_SIZE) as i32,
MARGIN as i32,
BORDER_WIDTH,
CONTENT_SIZE,
),
Rect::new(
(MARGIN + BORDER_WIDTH + 2 * CELL_SIZE) as i32,
MARGIN as i32,
BORDER_WIDTH,
CONTENT_SIZE,
),
Rect::new(
MARGIN as i32,
(MARGIN + CELL_SIZE) as i32,
CONTENT_SIZE,
BORDER_WIDTH,
),
Rect::new(
MARGIN as i32,
(MARGIN + BORDER_WIDTH + 2 * CELL_SIZE) as i32,
CONTENT_SIZE,
BORDER_WIDTH,
),
];
let prev_col = canvas.draw_color();
canvas.set_draw_color(Color::RGB(0, 0, 0));
let result = canvas.fill_rects(&grid_lines);
canvas.set_draw_color(prev_col);
result
}
fn draw_nought<T: render::RenderTarget>(
canvas: &render::Canvas<T>,
center: Point,
) -> Result<(), String> {
let x = center.x() as i16;
let y = center.y() as i16;
let r1 = (CELL_SIZE / 3) as i16;
canvas.filled_circle(x, y, r1, Color::RGB(0, 0, 255))?;
let r2 = ((2 * CELL_SIZE) / 9) as i16;
canvas.filled_circle(x, y, r2, Color::RGB(255, 255, 255))?;
Ok(())
}
fn draw_cross<T: render::RenderTarget>(
canvas: &render::Canvas<T>,
center: Point,
) -> Result<(), String> {
let cross: Vec<_> = [
(-1.0, 6.0),
(-1.0, 1.0),
(-6.0, 1.0),
(-6.0, -1.0),
(-1.0, -1.0),
(-1.0, -6.0),
(1.0, -6.0),
(1.0, -1.0),
(6.0, -1.0),
(6.0, 1.0),
(1.0, 1.0),
(1.0, 6.0),
]
.iter()
.map(|(x, y)| {
let scale_factor = (CELL_SIZE as f32) / 18.0;
let u = na::Vector2::new(*x, *y);
let rot = na::Rotation2::new(std::f32::consts::PI / 4.0);
rot.transform_vector(&u) * scale_factor
+ na::Vector2::new(center.x() as f32, center.y() as f32)
})
.collect();
let vx: Vec<_> = cross.iter().map(|v| v.x.round() as i16).collect();
let vy: Vec<_> = cross.iter().map(|v| v.y.round() as i16).collect();
canvas.filled_polygon(&vx, &vy, Color::RGB(255, 0, 0))?;
Ok(())
}
fn main() {
// Initialize game state
let mut state = GameState::new();
let mut name = HashMap::new();
name.insert(Player::First, "Alice");
name.insert(Player::Second, "Bob");
// Initialize sdl2
let sdl_context = sdl2::init().unwrap();
let video_subsystem = sdl_context.video().unwrap();
let window = video_subsystem
.window("Tic-Tac-Toe", SCREEN_SIZE, SCREEN_SIZE)
.position_centered()
.build()
.unwrap();
let mut canvas = window.into_canvas().build().unwrap();
let mut event_pump = sdl_context.event_pump().unwrap();
'game_loop: loop {
// Get user input
for event in event_pump.poll_iter() {
match event {
Event::KeyDown {
keycode: Some(Keycode::Escape),
..
}
| Event::Quit { .. } => break 'game_loop,
Event::MouseButtonUp { x, y, .. } => {
if let Some(idx) = get_id(Point::new(x, y)) {
if state.make_move(idx) {
if let Some(winner) = state.winner {
println!("Game over! {} has won the game.", name[&winner]);
}
}
}
}
_ => (),
}
}
// Draw current state
canvas.set_draw_color(Color::RGB(255, 255, 255));
canvas.clear();
draw_grid(&mut canvas).unwrap();
for idx in 0..9 {
let p = get_rect(idx as u32).center();
let board = state.get_board();
match board[idx] {
Some(Player::First) => draw_nought(&canvas, p).unwrap(),
Some(Player::Second) => draw_cross(&canvas, p).unwrap(),
None => (),
}
}
canvas.present();
}
}
|
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::io::Read;
use std::io::SeekFrom;
use crate::gb;
pub struct Memory {
pub rom_bank0: Vec<u8>,
pub rom_bank1: Vec<u8>,
pub vram: Vec<u8>,
pub eram: Vec<u8>,
pub wram: Vec<u8>,
pub oam: Vec<u8>,
pub io: Vec<u8>,
pub hram: Vec<u8>,
pub interrupt_register: u8,
pub rom_low_bytes: Vec<u8>,
}
pub const ROM0_START: u16 = 0x0000;
pub const ROM0_END: u16 = 0x3FFF;
pub const ROM1_START: u16 = 0x4000;
pub const ROM1_END: u16 = 0x7FFF;
pub const VRAM_START: u16 = 0x8000;
pub const VRAM_END: u16 = 0x9FFF;
pub const ERAM_START: u16 = 0xA000;
pub const ERAM_END: u16 = 0xBFFF;
pub const WRAM_START: u16 = 0xC000;
pub const WRAM_END: u16 = 0xDFFF;
pub const OAM_START: u16 = 0xFE00;
pub const OAM_END: u16 = 0xFE9F;
pub const IO_START: u16 = 0xFF00;
pub const IO_END: u16 = 0xFF7F;
pub const HRAM_START: u16 = 0xFF80;
pub const HRAM_END: u16 = 0xFFFE;
pub const IR: u16 = 0xFFFF;
impl Memory {
pub fn initialize() -> Memory {
let bootrom_path = env::var("BOOTROM").unwrap();
let rom_path = env::var("ROM").unwrap();
let mut rom_bank0 = vec![0; (ROM0_END - ROM0_START + 1) as usize];
let mut rom_low_bytes = vec![0; 0x100];
File::open(bootrom_path)
.unwrap()
.read_exact(&mut rom_bank0.as_mut_slice()[0..=255])
.unwrap();
let mut rom = File::open(rom_path).unwrap();
rom.read_exact(&mut rom_low_bytes).unwrap();
rom.read_exact(&mut rom_bank0.as_mut_slice()[0x100..=(ROM0_END as usize)])
.unwrap();
let mut rom_bank1 = vec![0; (ROM1_END - ROM1_START + 1) as usize];
rom.read_exact(&mut rom_bank1).unwrap();
let vram = vec![0; (VRAM_END - VRAM_START + 1) as usize];
let eram = vec![0; (ERAM_END - ERAM_START + 1) as usize];
let wram = vec![0; (WRAM_END - WRAM_START + 1) as usize];
let oam = vec![0; (OAM_END - OAM_START + 1) as usize];
let mut io = vec![0; (IO_END - IO_START + 1) as usize];
io[0] = 0xCF;
let hram = vec![0; (HRAM_END - HRAM_START + 1) as usize];
let interrupt_register = 0;
Memory {
rom_bank0,
rom_bank1,
vram,
eram,
wram,
oam,
io,
hram,
interrupt_register,
rom_low_bytes,
}
}
pub fn read_byte(&self, address: u16) -> u8 {
// if address == 0xFF80 {
// println!("Reading from ff80h which has val {:#0x}", self.hram[0]);
// };
match address {
ROM0_START..=ROM0_END => self.rom_bank0[address as usize],
ROM1_START..=ROM1_END => self.rom_bank1[(address as usize) - 0x4000],
VRAM_START..=VRAM_END => self.vram[(address as usize) - 0x8000],
ERAM_START..=ERAM_END => self.eram[(address as usize) - 0xA000],
WRAM_START..=WRAM_END => self.wram[(address as usize) - 0xC000],
0xE000..=0xFDFF => 0xFF,
OAM_START..=OAM_END => self.oam[(address as usize) - 0xFE00],
0xFEA0..=0xFEFF => panic!(
"Address {:#0x} attempts to access prohibited region of memory",
address
),
IO_START..=IO_END => self.io[(address as usize) - 0xFF00],
HRAM_START..=HRAM_END => self.hram[(address as usize) - 0xFF80],
IR => self.interrupt_register,
}
}
pub fn read_2_bytes(&self, a: u16) -> u16 {
(self.read_byte(a) as u16) | (self.read_byte(a + 1) as u16) << 8
}
pub fn write_byte(&mut self, address: u16, value: u8) {
if address == 0xFF41 {
return;
};
match address {
ROM0_START..=ROM0_END => self.rom_bank0[address as usize] = value,
ROM1_START..=ROM1_END => self.rom_bank1[(address as usize) - 0x4000] = value,
VRAM_START..=VRAM_END => self.vram[(address as usize) - 0x8000] = value,
ERAM_START..=ERAM_END => self.eram[(address as usize) - 0xA000] = value,
WRAM_START..=WRAM_END => self.wram[(address as usize) - 0xC000] = value,
0xE000..=0xFDFF => {}
OAM_START..=OAM_END => self.oam[(address as usize) - 0xFE00] = value,
0xFEA0..=0xFEFF => {}
IO_START..=IO_END => match address {
gb::joypad => self.io[gb::joypad as usize - 0xFF00] |= value & 0x30,
gb::lcd_stat => self.io[gb::lcd_stat as usize - 0xFF00] |= value & 0xF8,
_ => self.io[(address as usize) - 0xFF00] = value,
},
HRAM_START..=HRAM_END => self.hram[(address as usize) - 0xFF80] = value,
IR => self.interrupt_register = value,
};
}
pub fn write_2_bytes(&mut self, a: u16, value: u16) {
self.write_byte(a + 1, value as u8);
self.write_byte(a, (value >> 8) as u8);
}
pub fn replace_bootrom(&mut self) {
self.rom_bank0
.splice(0..0x100, self.rom_low_bytes.as_slice().iter().cloned());
}
pub fn update_lcd_stat(&mut self, value: u8) {
self.io[gb::lcd_stat as usize - 0xFF00] = value
}
}
|
#[doc = "Reader of register IC_ENABLE_STATUS"]
pub type R = crate::R<u32, super::IC_ENABLE_STATUS>;
#[doc = "Slave Received Data Lost. This bit indicates if a Slave-Receiver operation has been aborted with at least one data byte received from an I2C transfer due to the setting bit 0 of IC_ENABLE from 1 to 0. When read as 1, DW_apb_i2c is deemed to have been actively engaged in an aborted I2C transfer (with matching address) and the data phase of the I2C transfer has been entered, even though a data byte has been responded with a NACK.\\n\\n Note: If the remote I2C master terminates the transfer with a STOP condition before the DW_apb_i2c has a chance to NACK a transfer, and IC_ENABLE\\[0\\]
has been set to 0, then this bit is also set to 1.\\n\\n When read as 0, DW_apb_i2c is deemed to have been disabled without being actively involved in the data phase of a Slave-Receiver transfer.\\n\\n Note: The CPU can safely read this bit when IC_EN (bit 0) is read as 0.\\n\\n Reset value: 0x0\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SLV_RX_DATA_LOST_A {
#[doc = "0: Slave RX Data is not lost"]
INACTIVE = 0,
#[doc = "1: Slave RX Data is lost"]
ACTIVE = 1,
}
impl From<SLV_RX_DATA_LOST_A> for bool {
#[inline(always)]
fn from(variant: SLV_RX_DATA_LOST_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `SLV_RX_DATA_LOST`"]
pub type SLV_RX_DATA_LOST_R = crate::R<bool, SLV_RX_DATA_LOST_A>;
impl SLV_RX_DATA_LOST_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> SLV_RX_DATA_LOST_A {
match self.bits {
false => SLV_RX_DATA_LOST_A::INACTIVE,
true => SLV_RX_DATA_LOST_A::ACTIVE,
}
}
#[doc = "Checks if the value of the field is `INACTIVE`"]
#[inline(always)]
pub fn is_inactive(&self) -> bool {
*self == SLV_RX_DATA_LOST_A::INACTIVE
}
#[doc = "Checks if the value of the field is `ACTIVE`"]
#[inline(always)]
pub fn is_active(&self) -> bool {
*self == SLV_RX_DATA_LOST_A::ACTIVE
}
}
#[doc = "Slave Disabled While Busy (Transmit, Receive). This bit indicates if a potential or active Slave operation has been aborted due to the setting bit 0 of the IC_ENABLE register from 1 to 0. This bit is set when the CPU writes a 0 to the IC_ENABLE register while:\\n\\n (a) DW_apb_i2c is receiving the address byte of the Slave-Transmitter operation from a remote master;\\n\\n OR,\\n\\n (b) address and data bytes of the Slave-Receiver operation from a remote master.\\n\\n When read as 1, DW_apb_i2c is deemed to have forced a NACK during any part of an I2C transfer, irrespective of whether the I2C address matches the slave address set in DW_apb_i2c (IC_SAR register) OR if the transfer is completed before IC_ENABLE is set to 0 but has not taken effect.\\n\\n Note: If the remote I2C master terminates the transfer with a STOP condition before the DW_apb_i2c has a chance to NACK a transfer, and IC_ENABLE\\[0\\]
has been set to 0, then this bit will also be set to 1.\\n\\n When read as 0, DW_apb_i2c is deemed to have been disabled when there is master activity, or when the I2C bus is idle.\\n\\n Note: The CPU can safely read this bit when IC_EN (bit 0) is read as 0.\\n\\n Reset value: 0x0\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SLV_DISABLED_WHILE_BUSY_A {
#[doc = "0: Slave is disabled when it is idle"]
INACTIVE = 0,
#[doc = "1: Slave is disabled when it is active"]
ACTIVE = 1,
}
impl From<SLV_DISABLED_WHILE_BUSY_A> for bool {
#[inline(always)]
fn from(variant: SLV_DISABLED_WHILE_BUSY_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `SLV_DISABLED_WHILE_BUSY`"]
pub type SLV_DISABLED_WHILE_BUSY_R = crate::R<bool, SLV_DISABLED_WHILE_BUSY_A>;
impl SLV_DISABLED_WHILE_BUSY_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> SLV_DISABLED_WHILE_BUSY_A {
match self.bits {
false => SLV_DISABLED_WHILE_BUSY_A::INACTIVE,
true => SLV_DISABLED_WHILE_BUSY_A::ACTIVE,
}
}
#[doc = "Checks if the value of the field is `INACTIVE`"]
#[inline(always)]
pub fn is_inactive(&self) -> bool {
*self == SLV_DISABLED_WHILE_BUSY_A::INACTIVE
}
#[doc = "Checks if the value of the field is `ACTIVE`"]
#[inline(always)]
pub fn is_active(&self) -> bool {
*self == SLV_DISABLED_WHILE_BUSY_A::ACTIVE
}
}
#[doc = "ic_en Status. This bit always reflects the value driven on the output port ic_en. - When read as 1, DW_apb_i2c is deemed to be in an enabled state. - When read as 0, DW_apb_i2c is deemed completely inactive. Note: The CPU can safely read this bit anytime. When this bit is read as 0, the CPU can safely read SLV_RX_DATA_LOST (bit 2) and SLV_DISABLED_WHILE_BUSY (bit 1).\\n\\n Reset value: 0x0\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum IC_EN_A {
#[doc = "0: I2C disabled"]
DISABLED = 0,
#[doc = "1: I2C enabled"]
ENABLED = 1,
}
impl From<IC_EN_A> for bool {
#[inline(always)]
fn from(variant: IC_EN_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `IC_EN`"]
pub type IC_EN_R = crate::R<bool, IC_EN_A>;
impl IC_EN_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> IC_EN_A {
match self.bits {
false => IC_EN_A::DISABLED,
true => IC_EN_A::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == IC_EN_A::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == IC_EN_A::ENABLED
}
}
impl R {
#[doc = "Bit 2 - Slave Received Data Lost. This bit indicates if a Slave-Receiver operation has been aborted with at least one data byte received from an I2C transfer due to the setting bit 0 of IC_ENABLE from 1 to 0. When read as 1, DW_apb_i2c is deemed to have been actively engaged in an aborted I2C transfer (with matching address) and the data phase of the I2C transfer has been entered, even though a data byte has been responded with a NACK.\\n\\n Note: If the remote I2C master terminates the transfer with a STOP condition before the DW_apb_i2c has a chance to NACK a transfer, and IC_ENABLE\\[0\\]
has been set to 0, then this bit is also set to 1.\\n\\n When read as 0, DW_apb_i2c is deemed to have been disabled without being actively involved in the data phase of a Slave-Receiver transfer.\\n\\n Note: The CPU can safely read this bit when IC_EN (bit 0) is read as 0.\\n\\n Reset value: 0x0"]
#[inline(always)]
pub fn slv_rx_data_lost(&self) -> SLV_RX_DATA_LOST_R {
SLV_RX_DATA_LOST_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 1 - Slave Disabled While Busy (Transmit, Receive). This bit indicates if a potential or active Slave operation has been aborted due to the setting bit 0 of the IC_ENABLE register from 1 to 0. This bit is set when the CPU writes a 0 to the IC_ENABLE register while:\\n\\n (a) DW_apb_i2c is receiving the address byte of the Slave-Transmitter operation from a remote master;\\n\\n OR,\\n\\n (b) address and data bytes of the Slave-Receiver operation from a remote master.\\n\\n When read as 1, DW_apb_i2c is deemed to have forced a NACK during any part of an I2C transfer, irrespective of whether the I2C address matches the slave address set in DW_apb_i2c (IC_SAR register) OR if the transfer is completed before IC_ENABLE is set to 0 but has not taken effect.\\n\\n Note: If the remote I2C master terminates the transfer with a STOP condition before the DW_apb_i2c has a chance to NACK a transfer, and IC_ENABLE\\[0\\]
has been set to 0, then this bit will also be set to 1.\\n\\n When read as 0, DW_apb_i2c is deemed to have been disabled when there is master activity, or when the I2C bus is idle.\\n\\n Note: The CPU can safely read this bit when IC_EN (bit 0) is read as 0.\\n\\n Reset value: 0x0"]
#[inline(always)]
pub fn slv_disabled_while_busy(&self) -> SLV_DISABLED_WHILE_BUSY_R {
SLV_DISABLED_WHILE_BUSY_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 0 - ic_en Status. This bit always reflects the value driven on the output port ic_en. - When read as 1, DW_apb_i2c is deemed to be in an enabled state. - When read as 0, DW_apb_i2c is deemed completely inactive. Note: The CPU can safely read this bit anytime. When this bit is read as 0, the CPU can safely read SLV_RX_DATA_LOST (bit 2) and SLV_DISABLED_WHILE_BUSY (bit 1).\\n\\n Reset value: 0x0"]
#[inline(always)]
pub fn ic_en(&self) -> IC_EN_R {
IC_EN_R::new((self.bits & 0x01) != 0)
}
}
|
use super::{Graph,Element,ElementType,SimResult};
use super::linalg::{Matrix,Vector,gaussian_elimination};
pub fn solve(gr: &Graph) -> SimResult
{
let (a,b) = build_eqns(gr);
// Solve Ax = b
let x = gaussian_elimination(&a, &b);
// Save results
let n = count_nets(gr);
let (v,i) = x.data.split_at(n);
SimResult {
v: v.to_vec(),
i: i.to_vec(),
}
}
fn build_eqns(gr: &Graph) -> (Matrix,Vector)
{
let m = gr.nodes.len();
let n = count_nets(gr);
let mut a = Matrix::new(m + n, n + m);
let mut b = Vector::new(m + n);
let mut prev: Option<&Element> = None;
for (i,elem) in gr.nodes.iter().enumerate()
{
let na = elem.nets[0] as usize;
let nb = elem.nets[1] as usize;
// Current flow / adjacency
a.data[m+na][n+i] += 1.0;
a.data[m+nb][n+i] -= 1.0;
// Voltage source
if elem.kind == ElementType::ConstantVoltage ||
elem.kind == ElementType::DependentVoltage
{
a.data[i][na] -= 1.0;
a.data[i][nb] += 1.0;
}
// Current source
if elem.kind == ElementType::ConstantCurrent ||
elem.kind == ElementType::DependentCurrent
{
a.data[i][n+i] = 1.0;
}
// Constant source
if elem.kind == ElementType::ConstantVoltage ||
elem.kind == ElementType::ConstantCurrent
{
b.data[i] = elem.value;
}
// Dependent source
if elem.kind == ElementType::DependentVoltage ||
elem.kind == ElementType::DependentCurrent
{
if let Some(ref_elem) = prev
{
let ref_na = ref_elem.nets[0] as usize;
let ref_nb = ref_elem.nets[1] as usize;
// Reference should be dummy
assert!(ref_elem.value == 0.0);
match ref_elem.kind
{
ElementType::ConstantCurrent =>
{
// Reference is open-circuit voltage
a.data[i][ref_na] += elem.value;
a.data[i][ref_nb] -= elem.value;
},
ElementType::ConstantVoltage =>
{
// Reference is short-circuit current
a.data[i][n+i-1] -= elem.value;
},
_ => panic!("Invalid dependent source reference")
}
}
else
{
panic!("Missing dependent source reference");
}
}
if elem.kind == ElementType::Resistor
{
a.data[i][na] -= 1.0;
a.data[i][nb] += 1.0;
a.data[i][n+i] = elem.value;
}
// Remember previous element
prev = Some(&elem);
}
// Replace node 0 current equation with V_0 = 0 reference
a.data[m] = vec![0.0; n + m];
a.data[m][0] = 1.0;
(a,b)
}
fn count_nets(gr: &Graph) -> usize
{
// Find highest numbered node
let max = gr.nodes.iter()
.map(|el| el.nets.iter()
.cloned()
.max()
.unwrap_or(0))
.max()
.unwrap_or(0) as usize;
max + 1
}
|
#[doc = "Reader of register RANGE_INTR_SET"]
pub type R = crate::R<u32, super::RANGE_INTR_SET>;
#[doc = "Writer for register RANGE_INTR_SET"]
pub type W = crate::W<u32, super::RANGE_INTR_SET>;
#[doc = "Register RANGE_INTR_SET `reset()`'s with value 0"]
impl crate::ResetValue for super::RANGE_INTR_SET {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `RANGE_SET`"]
pub type RANGE_SET_R = crate::R<u16, u16>;
#[doc = "Write proxy for field `RANGE_SET`"]
pub struct RANGE_SET_W<'a> {
w: &'a mut W,
}
impl<'a> RANGE_SET_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u16) -> &'a mut W {
self.w.bits = (self.w.bits & !0xffff) | ((value as u32) & 0xffff);
self.w
}
}
impl R {
#[doc = "Bits 0:15 - Write with '1' to set corresponding bit in interrupt request register."]
#[inline(always)]
pub fn range_set(&self) -> RANGE_SET_R {
RANGE_SET_R::new((self.bits & 0xffff) as u16)
}
}
impl W {
#[doc = "Bits 0:15 - Write with '1' to set corresponding bit in interrupt request register."]
#[inline(always)]
pub fn range_set(&mut self) -> RANGE_SET_W {
RANGE_SET_W { w: self }
}
}
|
use logos::{Logos, Lexer as LLexer};
#[derive(Logos, Clone, Debug, PartialEq)]
pub enum ObjectT {
#[token("'", priority = 5)]
Quote,
#[token("`", priority = 5)]
QuasiQuote,
#[token(",", priority = 5)]
Unquote,
#[token(",@", priority = 5)]
UnquoteSplice,
#[token("#t", priority = 5)]
True,
#[token("#f", priority = 5)]
False,
#[token("(", priority = 4)]
LBrace,
#[token(")", priority = 4)]
RBrace,
#[regex("-?([0-9]*\\.?[0-9]+)", |lex| lex.slice().parse(), priority = 3)]
Number(f64),
#[token("\"", priority = 2)]
StartString,
#[regex("[^'`,\"\\s\\(\\)][^\\s\\(\\)]*", |lex| lex.slice().to_string(), priority = 1)]
Symbol(String),
#[error]
#[regex(r"[ \t\n\f]+", logos::skip)]
Error,
}
#[derive(Logos, Clone, Debug, PartialEq)]
pub enum StringT {
#[error]
Error,
#[regex(r#"[^\\"]+"#, |lex| lex.slice().to_string())]
Text(String),
#[token("\"")]
EndString,
}
enum Modes<'a> {
Object(LLexer<'a, ObjectT>),
String(LLexer<'a, StringT>),
}
pub enum Tokens {
Object(ObjectT),
String(StringT),
}
pub struct Lexer<'a> {
mode: Modes<'a>,
}
impl<'a> Iterator for Lexer<'a> {
type Item = Tokens;
fn next(&mut self) -> Option<Self::Item> {
match &mut self.mode {
Modes::Object(lex) => {
let t = lex.next();
if t == Some(ObjectT::StartString) {
self.mode = Modes::String(lex.to_owned().morph());
}
t.map(Tokens::Object)
},
Modes::String(lex) => {
let t = lex.next();
if t == Some(StringT::EndString) {
self.mode = Modes::Object(lex.to_owned().morph());
}
t.map(Tokens::String)
}
}
}
}
impl<'a> Lexer<'a> {
pub fn new(input: &str) -> Lexer {
Lexer {
mode: Modes::Object(ObjectT::lexer(input))
}
}
pub fn span(&self) -> (usize, usize) {
match &self.mode {
Modes::Object(lex) => (lex.span().start, lex.span().end),
Modes::String(lex) => (lex.span().start, lex.span().end),
}
}
}
|
/// An enum to represent all characters in the Lydian block.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum Lydian {
/// \u{10920}: '𐤠'
LetterA,
/// \u{10921}: '𐤡'
LetterB,
/// \u{10922}: '𐤢'
LetterG,
/// \u{10923}: '𐤣'
LetterD,
/// \u{10924}: '𐤤'
LetterE,
/// \u{10925}: '𐤥'
LetterV,
/// \u{10926}: '𐤦'
LetterI,
/// \u{10927}: '𐤧'
LetterY,
/// \u{10928}: '𐤨'
LetterK,
/// \u{10929}: '𐤩'
LetterL,
/// \u{1092a}: '𐤪'
LetterM,
/// \u{1092b}: '𐤫'
LetterN,
/// \u{1092c}: '𐤬'
LetterO,
/// \u{1092d}: '𐤭'
LetterR,
/// \u{1092e}: '𐤮'
LetterSs,
/// \u{1092f}: '𐤯'
LetterT,
/// \u{10930}: '𐤰'
LetterU,
/// \u{10931}: '𐤱'
LetterF,
/// \u{10932}: '𐤲'
LetterQ,
/// \u{10933}: '𐤳'
LetterS,
/// \u{10934}: '𐤴'
LetterTt,
/// \u{10935}: '𐤵'
LetterAn,
/// \u{10936}: '𐤶'
LetterEn,
/// \u{10937}: '𐤷'
LetterLy,
/// \u{10938}: '𐤸'
LetterNn,
/// \u{10939}: '𐤹'
LetterC,
}
impl Into<char> for Lydian {
fn into(self) -> char {
match self {
Lydian::LetterA => '𐤠',
Lydian::LetterB => '𐤡',
Lydian::LetterG => '𐤢',
Lydian::LetterD => '𐤣',
Lydian::LetterE => '𐤤',
Lydian::LetterV => '𐤥',
Lydian::LetterI => '𐤦',
Lydian::LetterY => '𐤧',
Lydian::LetterK => '𐤨',
Lydian::LetterL => '𐤩',
Lydian::LetterM => '𐤪',
Lydian::LetterN => '𐤫',
Lydian::LetterO => '𐤬',
Lydian::LetterR => '𐤭',
Lydian::LetterSs => '𐤮',
Lydian::LetterT => '𐤯',
Lydian::LetterU => '𐤰',
Lydian::LetterF => '𐤱',
Lydian::LetterQ => '𐤲',
Lydian::LetterS => '𐤳',
Lydian::LetterTt => '𐤴',
Lydian::LetterAn => '𐤵',
Lydian::LetterEn => '𐤶',
Lydian::LetterLy => '𐤷',
Lydian::LetterNn => '𐤸',
Lydian::LetterC => '𐤹',
}
}
}
impl std::convert::TryFrom<char> for Lydian {
type Error = ();
fn try_from(c: char) -> Result<Self, Self::Error> {
match c {
'𐤠' => Ok(Lydian::LetterA),
'𐤡' => Ok(Lydian::LetterB),
'𐤢' => Ok(Lydian::LetterG),
'𐤣' => Ok(Lydian::LetterD),
'𐤤' => Ok(Lydian::LetterE),
'𐤥' => Ok(Lydian::LetterV),
'𐤦' => Ok(Lydian::LetterI),
'𐤧' => Ok(Lydian::LetterY),
'𐤨' => Ok(Lydian::LetterK),
'𐤩' => Ok(Lydian::LetterL),
'𐤪' => Ok(Lydian::LetterM),
'𐤫' => Ok(Lydian::LetterN),
'𐤬' => Ok(Lydian::LetterO),
'𐤭' => Ok(Lydian::LetterR),
'𐤮' => Ok(Lydian::LetterSs),
'𐤯' => Ok(Lydian::LetterT),
'𐤰' => Ok(Lydian::LetterU),
'𐤱' => Ok(Lydian::LetterF),
'𐤲' => Ok(Lydian::LetterQ),
'𐤳' => Ok(Lydian::LetterS),
'𐤴' => Ok(Lydian::LetterTt),
'𐤵' => Ok(Lydian::LetterAn),
'𐤶' => Ok(Lydian::LetterEn),
'𐤷' => Ok(Lydian::LetterLy),
'𐤸' => Ok(Lydian::LetterNn),
'𐤹' => Ok(Lydian::LetterC),
_ => Err(()),
}
}
}
impl Into<u32> for Lydian {
fn into(self) -> u32 {
let c: char = self.into();
let hex = c
.escape_unicode()
.to_string()
.replace("\\u{", "")
.replace("}", "");
u32::from_str_radix(&hex, 16).unwrap()
}
}
impl std::convert::TryFrom<u32> for Lydian {
type Error = ();
fn try_from(u: u32) -> Result<Self, Self::Error> {
if let Ok(c) = char::try_from(u) {
Self::try_from(c)
} else {
Err(())
}
}
}
impl Iterator for Lydian {
type Item = Self;
fn next(&mut self) -> Option<Self> {
let index: u32 = (*self).into();
use std::convert::TryFrom;
Self::try_from(index + 1).ok()
}
}
impl Lydian {
/// The character with the lowest index in this unicode block
pub fn new() -> Self {
Lydian::LetterA
}
/// The character's name, in sentence case
pub fn name(&self) -> String {
let s = std::format!("Lydian{:#?}", self);
string_morph::to_sentence_case(&s)
}
}
|
use syn::parse::{Parse, ParseStream, Result};
mod glsl;
use glsl::{Glsl, GlslLine};
mod yasl_block;
mod yasl_expr;
mod yasl_file;
mod yasl_ident;
mod yasl_item;
mod yasl_stmt;
mod yasl_type;
use yasl_file::YaslFile;
pub struct Shader {
pub glsl: String,
pub sourcemap: Vec<GlslLine>,
}
impl Parse for Shader {
fn parse(input: ParseStream) -> Result<Self> {
let version = "#version 450\n";
let mut out = String::new();
out += version;
let file = YaslFile::parse(input)?;
// println!("{:#?}", file);
let glsl: Glsl = file.into();
// println!("{:#?}", glsl);
let glsl = if let Glsl::Fragment(f) = glsl {
f
} else {
panic!("Expected Fragment On TopLevel");
};
out += &glsl.to_string();
out += "\n";
out += "void main(){ yasl_main(); }";
let sourcemap = glsl.squash();
println!("{}", out);
Ok(Self {
glsl: out,
sourcemap,
})
}
}
|
fn main() {
println!("Hello, world!");
let x: i64 = 257;
println!("{}!", x);
another_function(x as i8);
let x = 127;
let y = 3.0;
second_fn(x, y);
let sum: i32 = {
let x: i32 = 5;
let y: i32 = 7;
x + y
};
println!("The sum is: {}!", sum);
let x: i64 = third_fn(6) as i64;
println!("the x is: {}!", x);
}
fn another_function(x: i8) {
println!("another function.");
println!("The value of x is: {}!", x);
}
fn second_fn(x: i8, y: f64) {
println!("x is {}!, y is {}!", x, y);
}
fn third_fn(x: i32) -> i32 {
x + 1
}
|
use std::slice;
use libc::c_uint;
use std::borrow::Cow;
use ::ffi;
use ::ffi::*;
use traits::{Named, FromRaw};
use mesh::*;
use ::scene::*;
pub struct Node<'a> {
raw: &'a ffi::AiNode
}
impl<'a> Named<'a> for Node<'a> {
#[inline]
fn name(&self) -> Cow<'a, str> {
self.raw.name.to_string_lossy()
}
}
impl<'a> FromRaw<'a, Node<'a>> for Node<'a> {
type Raw = *const ffi::AiNode;
#[inline(always)]
fn from_raw(raw: &'a Self::Raw) -> Node<'a> {
Node { raw: unsafe { raw.as_ref().expect("Node pointer provided by Assimp was NULL") } }
}
}
impl<'a> Node<'a> {
/// Returns the transformation matrix of this node in the scene
#[inline(always)]
pub fn transformation(&self) -> &AiMatrix4x4 {
&self.raw.transformation
}
/// If the node has a parent, get it.
pub fn parent(&self) -> Option<Node<'a>> {
if self.raw.parent.is_null() { None } else {
Some(Node { raw: unsafe { &*self.raw.parent } })
}
}
impl_optional_iterator!(children, children, num_children, Node, {
/// Returns an iterator to the children of this node
});
impl_optional_slice!(meshes, meshes, num_meshes, c_uint, {
/// Returns the mesh indices for this node.
});
/// Maps the mesh indices of this node to the meshes in a scene.
pub fn meshes_from_scene(&self, scene: &'a Scene<'a>) -> Option<Box<Iterator<Item=Mesh<'a>> + 'a>> {
if let Some(mesh_indices) = self.meshes() {
Some(Box::new(mesh_indices
.iter()
.filter_map(move |index| scene.mesh(*index as usize))))
} else {
None
}
}
} |
use lexer_lib as lexer;
use parser_lib as parser;
use gen_lib as gen;
use lib::Pprint;
use std::env;
use std::io::{stdin, stdout, Write};
use std::process::Command;
use std::os::unix::process::CommandExt;
fn get_args() -> (String, String) {
let mut path = String::new();
let mut args = env::args_os();
if args.len() > 1 {
path = args.nth(1).expect("Compiler: Invalid arg[1]").into_string().expect("Compiler: Invalid arg[1]").clone();
} else {
print!("File name: ");
stdout().flush().unwrap();
stdin().read_line(&mut path).expect("Compiler: Invalid file name.");
}
// path = .c ; filename = .s
path = path.trim().to_string();
let filename = path.replace(".c", ".s");
(path, filename)
}
fn gcc(filename: & String) {
let out = filename.replace(".s", "");
Command::new("gcc")
.uid(0)
.arg("-masm=intel")
.arg(&filename)
.arg("-o")
.arg(&out)
.status().unwrap();
}
fn main() {
// let valid = vec!["../../test/stage_2/valid/bitwise.c", "../../test/stage_2/valid/bitwise_zero.c",
// "../../test/stage_2/valid/neg.c", "../../test/stage_2/valid/nested_ops_2.c",
// "../../test/stage_2/valid/nested_ops.c", "../../test/stage_2/valid/not_five.c",
// "../../test/stage_2/valid/not_zero.c"];
let (path, filename) = get_args();
let token_vec = lexer::lex(&path);
// Pprint::print_token(&token_vec);
let ast = parser::parse(token_vec, &path);
// Pprint::print_ast(&ast, 2);
gen::gen(&ast, &filename);
// Pprint::print_asm(&filename);
gcc(&filename);
} |
// Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
use crate::{
field::{FieldElement, StarkField},
utils::log2,
};
use utils::{collections::Vec, iterators::*, rayon, uninit_vector};
// POLYNOMIAL EVALUATION
// ================================================================================================
/// Evaluates polynomial `p` using FFT algorithm; the evaluation is done in-place, meaning
/// `p` is updated with results of the evaluation.
pub fn evaluate_poly<B: StarkField, E: FieldElement<BaseField = B>>(p: &mut [E], twiddles: &[B]) {
split_radix_fft(p, twiddles);
permute(p);
}
/// Evaluates polynomial `p` using FFT algorithm and returns the result. The polynomial is
/// evaluated over domain specified by `twiddles`, expanded by the `blowup_factor`, and shifted
/// by the `domain_offset`.
pub fn evaluate_poly_with_offset<B: StarkField, E: FieldElement<BaseField = B>>(
p: &[E],
twiddles: &[B],
domain_offset: B,
blowup_factor: usize,
) -> Vec<E> {
let domain_size = p.len() * blowup_factor;
let g = B::get_root_of_unity(log2(domain_size));
let mut result = unsafe { uninit_vector(domain_size) };
result
.as_mut_slice()
.par_chunks_mut(p.len())
.enumerate()
.for_each(|(i, chunk)| {
let idx = super::permute_index(blowup_factor, i) as u64;
let offset = E::from(g.exp(idx.into()) * domain_offset);
clone_and_shift(p, chunk, offset);
split_radix_fft(chunk, twiddles);
});
permute(&mut result);
result
}
// POLYNOMIAL INTERPOLATION
// ================================================================================================
/// Uses FFT algorithm to interpolate a polynomial from provided `values`; the interpolation
/// is done in-place, meaning `values` are updated with polynomial coefficients.
pub fn interpolate_poly<B, E>(v: &mut [E], inv_twiddles: &[B])
where
B: StarkField,
E: FieldElement<BaseField = B>,
{
split_radix_fft(v, inv_twiddles);
let inv_length = E::inv((v.len() as u64).into());
v.par_iter_mut().for_each(|e| *e *= inv_length);
permute(v);
}
/// Uses FFT algorithm to interpolate a polynomial from provided `values` over the domain defined
/// by `inv_twiddles` and offset by `domain_offset` factor.
pub fn interpolate_poly_with_offset<B, E>(values: &mut [E], inv_twiddles: &[B], domain_offset: B)
where
B: StarkField,
E: FieldElement<BaseField = B>,
{
split_radix_fft(values, inv_twiddles);
permute(values);
let domain_offset = E::inv(domain_offset.into());
let inv_len = E::inv((values.len() as u64).into());
let batch_size = values.len() / rayon::current_num_threads().next_power_of_two();
values
.par_chunks_mut(batch_size)
.enumerate()
.for_each(|(i, batch)| {
let mut offset = domain_offset.exp(((i * batch_size) as u64).into()) * inv_len;
for coeff in batch.iter_mut() {
*coeff = *coeff * offset;
offset = offset * domain_offset;
}
});
}
// PERMUTATIONS
// ================================================================================================
pub fn permute<E: FieldElement>(v: &mut [E]) {
let n = v.len();
let num_batches = rayon::current_num_threads().next_power_of_two();
let batch_size = n / num_batches;
rayon::scope(|s| {
for batch_idx in 0..num_batches {
// create another mutable reference to the slice of values to use in a new thread; this
// is OK because we never write the same positions in the slice from different threads
let values = unsafe { &mut *(&mut v[..] as *mut [E]) };
s.spawn(move |_| {
let batch_start = batch_idx * batch_size;
let batch_end = batch_start + batch_size;
for i in batch_start..batch_end {
let j = super::permute_index(n, i);
if j > i {
values.swap(i, j);
}
}
});
}
});
}
// SPLIT-RADIX FFT
// ================================================================================================
/// In-place recursive FFT with permuted output.
/// Adapted from: https://github.com/0xProject/OpenZKP/tree/master/algebra/primefield/src/fft
pub(super) fn split_radix_fft<B: StarkField, E: FieldElement<BaseField = B>>(
values: &mut [E],
twiddles: &[B],
) {
// generator of the domain should be in the middle of twiddles
let n = values.len();
let g = E::from(twiddles[twiddles.len() / 2]);
debug_assert_eq!(g.exp((n as u32).into()), E::ONE);
let inner_len = 1_usize << (log2(n) / 2);
let outer_len = n / inner_len;
let stretch = outer_len / inner_len;
debug_assert!(outer_len == inner_len || outer_len == 2 * inner_len);
debug_assert_eq!(outer_len * inner_len, n);
// transpose inner x inner x stretch square matrix
transpose_square_stretch(values, inner_len, stretch);
// apply inner FFTs
values
.par_chunks_mut(outer_len)
.for_each(|row| super::serial::fft_in_place(row, &twiddles, stretch, stretch, 0));
// transpose inner x inner x stretch square matrix
transpose_square_stretch(values, inner_len, stretch);
// apply outer FFTs
values
.par_chunks_mut(outer_len)
.enumerate()
.for_each(|(i, row)| {
if i > 0 {
let i = super::permute_index(inner_len, i);
let inner_twiddle = g.exp((i as u32).into());
let mut outer_twiddle = inner_twiddle;
for element in row.iter_mut().skip(1) {
*element = *element * outer_twiddle;
outer_twiddle = outer_twiddle * inner_twiddle;
}
}
super::serial::fft_in_place(row, &twiddles, 1, 1, 0)
});
}
// TRANSPOSING
// ================================================================================================
fn transpose_square_stretch<T>(matrix: &mut [T], size: usize, stretch: usize) {
assert_eq!(matrix.len(), size * size * stretch);
match stretch {
1 => transpose_square_1(matrix, size),
2 => transpose_square_2(matrix, size),
_ => unimplemented!("only stretch sizes 1 and 2 are supported"),
}
}
fn transpose_square_1<T>(matrix: &mut [T], size: usize) {
debug_assert_eq!(matrix.len(), size * size);
if size % 2 != 0 {
unimplemented!("odd sizes are not supported");
}
// iterate over upper-left triangle, working in 2x2 blocks
for row in (0..size).step_by(2) {
let i = row * size + row;
matrix.swap(i + 1, i + size);
for col in (row..size).step_by(2).skip(1) {
let i = row * size + col;
let j = col * size + row;
matrix.swap(i, j);
matrix.swap(i + 1, j + size);
matrix.swap(i + size, j + 1);
matrix.swap(i + size + 1, j + size + 1);
}
}
}
fn transpose_square_2<T>(matrix: &mut [T], size: usize) {
debug_assert_eq!(matrix.len(), 2 * size * size);
// iterate over upper-left triangle, working in 1x2 blocks
for row in 0..size {
for col in (row..size).skip(1) {
let i = (row * size + col) * 2;
let j = (col * size + row) * 2;
matrix.swap(i, j);
matrix.swap(i + 1, j + 1);
}
}
}
// HELPER FUNCTIONS
// ================================================================================================
fn clone_and_shift<E: FieldElement>(source: &[E], destination: &mut [E], offset: E) {
let batch_size = source.len() / rayon::current_num_threads().next_power_of_two();
source
.par_chunks(batch_size)
.zip(destination.par_chunks_mut(batch_size))
.enumerate()
.for_each(|(i, (source, destination))| {
let mut factor = offset.exp(((i * batch_size) as u64).into());
for (s, d) in source.iter().zip(destination.iter_mut()) {
*d = *s * factor;
factor = factor * offset;
}
});
}
|
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use anyhow::Result;
use starcoin_crypto::HashValue;
use starcoin_state_api::{ChainState, ChainStateReader};
use starcoin_types::{
account_address::AccountAddress,
block::{Block, BlockHeader, BlockInfo, BlockNumber, BlockState, BlockTemplate},
transaction::{SignedUserTransaction, Transaction, TransactionInfo},
U256,
};
/// TODO: figure out a better place for it.
#[derive(Clone, Debug)]
pub struct ExcludedTxns {
pub discarded_txns: Vec<SignedUserTransaction>,
pub untouched_txns: Vec<SignedUserTransaction>,
}
pub trait ChainReader {
fn head_block(&self) -> Block;
fn current_header(&self) -> BlockHeader;
fn get_header(&self, hash: HashValue) -> Result<Option<BlockHeader>>;
fn get_header_by_number(&self, number: BlockNumber) -> Result<Option<BlockHeader>>;
fn get_block_by_number(&self, number: BlockNumber) -> Result<Option<Block>>;
/// Get latest `count` blocks before `number`. if `number` is absent, use head block number.
fn get_blocks_by_number(&self, number: Option<BlockNumber>, count: u64) -> Result<Vec<Block>>;
fn get_block(&self, hash: HashValue) -> Result<Option<Block>>;
fn get_transaction(&self, hash: HashValue) -> Result<Option<Transaction>>;
/// get txn info at version in main chain.
fn get_transaction_info_by_version(&self, version: u64) -> Result<Option<TransactionInfo>>;
fn create_block_template(
&self,
author: AccountAddress,
auth_key_prefix: Option<Vec<u8>>,
parent_hash: Option<HashValue>,
user_txns: Vec<SignedUserTransaction>,
) -> Result<(BlockTemplate, ExcludedTxns)>;
fn chain_state_reader(&self) -> &dyn ChainStateReader;
fn get_block_info(&self, block_id: Option<HashValue>) -> Result<Option<BlockInfo>>;
fn get_total_difficulty(&self) -> Result<U256>;
fn exist_block(&self, block_id: HashValue) -> bool;
}
pub trait ChainWriter {
/// execute and insert block to current chain.
fn apply(&mut self, block: Block) -> Result<bool>;
/// execute and insert block to current chain.
fn commit(
&mut self,
block: Block,
block_info: BlockInfo,
block_state: BlockState,
) -> Result<()>;
fn chain_state(&mut self) -> &dyn ChainState;
}
/// `Chain` is a trait that defines a single Chain.
pub trait Chain: ChainReader + ChainWriter {}
|
use amethyst::{
ecs::prelude::{Entities, Entity, Join, ReadExpect, ReadStorage, System, WriteStorage},
renderer::SpriteRender,
};
use crate::{
components::{Sprite, Sprites},
resources::SpriteResource,
};
pub struct SpriteSystem;
impl<'s> System<'s> for SpriteSystem {
type SystemData = (
Entities<'s>,
ReadStorage<'s, Sprite>,
WriteStorage<'s, SpriteRender>,
ReadExpect<'s, SpriteResource>,
);
fn run(&mut self, (entities, sprites, mut sprite_renders, sprite_resource): Self::SystemData) {
let mut sprites_to_insert: Vec<(Entity, SpriteRender)> = vec![];
for (entity, sprite, _) in (&entities, &sprites, !&sprite_renders).join() {
let sprite_sheet = sprite_resource.sprite_sheet.clone();
// Attach the sprite according to the sprites enum.
match sprite.sprite {
Sprites::Worker => {
sprites_to_insert.push((
entity,
SpriteRender {
sprite_sheet: sprite_sheet,
sprite_number: 0,
},
));
}
}
}
for (entity, sprite_render) in sprites_to_insert {
sprite_renders.insert(entity, sprite_render).unwrap();
}
}
}
|
extern crate crossbeam_channel;
use crossbeam_channel::{Sender, Receiver};
#[derive(Debug, Clone)]
pub struct Phone<S, R> {
sender: Sender<S>,
receiver: Receiver<R>,
}
impl<S, R> Phone<S, R> {
pub fn send(&self, msg: S) {
self.sender.send(msg)
}
pub fn recv(&self) -> Option<R> {
self.receiver.recv()
}
pub fn try_recv(&self) -> Option<R> {
self.receiver.try_recv()
}
pub fn sender(&self) -> &Sender<S> {
&self.sender
}
pub fn receiver(&self) -> &Receiver<R> {
&self.receiver
}
}
pub fn bounded<S, R>(cap: usize) -> (Phone<S, R>, Phone<R, S>) {
let (sender1, receiver1) = crossbeam_channel::bounded(cap);
let (sender2, receiver2) = crossbeam_channel::bounded(cap);
(
Phone {sender: sender1, receiver: receiver2},
Phone {sender: sender2, receiver: receiver1},
)
}
pub fn unbounded<S, R>() -> (Phone<S, R>, Phone<R, S>) {
let (sender1, receiver1) = crossbeam_channel::unbounded();
let (sender2, receiver2) = crossbeam_channel::unbounded();
(
Phone {sender: sender1, receiver: receiver2},
Phone {sender: sender2, receiver: receiver1},
)
}
|
pub(crate) const USAGE_MSG: &str = "usage: visudo [-chqsV] [[-f] sudoers ]";
const DESCRIPTOR: &str = "visudo - safely edit the sudoers file";
const HELP_MSG: &str = "Options:
-c, --check check-only mode
-f, --file=sudoers specify sudoers file location
-h, --help display help message and exit
-I, --no-includes do not edit include files
-q, --quiet less verbose (quiet) syntax error messages
-s, --strict strict syntax checking
-V, --version display version information and exit
";
pub(crate) fn long_help_message() -> String {
format!("{USAGE_MSG}\n\n{DESCRIPTOR}\n\n{HELP_MSG}")
}
|
use crate::{error::ValueError, eval::Expr, EvalError};
use gc::{Finalize, Gc, Trace};
use std::{
collections::HashMap,
fmt::{Debug, Display},
};
#[derive(Clone, Trace, Finalize)]
pub enum NixValue {
Map(HashMap<String, Gc<Expr>>),
#[allow(dead_code)] // TODO: implement parsing for strings
Str(String),
Bool(bool),
Float(f64),
Integer(i64),
Null,
}
impl NixValue {
pub fn type_name(&self) -> String {
match self {
NixValue::Map(_) => "attribute set",
NixValue::Str(_) => "string",
NixValue::Bool(_) => "bool",
NixValue::Float(_) => "float",
NixValue::Integer(_) => "integer",
NixValue::Null => "null",
}
.to_string()
}
pub fn as_map(&self) -> Result<HashMap<String, Gc<Expr>>, EvalError> {
match self {
NixValue::Map(x) => Ok(x.clone()),
_ => Err(EvalError::Value(ValueError::TypeError(format!(
"expected map, got {}",
self.type_name()
)))),
}
}
pub fn as_str(&self) -> Result<String, EvalError> {
match self {
NixValue::Str(x) => Ok(x.clone()),
_ => Err(EvalError::Value(ValueError::TypeError(format!(
"expected string, got {}",
self.type_name()
)))),
}
}
pub fn as_bool(&self) -> Result<bool, EvalError> {
match self {
NixValue::Bool(x) => Ok(*x),
_ => Err(EvalError::Value(ValueError::TypeError(format!(
"expected bool, got {}",
self.type_name()
)))),
}
}
#[allow(dead_code)] // this function is used by tests
pub fn as_int(&self) -> Result<i64, EvalError> {
match self {
NixValue::Integer(x) => Ok(*x),
_ => Err(EvalError::Value(ValueError::TypeError(format!(
"expected int, got {}",
self.type_name()
)))),
}
}
#[allow(dead_code)] // this function is used by tests
pub fn as_float(&self) -> Result<f64, EvalError> {
match self {
NixValue::Float(x) => Ok(*x),
_ => Err(EvalError::Value(ValueError::TypeError(format!(
"expected float, got {}",
self.type_name()
)))),
}
}
pub fn format_markdown(&self) -> String {
use NixValue::*;
match self {
Str(_) | Bool(_) | Float(_) | Integer(_) | Null => format!("```nix\n{}\n```", self),
Map(_) => format!("```text\n{}\n```", self),
}
}
}
/// Maximum number of keys to show when displaying attribute sets in tooltips.
const MAX_DISPLAY_KEYS: usize = 5;
impl Display for NixValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
NixValue::Str(x) => write!(f, "{:?}", x),
NixValue::Bool(x) => write!(f, "{}", x),
// TODO: format nicely like `nix repl`
NixValue::Float(x) => write!(f, "{}", x),
NixValue::Integer(x) => write!(f, "{}", x),
NixValue::Null => write!(f, "null"),
NixValue::Map(map) => {
let mut keys = map
.keys()
.take(MAX_DISPLAY_KEYS)
.cloned()
.collect::<Vec<_>>();
// Sorting a random subset of attributes would
// confuse users who think that we're showing
// the first MAX_DISPLAY_KEYS values *after*
// sorting, instead of showing a sorted random
// subset.
if map.keys().len() <= MAX_DISPLAY_KEYS {
keys.sort();
}
let mut body = keys.join(", ");
if map.keys().len() > MAX_DISPLAY_KEYS {
body.push_str(", ...");
}
write!(f, "{{ {} }}", body)
}
}
}
}
impl Debug for NixValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Display::fmt(self, f)
}
}
|
pub fn is_interleave(s1: String, s2: String, s3: String) -> bool {
let s1: Vec<char> = s1.chars().collect();
let s2: Vec<char> = s2.chars().collect();
let s3: Vec<char> = s3.chars().collect();
let n1 = s1.len();
let n2 = s2.len();
if n1 + n2 != s3.len() {
return false
}
let mut partial_interleaving = vec![vec![None; n2+1]; n1+1];
partial_interleaving[0][0] = Some(true);
let mut match_partial_s1 = true;
for i in 0..n1 {
if match_partial_s1 && s1[i] != s3[i] {
match_partial_s1 = false;
}
partial_interleaving[i+1][0] = Some(match_partial_s1);
}
let mut match_partial_s2 = true;
for j in 0..n2 {
if match_partial_s2 && s2[j] != s3[j] {
match_partial_s2 = false;
}
partial_interleaving[0][j+1] = Some(match_partial_s2);
}
fn core(i: usize, j: usize, s1: &[char], s2: &[char], s3: &[char], partial_interleaving: &mut Vec<Vec<Option<bool>>>) -> bool {
match partial_interleaving[i][j] {
Some(b) => b,
None => {
let b = (s1[i-1] == s3[i+j-1] && core(i-1, j, s1, s2, s3, partial_interleaving)) || (s2[j-1] == s3[i+j-1] && core(i, j-1, s1, s2, s3, partial_interleaving));
partial_interleaving[i][j] = Some(b);
b
}
}
}
core(n1, n2, s1.as_slice(), s2.as_slice(), s3.as_slice(), &mut partial_interleaving)
} |
extern crate ndarray;
pub mod levenshtein;
|
mod assets;
mod map;
pub use assets::MapAssetsListener;
pub use map::{MapEvents, MapEventsListener};
|
//! The simple python packaging tool ✨
#![deny(unsafe_code)]
#![deny(missing_docs)]
#![feature(format_args_nl)]
pub(crate) mod log;
mod errors;
mod init;
mod package;
pub use errors::{Error, Result};
pub use package::{Package, PackageId};
use sqlx::SqlitePool;
use std::{env, process};
const DEFAULT_LOCKFILE: &str = "sqlite://nakes.lock";
/// Small integrated argument parser, this enum represents all possible commands
#[derive(Debug)]
enum ArgParse {
Init,
Install,
Uninstall,
}
/// Extra metadata for [ArgParse] enum
#[derive(Debug)]
struct ArgParseMeta {
lockfile: Option<String>,
}
impl ArgParse {
fn launch() -> (Self, ArgParseMeta) {
let args: Vec<String> = env::args().collect();
let get_arg_data = |name| {
let ours = format!("--{}", name);
let pos = match args.iter().position(|arg| arg == &ours) {
Some(val) => val + 1,
None => return None,
};
if args.len() < pos {
eprintln!("{}No data given for {} argument", Self::err_msg(), ours);
process::exit(1);
} else if args[pos].starts_with("-") {
eprintln!(
"{}Data for {} argument is an argument itself",
Self::err_msg(),
ours
);
process::exit(1);
}
Some(args[pos].clone())
};
if args.len() < 2 {
eprintln!("{}Too few arguments", Self::err_msg());
process::exit(1);
} else if args.contains(&"--help".to_string()) {
println!("{}", Self::help());
process::exit(0);
}
let command = match args[1].as_str() {
"init" => ArgParse::Init,
"install" => ArgParse::Install,
"uninstall" | "remove" => ArgParse::Uninstall,
unknown => {
eprintln!("{}Unknown '{}' command", Self::err_msg(), unknown);
process::exit(1)
}
};
let args = ArgParseMeta {
lockfile: get_arg_data("lockfile"),
};
(command, args)
}
fn help() -> String {
const CLI_USAGE: &str = "nakes [COMMAND] [OPTIONS]";
const CLI_DESCRIPTION: &str = "the simple python packaging tool ✨";
format!("Usage: {}\n\nnakes\n {}\n\nCOMMANDS:\n init creates a new, empty project\n install [pkg] installs a package to venv\n uninstall [pkg] removes a package from venv\n help shows this message\n\nOPTIONS:\n --lockfile [uri] custom lockfile uri", CLI_USAGE, CLI_DESCRIPTION)
}
fn err_msg() -> String {
format!("{}\n\nCMDERROR:\n", Self::help())
}
}
/// Gets pool from args location
async fn get_pool(args: &ArgParseMeta) -> SqlitePool {
let pool_res = SqlitePool::connect(
args.lockfile
.as_ref()
.unwrap_or(&DEFAULT_LOCKFILE.to_string()),
)
.await
.map_err(|err| Error::InvalidDatabase(err));
match pool_res {
Ok(pool) => pool,
Err(err) => {
eprintln!("{}", err);
process::exit(1);
}
}
}
#[tokio::main]
async fn main() {
let (command, args) = ArgParse::launch();
let _pool = get_pool(&args).await;
match command {
ArgParse::Init => init::run(),
_ => todo!("finish command"),
}
.map_err(|err| log::fatal(err))
.unwrap();
}
|
use battleship::*;
use iota_sc_utils::*;
use wasmlib::*;
use crate::consts::*;
use crate::helpers::*;
use crate::structures::*;
pub fn create_game(ctx: &ScFuncContext) {
ctx.log("create_game");
// Reads argument called "createGameRequestKey" and tries to deserialize it to the CreateGameRequest structure
let req: Result<CreateGameRequest, serde_json::Error> =
get_struct::<ScFuncContext, CreateGameRequest>(PARAM_CREATE_GAME_REQUEST, ctx);
if !req.is_ok() {
ctx.log("Request could not be deserialized");
return;
}
ctx.log("Request successfully deserialized");
let req_body = req.unwrap();
// Gets the caller agent identifier from the context
let caller_agent_id = ctx.caller().to_string();
// Gets the provided stake that will be used in this game
let stake = ctx.incoming().balance(&ScColor::IOTA) * 2;
// Create a new game
let game = Game::new(&caller_agent_id, &req_body.player_name, stake);
ctx.log(
&format!(
"Game {} was created by player {}",
game.id, req_body.player_name
)[..],
);
// Save game to SC state as a JSON string
let game_str = serde_json::to_string(&game).unwrap();
ctx.state()
.get_string(ACTIVE_GAME_STATE)
.set_value(&game_str);
}
pub fn join_game(ctx: &ScFuncContext) {
ctx.log("join_game");
// Reads argument called "joinGameRequestKey" and tries to deserialize it to the JoinGameRequest structure
let req: Result<JoinGameRequest, serde_json::Error> =
get_struct::<ScFuncContext, JoinGameRequest>(PARAM_JOIN_GAME_REQUEST, ctx);
if !req.is_ok() {
ctx.log("Request could not be deserialized");
return;
}
ctx.log("Request successfully deserialized");
let req_body = req.unwrap();
// Get the game from the SC state
let game_str = ctx.state().get_string(ACTIVE_GAME_STATE).value();
let mut game: Game = serde_json::from_str(&game_str).unwrap();
// Check if the SC game state id matches the request game id, return if not
if game.id != req_body.game_id {
ctx.log(&format!("Game {} not found.", req_body.game_id)[..]);
return;
}
// Check if the provided stake of the new player is correct
let stake = ctx.incoming().balance(&ScColor::IOTA) * 2;
if game.stake != stake {
ctx.log(&format!("Player {} requested to join game {}, but supplied an incorrect stake. The stake of this game equals {}", &req_body.player_name, game.id, stake.to_string())[..]);
return;
}
let caller_agent_id = ctx.caller().to_string();
// Let the player join the game
let game_ref = game.join(&caller_agent_id, &req_body.player_name);
ctx.log(
&format!(
"Game {} was joined by player {}",
game_ref.id, req_body.player_name
)[..],
);
// Save game to SC state as a JSON string
let game_str = serde_json::to_string(game_ref).unwrap();
ctx.state()
.get_string(ACTIVE_GAME_STATE)
.set_value(&game_str);
}
pub fn init_field(ctx: &ScFuncContext) {
ctx.log("init_field");
// Reads argument called "initFieldRequestKey" and tries to deserialize it to the InitFieldRequest structure
let req: Result<InitFieldRequest, serde_json::Error> =
get_struct::<ScFuncContext, InitFieldRequest>(PARAM_INIT_FIELD_REQUEST, ctx);
if !req.is_ok() {
ctx.log("Request could not be deserialized");
return;
}
ctx.log("Request successfully deserialized");
let req_body = req.unwrap();
// Get the game from the SC state
let game_str = ctx.state().get_string(ACTIVE_GAME_STATE).value();
let mut game: Game = serde_json::from_str(&game_str).unwrap();
if !validate_request(ctx, &game, req_body.game_id) {
ctx.log("Request could not be validated. Terminating request.");
return;
}
// Initialize the game field of the request player and start the game if it's ready
let caller_agent_id = ctx.caller().to_string();
game.init(caller_agent_id, req_body.field);
if game.is_ready() {
game.start();
}
// Save game to SC state as a JSON string
let game_str = serde_json::to_string(&game).unwrap();
ctx.state()
.get_string(ACTIVE_GAME_STATE)
.set_value(&game_str);
}
pub fn make_move(ctx: &ScFuncContext) {
ctx.log("make_move");
// Reads argument called "moveRequestKey" and tries to deserialize it to the MoveRequest structure
let req: Result<MoveRequest, serde_json::Error> =
get_struct::<ScFuncContext, MoveRequest>(PARAM_MOVE_REQUEST, ctx);
if !req.is_ok() {
ctx.log("Request could not be deserialized");
return;
}
ctx.log("Request successfully deserialized");
let req_body = req.unwrap();
// Get the game from the SC state
let game_str = ctx.state().get_string(ACTIVE_GAME_STATE).value();
let mut game: Game = serde_json::from_str(&game_str).unwrap();
if !validate_request(ctx, &game, req_body.game_id) {
ctx.log("Request could not be validated. Terminating request.");
return;
}
// Make the request player's move
let caller_agent_id = ctx.caller().to_string();
game.player_move(caller_agent_id, req_body.point);
// Check if the game has been settled and proclaim a winner if so
if game
.mediator
.player_a
.as_ref()
.unwrap()
.own_field
.sunked_ships
== utils::ALL_SHIPS
{
let winner_id = game.mediator.player_a.as_ref().unwrap().id.to_string();
game.won(&winner_id);
}
if game
.mediator
.player_b
.as_ref()
.unwrap()
.own_field
.sunked_ships
== utils::ALL_SHIPS
{
let winner_id = game.mediator.player_b.as_ref().unwrap().id.to_string();
game.won(&winner_id);
}
// Send all staked tokens of this game to the winner
ctx.log(&format!("Player {} has won game {}.", game.winner_id, game.id)[..]);
let winner_id_vec = ctx.utility().base58_decode(&game.winner_id[..]);
let winner_id_arr = vector_as_u8_array(winner_id_vec);
let winner = ScAgentId::from_bytes(&winner_id_arr);
let bal = ctx.balances().balance(&ScColor::IOTA);
if bal >= game.stake {
ctx.transfer_to_address(
&winner.address(),
ScTransfers::new(&ScColor::IOTA, game.stake),
)
}
// Remove the game from the active game state
ctx.state().get_string(ACTIVE_GAME_STATE).set_value("");
// Save the game to the settled games state
let mut settled_game_str = ctx.state().get_string(SETTLED_GAMES_STATE).value();
let mut settled_games: SettledGames = serde_json::from_str(&settled_game_str).unwrap();
settled_games.games.push(game);
settled_game_str = serde_json::to_string(&settled_games).unwrap();
ctx.state()
.get_string(SETTLED_GAMES_STATE)
.set_value(&settled_game_str);
}
pub fn quit_game(ctx: &ScFuncContext) {
ctx.log("quit_game");
// Reads argument called "quitGameRequestKey" and tries to deserialize it to the QuitGameRequest structure
let req: Result<QuitGameRequest, serde_json::Error> =
get_struct::<ScFuncContext, QuitGameRequest>(PARAM_QUIT_GAME_REQUEST, ctx);
if !req.is_ok() {
ctx.log("Request could not be deserialized");
return;
}
ctx.log("Request successfully deserialized");
let req_body = req.unwrap();
// Get the game from the SC state
let game_str = ctx.state().get_string(ACTIVE_GAME_STATE).value();
let mut game: Game = serde_json::from_str(&game_str).unwrap();
// Check if the SC game state id matches the request game id, return if not
if game.id == req_body.game_id {
ctx.log(&format!("Game {} not found.", req_body.game_id)[..]);
}
// Check if the SC game state player id matches the request caller_agent_id, return if not
if !game.mediator.player_a.is_some() && !game.mediator.player_b.is_some() {
ctx.log(&format!("Game {} has no players.", game.id)[..]);
return;
}
let caller_agent_id = ctx.caller().to_string();
if game.mediator.player_a.as_ref().unwrap().id != caller_agent_id
&& game.mediator.player_b.as_ref().unwrap().id != caller_agent_id
{
ctx.log(&format!("Player {} not found in game {}.", caller_agent_id, game.id)[..]);
return;
}
// Settle the game
ctx.log(
&format!(
"Player {} wants to forfait game {}.",
caller_agent_id, game.id
)[..],
);
if game.mediator.player_a.as_ref().unwrap().id == caller_agent_id {
let winner_id = game.mediator.player_b.as_ref().unwrap().id.to_string();
game.won(&winner_id);
}
if game.mediator.player_b.as_ref().unwrap().id == caller_agent_id {
let winner_id = game.mediator.player_a.as_ref().unwrap().id.to_string();
game.won(&winner_id);
}
// Remove the game from the active game state
ctx.state().get_string(ACTIVE_GAME_STATE).set_value("");
// Save the game to the settled games state
let mut settled_game_str = ctx.state().get_string(SETTLED_GAMES_STATE).value();
let mut settled_games: SettledGames = serde_json::from_str(&settled_game_str).unwrap();
settled_games.games.push(game);
settled_game_str = serde_json::to_string(&settled_games).unwrap();
ctx.state()
.get_string(SETTLED_GAMES_STATE)
.set_value(&settled_game_str);
}
// Public view
pub fn get_game(ctx: &ScViewContext) {
ctx.log("get_game");
// Reads argument called "quitGameRequestKey" and tries to deserialize it to the QuitGameRequest structure
let req: Result<GetGameRequest, serde_json::Error> =
get_struct::<ScViewContext, GetGameRequest>(PARAM_QUIT_GAME_REQUEST, ctx);
if !req.is_ok() {
ctx.log("Request could not be deserialized");
return;
}
ctx.log("Request successfully deserialized");
let req_body = req.unwrap();
// Get the game from the SC state
let game_str = ctx.state().get_string(ACTIVE_GAME_STATE).value();
let game: Game = serde_json::from_str(&game_str).unwrap();
// validate if request game id matches state game id
if req_body.game_id != game.id {
ctx.log(&format!("Game {} not found.", req_body.game_id)[..]);
ctx.results()
.get_string(PARAM_GAME_STATE_RESPONSE)
.set_value("");
return;
}
// Attach the game state to the responce with the key "gameStateResponseKey"
ctx.results()
.get_string(PARAM_GAME_STATE_RESPONSE)
.set_value(&game_str);
}
// Private functions
fn validate_request(ctx: &ScFuncContext, game: &Game, req_game_id: String) -> bool {
// Check if the SC game state id matches the request game id, return if not
if game.id != req_game_id {
ctx.log(&format!("Game {} not found.", req_game_id)[..]);
return false;
}
// Check if the SC game contains players
if !game.mediator.player_a.is_some() && !game.mediator.player_b.is_some() {
ctx.log(&format!("Game {} has no players.", game.id)[..]);
return false;
}
// Check if game is already settled
if game.is_settled() {
ctx.log(
&format!(
"Game {} has already been settled. It was won by {}.",
game.id, game.winner_id
)[..],
);
return false;
}
// Check if a SC game state player id matches the request caller_agent_id, return if not
let caller_agent_id = ctx.caller().to_string();
if (game.mediator.player_a.is_some()
&& game.mediator.player_a.as_ref().unwrap().id != caller_agent_id)
&& (game.mediator.player_b.is_some()
&& game.mediator.player_b.as_ref().unwrap().id != caller_agent_id)
{
ctx.log(&format!("Player {} not found in game {}.", caller_agent_id, game.id)[..]);
return false;
}
true
}
fn settle_game(ctx: ScFuncContext, game: Game) {
// Send all staked tokens of this game to the winner
ctx.log(&format!("Player {} has won game {}.", game.winner_id, game.id)[..]);
let winner_id_vec = ctx.utility().base58_decode(&game.winner_id[..]);
let winner_id_arr = vector_as_u8_array(winner_id_vec);
let winner = ScAgentId::from_bytes(&winner_id_arr);
let bal = ctx.balances().balance(&ScColor::IOTA);
if bal >= game.stake {
ctx.transfer_to_address(
&winner.address(),
ScTransfers::new(&ScColor::IOTA, game.stake),
)
}
//TODO: add functionality to be able to host several active games at once and remove usage of SETTLED_GAMES_STATE
// Remove the game from the active game state
ctx.state().get_string(ACTIVE_GAME_STATE).set_value("");
// Save the game to the settled games state
let mut settled_game_str = ctx.state().get_string(SETTLED_GAMES_STATE).value();
let mut settled_games: SettledGames = serde_json::from_str(&settled_game_str).unwrap();
settled_games.games.push(game);
settled_game_str = serde_json::to_string(&settled_games).unwrap();
ctx.state()
.get_string(SETTLED_GAMES_STATE)
.set_value(&settled_game_str);
}
|
pub mod intcode;
pub mod sif;
pub mod intcode_old; |
use chrono::NaiveDateTime;
use schema::horus_pastes;
#[derive(AsChangeset, Identifiable, Serialize, Insertable, Queryable, Deserialize)]
#[table_name = "horus_pastes"]
pub struct HPaste
{
pub id: String,
pub title: Option<String>,
pub paste_data: String,
pub owner: i32,
pub date_added: NaiveDateTime,
pub is_expiry: bool,
pub expiration_time: Option<NaiveDateTime>,
}
|
#[doc = "Register `MACL3A30R` reader"]
pub type R = crate::R<MACL3A30R_SPEC>;
#[doc = "Register `MACL3A30R` writer"]
pub type W = crate::W<MACL3A30R_SPEC>;
#[doc = "Field `L3A30` reader - Layer 3 Address 3 Field When the L3PEN0 and L3SAM0 bits are set in the L3 and L4 control 0 register (ETH_MACL3L4C0R), this field contains the value to be matched with Bits\\[127:96\\]
of the IP Source Address field in the IPv6 packets. When the L3PEN0 and L3DAM0 bits are set in the L3 and L4 control 0 register (ETH_MACL3L4C0R), this field contains the value to be matched with Bits\\[127:96\\]
of the IP Destination Address field in the IPv6 packets. When the L3PEN0 bit is reset in the L3 and L4 control 0 register (ETH_MACL3L4C0R), this field is not used."]
pub type L3A30_R = crate::FieldReader<u32>;
#[doc = "Field `L3A30` writer - Layer 3 Address 3 Field When the L3PEN0 and L3SAM0 bits are set in the L3 and L4 control 0 register (ETH_MACL3L4C0R), this field contains the value to be matched with Bits\\[127:96\\]
of the IP Source Address field in the IPv6 packets. When the L3PEN0 and L3DAM0 bits are set in the L3 and L4 control 0 register (ETH_MACL3L4C0R), this field contains the value to be matched with Bits\\[127:96\\]
of the IP Destination Address field in the IPv6 packets. When the L3PEN0 bit is reset in the L3 and L4 control 0 register (ETH_MACL3L4C0R), this field is not used."]
pub type L3A30_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 32, O, u32>;
impl R {
#[doc = "Bits 0:31 - Layer 3 Address 3 Field When the L3PEN0 and L3SAM0 bits are set in the L3 and L4 control 0 register (ETH_MACL3L4C0R), this field contains the value to be matched with Bits\\[127:96\\]
of the IP Source Address field in the IPv6 packets. When the L3PEN0 and L3DAM0 bits are set in the L3 and L4 control 0 register (ETH_MACL3L4C0R), this field contains the value to be matched with Bits\\[127:96\\]
of the IP Destination Address field in the IPv6 packets. When the L3PEN0 bit is reset in the L3 and L4 control 0 register (ETH_MACL3L4C0R), this field is not used."]
#[inline(always)]
pub fn l3a30(&self) -> L3A30_R {
L3A30_R::new(self.bits)
}
}
impl W {
#[doc = "Bits 0:31 - Layer 3 Address 3 Field When the L3PEN0 and L3SAM0 bits are set in the L3 and L4 control 0 register (ETH_MACL3L4C0R), this field contains the value to be matched with Bits\\[127:96\\]
of the IP Source Address field in the IPv6 packets. When the L3PEN0 and L3DAM0 bits are set in the L3 and L4 control 0 register (ETH_MACL3L4C0R), this field contains the value to be matched with Bits\\[127:96\\]
of the IP Destination Address field in the IPv6 packets. When the L3PEN0 bit is reset in the L3 and L4 control 0 register (ETH_MACL3L4C0R), this field is not used."]
#[inline(always)]
#[must_use]
pub fn l3a30(&mut self) -> L3A30_W<MACL3A30R_SPEC, 0> {
L3A30_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 = "Layer3 Address 3 filter 0 register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`macl3a30r::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 [`macl3a30r::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct MACL3A30R_SPEC;
impl crate::RegisterSpec for MACL3A30R_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`macl3a30r::R`](R) reader structure"]
impl crate::Readable for MACL3A30R_SPEC {}
#[doc = "`write(|w| ..)` method takes [`macl3a30r::W`](W) writer structure"]
impl crate::Writable for MACL3A30R_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets MACL3A30R to value 0"]
impl crate::Resettable for MACL3A30R_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use crate::prelude::*;
use polars::prelude::*;
pub fn link_work_genders() -> Result<()> {
require_working_dir("goodreads")?;
let gender = LazyFrame::scan_parquet("../book-links/cluster-genders.parquet", default())?;
let books = LazyFrame::scan_parquet("gr-book-link.parquet", default())?;
let merged = gender.join(books, &[col("cluster")], &[col("cluster")], JoinType::Inner);
let dedup = merged.unique(None, UniqueKeepStrategy::First);
info!("computing results");
let results = dedup.collect()?;
info!("saving {} work-gender records", results.height());
save_df_parquet(results, "gr-work-gender.parquet")?;
Ok(())
}
|
use crate::*;
use crate::primitives::*;
use ndarray::prelude::*;
use rand::prelude::ThreadRng;
use std::convert::TryFrom;
use crate::primitives;
macro_rules! assert_num_args {
($name:expr, $args:expr, $len:expr) => {
if $args.len() != $len {
panic!("{} requires {} arguments but got {}", $name, $len, $args.len());
}
};
}
macro_rules! get_arg {
($argname:ident, $arg:expr, number, $message:expr) => {
let $argname = match f64::try_from_ref($arg) {
Some(f) => *f,
None => {return Err(String::from($message))},
};
};
($argname:ident, $arg:expr, integral, $message:expr) => {
let $argname = match i128::try_from_ref($arg) {
Some(f) => *f,
None => {return Err(String::from($message))},
};
};
($argname:ident, $arg:expr, vector, $message:expr) => {
let $argname = match Array1::<f32>::try_from($arg) {
Ok(f) => f,
Err(_) => {return Err(String::from($message))},
};
};
($argname:ident, $arg:expr, list, $message:expr) => {
let $argname: Vec<Primitive> = match &$arg {
Primitive::Vector(v) => v.iter().cloned().collect(),
Primitive::EvaluatedVector(v) => v.iter().map(|f| Primitive::from(*f)).collect(),
_ => {return Err(String::from($message))},
};
};
}
use rand::prelude::*;
use rand_distr::*;
use rand_distr::Distribution;
impl Sample for primitives::Distribution {
type Output = Primitive;
fn sample(&self, rng: &mut ThreadRng) -> Primitive {
match self {
Self::Dirac{center} => Primitive::from(*center),
Self::Kronecker{center} => Primitive::from(*center),
Self::UniformDiscrete{a, b} => {
Primitive::from(Uniform::from(*a..*b).sample(rng))
}
Self::Categorical{weights} => {
let l = weights.len();
if cfg!(debug_assertions) {
print!("Sampling (categorical {:?})…", weights.as_slice());
}
let val = rng.gen::<f32>();
let mut ssf = 0.0;
for (i, x) in weights.iter().enumerate() {
ssf += x;
if val <= ssf {
if cfg!(debug_assertions) { println!(" -> result: {}", i); }
return Primitive::from(i);
}
}
Primitive::from(l - 1) // rounding error
}
Self::MappedCategorical{weights, values} => {
let l = weights.len();
if cfg!(debug_assertions) {
print!("Sampling (categorical {:?})…", weights.as_slice());
}
let val = rng.gen::<f32>();
let mut ssf = 0.0;
let mut res = -1;
for (i, x) in weights.iter().enumerate() {
ssf += x;
if val <= ssf {
if cfg!(debug_assertions) { println!(" -> result: {}", i); }
res = i as i128;
}
}
if res == -1 {
res = (l - 1) as i128;
}
values[res as usize].clone()
}
Self::Bernoulli{p} => {
Primitive::from(rng.gen::<f64>() <= *p)
}
_ => todo!()
}
}
}
pub fn build_distribution(dtype: DistributionType, args: &[Primitive]) -> Result<primitives::Distribution, String> {
match dtype {
DistributionType::Dirac => {
assert_num_args!("(dirac center)", args, 1);
get_arg!(center, &args[0], number, "(dirac center) requries `center` numeric.");
Ok(primitives::Distribution::Dirac{center})
}
DistributionType::Kronecker => {
assert_num_args!("(kronecker center)", args, 1);
get_arg!(center, &args[0], integral, "(kronecker center) requries `center` integral.");
Ok(primitives::Distribution::Kronecker{center})
}
DistributionType::UniformContinuous => {
assert_num_args!("(uniform-continuous a b)", args, 2);
get_arg!(a, &args[0], number, "(uniform-continuous a b) requires `a` numeric.");
get_arg!(b, &args[1], number, "(uniform-continuous a b) requires `b` numeric.");
if b < a {
return Err(String::from("(uniform-continuous a b) requires a <= b."));
}
Ok(primitives::Distribution::UniformContinuous{a, b})
}
DistributionType::UniformDiscrete => {
assert_num_args!("(uniform-continuous a b)", args, 2);
get_arg!(a, &args[0], integral, "(uniform-discrete a b) requires `a` numeric.");
get_arg!(b, &args[1], integral, "(uniform-discrete a b) requires `b` numeric.");
if b < a {
return Err(String::from("(uniform-discrete a b) requires a <= b."));
}
Ok(primitives::Distribution::UniformDiscrete{a, b})
}
DistributionType::Categorical => {
assert_num_args!("(categorical weights)", args, 1);
get_arg!(weights, &args[0], vector, "(categorical weights) requires `weights` to be a vector of numbers.");
let mut weights = weights;
weights /= weights.iter().copied().sum::<f32>();
if weights.iter().any(|x| *x < 0.0) {
Err("(categorical weights): all weights must be positive".into())
} else {
Ok(primitives::Distribution::Categorical{weights})
}
}
DistributionType::MappedCategorical => {
assert_num_args!("(map-categorical weights values)", args, 2);
get_arg!(weights, &args[0], vector, "(map-categorical weights values) requires `weights` to be a vector of numbers.");
get_arg!(values, &args[1], list, "(map-categorical weights values) requires `values` to be a vector.");
let mut weights = weights;
weights /= weights.iter().copied().sum::<f32>();
if weights.iter().any(|x| *x < 0.0) {
Err("(map-categorical weights values): all weights must be positive".into())
} else if weights.len() != values.len() {
Err("(map-categorical weights values): values and weights must have the same length".into())
} else {
Ok(primitives::Distribution::MappedCategorical{weights, values})
}
}
DistributionType::Normal => {
assert_num_args!("(normal mu sigma)", args, 2);
get_arg!(mu, &args[0], number, "(normal mu sigma) requires `mu` numeric.");
get_arg!(sigma, &args[1], number, "(normal mu sigma) requires `sigma` numeric.");
if sigma <= 0. {
Err("(normal mu sigma) requires `sigma` > 0".into())
} else {
Ok(primitives::Distribution::Normal{mu, sigma})
}
}
DistributionType::Cauchy => {
assert_num_args!("(cauchy median scale)", args, 2);
get_arg!(median, &args[0], number, "(cauchy median scale) requires `median` numeric.");
get_arg!(scale, &args[1], number, "(cauchy median scale) requires `scale` numeric.");
if scale <= 0. {
Err("(cauchy median scale) requires `scale` > 0".into())
} else {
Ok(primitives::Distribution::Cauchy{median, scale})
}
}
DistributionType::Beta => {
assert_num_args!("(beta α β)", args, 2);
get_arg!(alpha, &args[0], number, "(beta α β) requires `α` numeric.");
get_arg!(beta, &args[1], number, "(beta α β) requires `β` numeric.");
if alpha <= 0. || beta <= 0. {
Err("(beta α β) requires all parameters > 0".into())
} else {
Ok(primitives::Distribution::Beta{alpha, beta})
}
}
DistributionType::Dirichlet => {
assert_num_args!("(dirichlet weights)", args, 1);
get_arg!(weights, &args[0], vector, "(dirichlet weights) requires `weights` numeric.");
if weights.iter().any(|x| *x > 1. || *x < 0.) {
Err("(dirichlet weights) requires all weights > 0 and < 1".into())
} else if (1.0 - weights.iter().sum::<f32>()).abs() > 1e-4 {
Err("(dirichlet weights) requires weights to sum to 1".into())
} else {
let weights = Array1::<f32>::from_iter(weights.iter().copied());
Ok(primitives::Distribution::Dirichlet{weights})
}
}
DistributionType::Exponential => {
assert_num_args!("(exponential λ)", args, 1);
get_arg!(lambda, &args[0], number, "(exponential λ) requires `λ` numeric");
if lambda <= 0. {
Err("(exponential λ) requires `λ` positive".into())
} else {
Ok(primitives::Distribution::Exponential{lambda})
}
}
DistributionType::Gamma => {
assert_num_args!("(gamma shape rate)", args, 2);
get_arg!(shape, &args[0], number, "(gamma shape rate) requires `shape` numeric.");
get_arg!(rate, &args[1], number, "(gamma shape rate) requires `rate` numeric.");
if shape <= 0. || rate <= 0. {
Err("(gamma shape rate) requires `shape` and `rate` positive.".into())
} else {
Ok(primitives::Distribution::Gamma{shape, rate})
}
}
DistributionType::Bernoulli => {
assert_num_args!("(bernoulli p)", args, 1);
get_arg!(p, &args[0], number, "(bernoulli p) requires `p` numeric.");
if p < 0. || p > 1. {
Err("(bernoulli p) requires p to be a probability".into())
} else {
Ok(primitives::Distribution::Bernoulli{p})
}
}
DistributionType::Binomial => {
assert_num_args!("(binomial n p)", args, 2);
get_arg!(n, &args[0], integral, "(binomial n p) requires `n` integral.");
get_arg!(p, &args[1], number, "(binomial n p) requires `p` numeric.");
if p < 0. || p > 1. {
Err("(binomial n p) requires p to be a probability.".into())
} else if n < 0 {
Err("(binomial n p) requires n nonnegative.".into())
} else {
Ok(primitives::Distribution::Binomial{n: n as u64, p})
}
}
}
}
// pub fn sample_distribution(
// distribution: &crate::primitives::Distribution, rng: &mut ThreadRng,
// ) -> Result<Primitive, String> {
// let args = &distribution.arguments[..];
// match distribution.distribution {
// DistributionType::Dirac => {
// check_params!((dirac center) from args);
// Ok(Primitive::from(center))
// }
// DistributionType::Kronecker => {
// check_params!((kronecker center) from args);
// Ok(Primitive::from(center))
// }
// DistributionType::UniformContinuous => {
// check_params!((uniform-continuous a b) from args);
// Ok(Primitive::from(Uniform::from(a..b).sample(rng)))
// }
// DistributionType::UniformDiscrete => {
// check_params!((uniform-discrete a b) from args);
// Ok(Primitive::from(Uniform::from(a..b).sample(rng)))
// }
// DistributionType::Categorical => {
// check_params!((categorical weights) from args);
// let l = weights.len();
// if cfg!(debug_assertions) {
// print!("Sampling (categorical {:?})…", weights.as_slice());
// }
// let val = rng.gen::<f64>();
// let mut ssf = 0.0;
// for (i, x) in weights.iter().enumerate() {
// ssf += x;
// if val <= ssf {
// if cfg!(debug_assertions) { println!(" -> result: {}", i); }
// return Ok(Primitive::from(i));
// }
// }
// if cfg!(debug_assertions) { println!(" -> result: {}", l - 1); }
// Ok(Primitive::from(l - 1)) // rounding error
// }
// // DistributionType::LogCategorical => {
// // check_params!((categorical-logit logits) from args);
// // let mut logits = logits;
// // // normalize
// // let norm = logsumexp(&logits);
// // logits -= norm;
// // // convert to probabilities
// // logits.mapv_inplace(|f| f.exp());
// // let norm = logits.sum();
// // logits /= norm;
// // let weights = logits;
// // // sample
// // let l = weights.len();
// // let val = rng.gen::<f32>();
// // let mut ssf: f32 = 0.0;
// // for (i, x) in weights.iter().enumerate() {
// // ssf += x;
// // if val <= ssf {
// // return Primitive::from(i);
// // }
// // }
// // return Primitive::from(l - 1); // rounding error
// // }
// DistributionType::Normal => {
// check_params!((normal mu sigma) from args);
// Ok(Primitive::from(Normal::new(mu, sigma).unwrap().sample(rng)))
// }
// // DistributionType::NormalStar => {
// // check_params!((normal mu sigma) from args);
// // let sigma = (sigma.exp() + 1.).ln();
// // Primitive::from(Normal::new(mu, sigma).unwrap().sample(rng))
// // }
// DistributionType::Cauchy => {
// check_params!((cauchy median scale) from args);
// Ok(Primitive::from(Cauchy::new(median, scale).unwrap().sample(rng)))
// }
// DistributionType::Beta => {
// check_params!((beta alpha beta) from args);
// Ok(Primitive::from(Beta::new(alpha, beta).unwrap().sample(rng)))
// }
// DistributionType::Dirichlet => {
// check_params!((dirichlet weights) from args);
// Ok(Primitive::from(
// Dirichlet::new(weights.as_slice().unwrap())
// .unwrap()
// .sample(rng)))
// }
// DistributionType::Exponential => {
// check_params!((exponential lambda) from args);
// Ok(Primitive::from(Exp::new(lambda).unwrap().sample(rng)))
// }
// DistributionType::Gamma => {
// check_params!((gamma shape rate) from args);
// Ok(Primitive::from(Gamma::new(shape, 1.0/rate).unwrap().sample(rng)))
// }
// // DistributionType::GammaStar => {
// // check_params!((gamma shape rate) from args);
// // let rate = (rate.exp() + 1.0).ln();
// // Primitive::from(Gamma::new(shape, 1.0/rate).unwrap().sample(rng))
// // }
// DistributionType::Bernoulli => {
// check_params!((bernoulli p) from args);
// Ok(Primitive::from(rng.gen::<f64>() <= p))
// }
// DistributionType::Binomial => {
// check_params!((binomial n p) from args);
// Ok(Primitive::from(Binomial::new(n as u64, p).unwrap().sample(rng) as i128))
// }
// }
// } |
//! This is more of a philosophy than a library
pub trait Dependee {
fn revision(&self) -> Revision;
}
#[derive(Debug)]
pub struct Current(Revision);
impl Current {
pub fn new() -> Self {
Self(Revision::INITIAL_CURRENT)
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Revision(u64);
impl Revision {
const DIRTY: Revision = Revision(0);
const INITIAL_CURRENT: Revision = Revision(1);
}
#[derive(Debug)]
pub struct LastVerified(Revision);
impl LastVerified {
pub fn clean(current: &Current) -> Self {
Self(current.0)
}
pub fn dirty() -> Self {
Self(Revision::DIRTY)
}
pub fn should_verify(&self, current: &Current) -> bool {
self.0 < current.0
}
pub fn update_to(&mut self, current: &Current) {
debug_assert!(self.0 < current.0);
self.0 = current.0;
}
pub fn verify_with(&mut self, current: &Current, f: impl FnOnce()) {
if self.should_verify(¤t) {
self.update_to(¤t);
f()
}
}
}
#[derive(Debug)]
pub struct LastModified(Revision);
impl LastModified {
pub fn new(current: &Current) -> Self {
Self(current.0)
}
pub fn modify(&mut self, current: &mut Current) {
(current.0).0 += 1;
self.0 = current.0;
}
}
impl Dependee for LastModified {
fn revision(&self) -> Revision {
self.0
}
}
#[derive(Debug)]
pub struct LastComputed(Revision);
impl LastComputed {
pub fn clean(current: &Current) -> Self {
Self(current.0)
}
pub fn dirty() -> Self {
Self(Revision::DIRTY)
}
pub fn should_compute(&self, dependee: &impl Dependee) -> bool {
self.0 < dependee.revision()
}
pub fn update_to(&mut self, dependee: &impl Dependee) {
let revision = dependee.revision();
if self.0 < revision {
self.0 = revision
}
}
}
impl Dependee for LastComputed {
fn revision(&self) -> Revision {
self.0
}
}
|
pub struct Complex {
pub real: f64,
pub imaginary: f64,
}
|
mod client;
pub mod models;
mod utils;
pub use client::VGMClient;
#[derive(Debug, thiserror::Error)]
pub enum VGMError {
#[error(transparent)]
RequestError(#[from] reqwest::Error),
#[error("no album found from search")]
NoAlbumFound,
#[error("invalid date format")]
InvalidDate,
}
pub(crate) type Result<T> = std::result::Result<T, VGMError>;
|
use utils;
pub fn problem_048() -> u64 {
let n = 1000;
let mut last_ten_digits = vec![0];
for i in 1..(n+1){
let digits = utils::as_digit_array(i);
let product = utils::power_digit_array_truncated(&digits, i as u32, 10);
last_ten_digits = utils::add_digit_array(&last_ten_digits, &product);
if last_ten_digits.len() > 10{
let excess = last_ten_digits.len() - 10;
last_ten_digits = last_ten_digits.split_off(excess);
}
}
utils::from_digit_array(last_ten_digits)
}
#[cfg(test)]
mod test {
use super::*;
use test::Bencher;
#[test]
fn test_problem_048() {
let ans: u64 = problem_048();
println!("Answer to Problem 48: {}", ans);
assert!(ans == 9110846700)
}
#[bench]
fn bench_problem_048(b: &mut Bencher) {
b.iter(|| problem_048());
}
}
|
use libc;
use std::ffi::CString;
use td_rlua::{self, lua_State, Lua, LuaPush, LuaRead, LuaStruct, NewStruct};
use {NetMsg, ProtocolMgr};
impl NewStruct for NetMsg {
fn new() -> NetMsg {
NetMsg::new()
}
fn name() -> &'static str {
"NetMsg"
}
}
impl<'a> LuaRead for &'a mut NetMsg {
fn lua_read_with_pop_impl(lua: *mut lua_State, index: i32, _pop: i32) -> Option<&'a mut NetMsg> {
td_rlua::userdata::read_userdata(lua, index)
}
}
impl LuaPush for NetMsg {
fn push_to_lua(self, lua: *mut lua_State) -> i32 {
unsafe {
let obj = Box::into_raw(Box::new(self));
td_rlua::userdata::push_lightuserdata(&mut *obj, lua, |_| {});
let typeid = CString::new(NetMsg::name()).unwrap();
td_rlua::lua_getglobal(lua, typeid.as_ptr());
if td_rlua::lua_istable(lua, -1) {
td_rlua::lua_setmetatable(lua, -2);
} else {
td_rlua::lua_pop(lua, 1);
}
1
}
}
}
extern "C" fn msg_to_table(lua: *mut td_rlua::lua_State) -> libc::c_int {
let net_msg: &mut NetMsg = unwrap_or!(LuaRead::lua_read_at_position(lua, 1), return 0);
ProtocolMgr::instance().unpack_protocol(lua, net_msg)
}
extern "C" fn get_data(lua: *mut td_rlua::lua_State) -> libc::c_int {
let net_msg: &mut NetMsg = unwrap_or!(LuaRead::lua_read_at_position(lua, 1), return 0);
unsafe {
let val = net_msg.get_buffer().get_data();
td_rlua::lua_pushlstring(lua, val.as_ptr() as *const libc::c_char, val.len());
}
return 1;
}
fn register_netmsg_func(lua: &mut Lua) {
let mut value = LuaStruct::<NetMsg>::new_light(lua.state());
value
.create()
.def("end_msg", td_rlua::function1(NetMsg::end_msg));
value.create().def(
"read_head",
td_rlua::function1(|net_msg: &mut NetMsg| {
let _ = net_msg.read_head();
}),
);
value.create().def(
"set_from_svr_id",
td_rlua::function2(|net_msg: &mut NetMsg, from_svr_id: u32| {
net_msg.set_from_svr_id(from_svr_id);
}),
);
value.create().def(
"get_from_svr_id",
td_rlua::function1(|net_msg: &mut NetMsg| -> u32 { net_msg.get_from_svr_id() }),
);
value.create().def(
"set_msg_type",
td_rlua::function2(|net_msg: &mut NetMsg, msg_type: u8| {
net_msg.set_msg_type(msg_type);
}),
);
value.create().def(
"get_msg_type",
td_rlua::function1(|net_msg: &mut NetMsg| -> u8 { net_msg.get_msg_type() }),
);
value.create().def(
"set_msg_flag",
td_rlua::function2(|net_msg: &mut NetMsg, msg_flag: u8| {
net_msg.set_msg_flag(msg_flag);
}),
);
value.create().def(
"get_msg_flag",
td_rlua::function1(|net_msg: &mut NetMsg| -> u8 { net_msg.get_msg_flag() }),
);
value.create().def(
"set_from_svr_type",
td_rlua::function2(|net_msg: &mut NetMsg, from_svr_type: u16| {
net_msg.set_from_svr_type(from_svr_type);
}),
);
value.create().def(
"get_from_svr_type",
td_rlua::function1(|net_msg: &mut NetMsg| -> u16 { net_msg.get_from_svr_type() }),
);
value.create().def(
"set_real_fd",
td_rlua::function2(|net_msg: &mut NetMsg, real_fd: u32| {
net_msg.set_real_fd(real_fd);
}),
);
value.create().def(
"get_real_fd",
td_rlua::function1(|net_msg: &mut NetMsg| -> u32 { net_msg.get_real_fd() }),
);
value.create().def(
"set_to_svr_type",
td_rlua::function2(|net_msg: &mut NetMsg, to_svr_type: u16| {
net_msg.set_to_svr_type(to_svr_type);
}),
);
value.create().def(
"get_to_svr_type",
td_rlua::function1(|net_msg: &mut NetMsg| -> u16 { net_msg.get_to_svr_type() }),
);
value.create().def(
"set_to_svr_id",
td_rlua::function2(|net_msg: &mut NetMsg, to_svr_id: u32| {
net_msg.set_to_svr_id(to_svr_id);
}),
);
value.create().def(
"get_to_svr_id",
td_rlua::function1(|net_msg: &mut NetMsg| -> u32 { net_msg.get_to_svr_id() }),
);
value.create().def(
"set_from_svr_type",
td_rlua::function2(|net_msg: &mut NetMsg, from_svr_type: u16| {
net_msg.set_from_svr_type(from_svr_type);
}),
);
value.create().def(
"get_from_svr_type",
td_rlua::function1(|net_msg: &mut NetMsg| -> u16 { net_msg.get_from_svr_type() }),
);
value.create().def(
"set_real_fd",
td_rlua::function2(|net_msg: &mut NetMsg, real_fd: u32| {
net_msg.set_real_fd(real_fd);
}),
);
value.create().def(
"get_real_fd",
td_rlua::function1(|net_msg: &mut NetMsg| -> u32 { net_msg.get_real_fd() }),
);
value.create().def(
"set_cookie",
td_rlua::function2(|net_msg: &mut NetMsg, cookie: u32| {
net_msg.set_cookie(cookie);
}),
);
value.create().def(
"get_cookie",
td_rlua::function1(|net_msg: &mut NetMsg| -> u32 { net_msg.get_cookie() }),
);
value
.create()
.def("set_read_data", td_rlua::function1(NetMsg::set_read_data));
value.create().register("msg_to_table", msg_to_table);
value.create().register("get_data", get_data);
}
pub fn register_userdata_func(lua: &mut Lua) {
register_netmsg_func(lua);
}
|
// https://www.codewars.com/kata/array-dot-diff
fn array_diff<T: PartialEq>(a: Vec<T>, b: Vec<T>) -> Vec<T> {
a.into_iter()
.filter(|x| !b.contains(&x))
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_array_diff() {
assert_eq!(array_diff(vec![1,2], vec![1]), vec![2]);
assert_eq!(array_diff(vec![1,2,2], vec![1]), vec![2,2]);
assert_eq!(array_diff(vec![1,2,2], vec![2]), vec![1]);
assert_eq!(array_diff(vec![1,2,2], vec![]), vec![1,2,2]);
assert_eq!(array_diff(vec![], vec![1,2]), vec![]);
}
}
|
use sdl2::{keyboard::Keycode};
use std::collections::HashMap;
pub enum GameInput {
Move(f64, f64),
Jump,
Up,
Down,
Other(Keycode),
None,
}
pub struct InputManager {
inputs: Vec<GameInput>,
pub keyboard_states: HashMap<Keycode, bool>,
}
impl InputManager {
pub fn new() -> Self {
Self {
inputs: vec![],
keyboard_states: HashMap::new()
}
}
pub fn process_keydown(&mut self, keycode: Keycode) {
self.keyboard_states.insert(keycode, true);
}
pub fn process_keyup(&mut self, keycode: Keycode) {
self.keyboard_states.insert(keycode, false);
match keycode {
Keycode::Space => {
self.inputs.push(GameInput::Jump)
}
Keycode::Up | Keycode::W => {
self.inputs.push(GameInput::Up)
}
Keycode::Down | Keycode::S => {
self.inputs.push(GameInput::Down)
},
_ => {
self.inputs.push(GameInput::Other(keycode));
}
}
}
pub fn is_key_down(&self, keycode: Keycode) -> bool {
self.keyboard_states.contains_key(&keycode)
&& *self.keyboard_states.get(&keycode).unwrap()
}
pub fn collect_game_inputs(&mut self) -> Vec<GameInput> {
let mut dx: f64 = 0.0;
let mut dy: f64 = 0.0;
if self.is_key_down(Keycode::W) || self.is_key_down(Keycode::Up) { dy = -1.0; }
if self.is_key_down(Keycode::A) || self.is_key_down(Keycode::Left) { dx = -1.0; }
if self.is_key_down(Keycode::S) || self.is_key_down(Keycode::Down) { dy = 1.0; }
if self.is_key_down(Keycode::D) || self.is_key_down(Keycode::Right) { dx = 1.0; }
if dx.abs() > 0.0 || dy.abs() > 0.0 {
let mag = (dy.powf(2.0) + dx.powf(2.0)).sqrt();
let theta = dy.atan2(dx);
self.inputs.push(GameInput::Move(theta.cos() * mag, theta.sin() * mag))
}
return self.inputs.drain(..).collect();
}
}
|
#[cfg(not(feature = "loom"))]
mod loom {
pub use std::thread;
pub use std::sync;
pub fn model<F>(f: F)
where
F: Fn() + Sync + Send + 'static
{
f()
}
}
use std::num::NonZeroUsize;
use loom::sync::Arc;
use loom::thread;
use wfqueue::queue::{ WfQueue, EnqueueCtx, DequeueCtx };
#[test]
fn one_thread() {
loom::model(|| {
let queue = WfQueue::new(3);
let mut ecx = EnqueueCtx::new();
let mut dcx = DequeueCtx::new();
let val = NonZeroUsize::new(0x42).unwrap();
assert!(queue.try_enqueue(&mut ecx, val));
let val2 = queue.try_dequeue(&mut dcx).unwrap();
assert_eq!(val, val2);
assert!(queue.try_dequeue(&mut dcx).is_none());
assert!(queue.is_empty());
let valx = NonZeroUsize::new(0x42).unwrap();
let valy = NonZeroUsize::new(0x43).unwrap();
let valz = NonZeroUsize::new(0x44).unwrap();
assert!(queue.try_enqueue(&mut ecx, valx));
assert!(queue.try_enqueue(&mut ecx, valy));
assert!(queue.try_enqueue(&mut ecx, valz));
assert!(!queue.try_enqueue(&mut ecx, valz));
assert!(queue.is_full());
let valx2 = queue.try_dequeue(&mut dcx).unwrap();
let valy2 = queue.try_dequeue(&mut dcx).unwrap();
let valz2 = queue.try_dequeue(&mut dcx).unwrap();
assert_eq!(valx, valx2);
assert_eq!(valy, valy2);
assert_eq!(valz, valz2);
});
}
#[test]
fn two_thread() {
loom::model(|| {
let queue = Arc::new(WfQueue::new(3));
let queue2 = queue.clone();
let h = thread::spawn(move || {
let mut ecx = EnqueueCtx::new();
for i in 0..5 {
let val = NonZeroUsize::new(0x42 + i).unwrap();
while !queue2.try_enqueue(&mut ecx, val) {
loom::sync::atomic::spin_loop_hint();
}
}
});
let mut dcx = DequeueCtx::new();
for i in 0..5 {
let val = NonZeroUsize::new(0x42 + i).unwrap();
loop {
if let Some(val2) = queue.try_dequeue(&mut dcx) {
assert_eq!(val, val2);
break
}
loom::sync::atomic::spin_loop_hint();
}
}
h.join().unwrap();
});
}
#[test]
fn three_thread_s2r1() {
loom::model(|| {
let queue = Arc::new(WfQueue::new(3));
let queue2 = queue.clone();
let queue3 = queue.clone();
let h = thread::spawn(move || {
let mut ecx = EnqueueCtx::new();
for i in 0..2 {
let val = NonZeroUsize::new(0x42 + i).unwrap();
while !queue2.try_enqueue(&mut ecx, val) {
loom::sync::atomic::spin_loop_hint();
}
}
});
let h2 = thread::spawn(move || {
let mut ecx = EnqueueCtx::new();
for i in 2..4 {
let val = NonZeroUsize::new(0x42 + i).unwrap();
while !queue3.try_enqueue(&mut ecx, val) {
loom::sync::atomic::spin_loop_hint();
}
}
});
let mut dcx = DequeueCtx::new();
let mut output = Vec::new();
for _ in 0..4 {
loop {
if let Some(val) = queue.try_dequeue(&mut dcx) {
output.push(val.get());
break
}
loom::sync::atomic::spin_loop_hint();
}
}
h.join().unwrap();
h2.join().unwrap();
// check
output.sort();
let expected = (0..4).map(|n| 0x42 + n).collect::<Vec<usize>>();
assert_eq!(expected, output.as_slice());
});
}
#[test]
fn three_thread_s1r2() {
loom::model(|| {
let queue = Arc::new(WfQueue::new(3));
let queue2 = queue.clone();
let queue3 = queue.clone();
let h = thread::spawn(move || {
let mut ecx = EnqueueCtx::new();
for i in 0..4 {
let val = NonZeroUsize::new(0x42 + i).unwrap();
while !queue2.try_enqueue(&mut ecx, val) {
loom::sync::atomic::spin_loop_hint();
}
}
});
let h2 = thread::spawn(move || {
let mut dcx = DequeueCtx::new();
let mut output = Vec::new();
for _ in 0..2 {
loop {
if let Some(val) = queue3.try_dequeue(&mut dcx) {
output.push(val.get());
break
}
loom::sync::atomic::spin_loop_hint();
}
}
output
});
let mut dcx = DequeueCtx::new();
let mut output = Vec::new();
for _ in 0..2 {
loop {
if let Some(val) = queue.try_dequeue(&mut dcx) {
output.push(val.get());
break
}
loom::sync::atomic::spin_loop_hint();
}
}
h.join().unwrap();
let mut output2 = h2.join().unwrap();
// check
output.append(&mut output2);
output.sort();
let expected = (0..4).map(|n| 0x42 + n).collect::<Vec<usize>>();
assert_eq!(expected, output.as_slice());
});
}
|
use crate::{Job, JobRequest};
use anyhow::Error;
use log::*;
use std::sync::Arc;
use tokio_postgres::{Client, NoTls, Row};
#[derive(Clone)]
pub struct DbHandle {
client: Arc<Client>,
}
impl DbHandle {
pub(crate) async fn new(url: &str) -> Result<Self, Error> {
let (client, connection) = tokio_postgres::connect(&url, NoTls).await?;
tokio::spawn(async move {
if let Err(e) = connection.await {
error!("connection error: {}", e);
}
});
client.batch_execute(include_str!("setup.sql")).await?;
Ok(DbHandle {
client: Arc::new(client),
})
}
pub(crate) async fn complete_job(&self, id: i64) -> Result<(), Error> {
let query = "update jobq set status = 'Completed', duration = extract(epoch from now() - \"time\") where id = $1";
self.client.query(query, &[&id]).await?;
Ok(())
}
pub(crate) async fn fail_job(&self, id: i64, msg: String) -> Result<(), Error> {
let query = "update jobq set status = 'Failed', duration = extract(epoch from now() - \"time\"), error = $1 where id = $2";
self.client.query(query, &[&msg, &id]).await?;
Ok(())
}
pub(crate) async fn begin_job(&self, id: i64) -> Result<(), Error> {
let query = "update jobq set status = 'Processing', time = now() where id = $1";
self.client.query(query, &[&id]).await?;
Ok(())
}
fn get_jobs(result: Vec<Row>) -> Result<Vec<Job>, Error> {
let mut jobs = Vec::new();
for row in result {
let id = row.try_get(0)?;
let name = row.try_get(1)?;
let username = row.try_get(2)?;
let uuid = row.try_get(3)?;
let params = row.try_get(4)?;
let priority = row.try_get(5)?;
let status = row.try_get(6)?;
jobs.push({
Job {
id,
username,
name,
uuid,
params,
priority,
status,
}
});
}
Ok(jobs)
}
pub(crate) async fn get_processing_jobs(&self) -> Result<Vec<Job>, Error> {
let query = "select id, name, username, uuid, params, priority, status from jobq
where status = 'Processing' order by priority asc, time asc";
DbHandle::get_jobs(self.client.query(query, &[]).await?)
}
pub(crate) async fn get_queued_jobs(&self, num: i64) -> Result<Vec<Job>, Error> {
let query = "select
id,
name,
username,
uuid,
params,
priority,
status
from jobq
where
status = 'Queued'
order by
priority asc, time asc
limit $1";
DbHandle::get_jobs(self.client.query(query, &[&num]).await?)
}
pub(crate) async fn submit_job_request(&self, job: &JobRequest) -> Result<i64, Error> {
let query =
"INSERT into jobq (name, username, uuid, params, priority, status) values ($1, $2, $3, $4, $5, 'Queued') returning id";
let result = self
.client
.query(
query,
&[
&job.name,
&job.username,
&job.uuid,
&job.params,
&job.priority,
],
)
.await?;
Ok(result[0].get(0))
}
}
|
#[doc = "Register `PTPPPSCR` reader"]
pub type R = crate::R<PTPPPSCR_SPEC>;
#[doc = "Field `TSSO` reader - TSSO"]
pub type TSSO_R = crate::BitReader;
#[doc = "Field `TSTTR` reader - TSTTR"]
pub type TSTTR_R = crate::BitReader;
impl R {
#[doc = "Bit 0 - TSSO"]
#[inline(always)]
pub fn tsso(&self) -> TSSO_R {
TSSO_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - TSTTR"]
#[inline(always)]
pub fn tsttr(&self) -> TSTTR_R {
TSTTR_R::new(((self.bits >> 1) & 1) != 0)
}
}
#[doc = "Ethernet PTP PPS control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ptpppscr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct PTPPPSCR_SPEC;
impl crate::RegisterSpec for PTPPPSCR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`ptpppscr::R`](R) reader structure"]
impl crate::Readable for PTPPPSCR_SPEC {}
#[doc = "`reset()` method sets PTPPPSCR to value 0"]
impl crate::Resettable for PTPPPSCR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
#[cfg(test)]
extern crate tempfile;
extern crate termion;
#[macro_use]
extern crate lazy_static;
#[cfg(test)]
mod tests;
use std::env;
use std::fs;
use std::io::{self, BufRead, BufReader, BufWriter, Write};
use std::ops::Range;
use termion::{
raw::IntoRawMode,
input::TermRead,
};
type Line = String;
type Buffer = Vec<Line>;
type Screen =
io::BufWriter<termion::raw::RawTerminal<termion::screen::AlternateScreen<io::Stdout>>>;
type Key = termion::event::Key;
struct Cursor {
col: usize,
row: usize,
left: usize,
top: usize,
}
impl Cursor {
fn new() -> Self {
Cursor{col: 0, row: 0, left: 0, top: 0}
}
}
struct Size {
rows: usize,
cols: usize,
}
impl Size {
fn new<T: Into<usize>>(rows: T, cols: T) -> Self {
Size{rows: rows.into(), cols: cols.into()}
}
}
fn get_screen_size() -> io::Result<Size> {
termion::terminal_size().map(|(cols, rows)| Size::new(rows, cols))
}
// file system functions
fn read_file(path: &str) -> io::Result<Buffer> {
match fs::OpenOptions::new().read(true).open(path) {
Ok(file) => BufReader::new(file).lines().collect(),
Err(err) => match err.kind() {
io::ErrorKind::NotFound => Ok(Buffer::new()),
_ => Err(err),
}
}
}
fn write_file(path: &str, buf: &Buffer) -> io::Result<()> {
let mut file = fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(true)
.open(path)?;
for line in buf {
writeln!(file, "{}", line)?;
}
file.flush()
}
// buffer mutations
fn init_buffer_if_empty(buf: &mut Buffer) {
if buf.len() == 0 {
buf.push(String::new());
}
}
fn insert_at(ch: char, cur: &Cursor, buf: &mut Buffer) {
if cur.row > buf.len() {
panic!("tried to insert past end of buffer");
}
buf[cur.row].insert(cur.col, ch)
}
fn delete_before(cur: &Cursor, buf: &mut Buffer) {
if cur.col == 0 {
panic!("tried to delete before start of buffer");
}
buf[cur.row].remove(cur.col - 1);
}
fn delete_at(cur: &Cursor, buf: &mut Buffer) {
if cur.row >= buf.len() {
panic!("tried to delete after end of buffer");
}
if cur.col >= buf[cur.row].len() {
panic!("tried to delete after end of line");
}
buf[cur.row].remove(cur.col);
}
fn merge_next_line_into(cur: &Cursor, buf: &mut Buffer) {
if cur.row + 1 >= buf.len() {
panic!("tried to merge line from past end of buffer");
}
let line = buf.remove(cur.row + 1);
buf[cur.row].push_str(&line);
}
fn break_line_at(cur: &Cursor, buf: &mut Buffer) {
let new_line = buf[cur.row].split_off(cur.col);
buf.insert(cur.row + 1, new_line);
}
fn push_new_line_if_at_end(cur: &Cursor, buf: &mut Buffer) {
if cur.row == buf.len() {
buf.push(Line::new());
}
}
// screen updating
fn buffer_char_range(cur: &Cursor, size: &Size) -> Range<usize> {
cur.left..(cur.left + size.cols)
}
fn buffer_line_range(cur: &Cursor, size: &Size) -> Range<usize> {
cur.top..(cur.top + size.rows)
}
fn cursor_screen_position(cur: &Cursor) -> (u16, u16) {
((cur.row - cur.top + 1) as u16, (cur.col - cur.left + 1) as u16)
}
fn replace_invisibles(c: char) -> char {
match c {
'\t' => '\u{00BB}',
' ' => '\u{0387}',
'\n' => '\u{00AC}',
c => c,
}
}
lazy_static! {
static ref SET_NORMAL_COLORS: Vec<u8> = format!(
"{}",
termion::color::Fg(termion::color::Reset),
).into_bytes();
static ref SET_INVISIBLE_COLORS: Vec<u8> = format!(
"{}",
termion::color::Fg(termion::color::LightBlack),
).into_bytes();
}
fn set_normal_colors(scr: &mut Screen) -> io::Result<()> {
scr.write(&SET_NORMAL_COLORS).map(|_|())
}
fn set_invisible_colors(scr: &mut Screen) -> io::Result<()> {
scr.write(&SET_INVISIBLE_COLORS).map(|_|())
}
fn write_invisible_to_screen(scr: &mut Screen, mut c: char) -> io::Result<()> {
c = replace_invisibles(c);
set_invisible_colors(scr)?;
write!(scr, "{}", c)?;
set_normal_colors(scr)
}
fn write_char_to_screen(scr: &mut Screen, c: char) -> io::Result<()> {
match c {
'\t' | ' ' => write_invisible_to_screen(scr, c),
c => write!(scr, "{}", c),
}
}
fn write_line_end(scr: &mut Screen) -> io::Result<()> {
write_invisible_to_screen(scr, '\n')
}
fn write_line_to_screen(
scr: &mut Screen,
cur: &Cursor,
line: &Line,
size: &Size,
) -> io::Result<()> {
set_normal_colors(scr)?;
let bytes = line.as_bytes();
for i in buffer_char_range(cur, size) {
if i >= line.len() {
write_line_end(scr)?;
break;
}
write_char_to_screen(scr, bytes[i] as char)?;
}
Ok(())
}
fn write_buffer_to_screen(
scr: &mut Screen,
cur: &Cursor,
buf: &Buffer,
size: &Size,
) -> io::Result<()> {
let range = buffer_line_range(cur, size);
let last = range.end - 1;
for i in range {
if i >= buf.len() {
break;
}
write_line_to_screen(scr, cur, &buf[i], size)?;
if i != last {
write!(scr, "\n\r")?;
}
}
let (r, c) = cursor_screen_position(cur);
write!(scr, "{}", termion::cursor::Goto(c, r))
}
fn blank_screen(scr: &mut Screen) -> io::Result<()> {
write!(scr, "{}{}", termion::cursor::Goto(1, 1), termion::clear::All)
}
fn init_screen() -> io::Result<Screen> {
termion::screen::AlternateScreen::from(io::stdout())
.into_raw_mode().map(BufWriter::new)
}
fn update_screen(
scr: &mut Screen,
cur: &Cursor,
buf: &Buffer,
size: &Size,
) -> io::Result<()> {
blank_screen(scr)?;
write_buffer_to_screen(scr, cur, buf, size)?;
scr.flush()
}
// Cursor movement
fn move_cursor_left(cur: &mut Cursor, buf: &Buffer, size: &Size) {
if cur.col > 0 {
cur.col -= 1;
} else if cur.row > 0 {
cur.row -= 1;
cur.col = buf[cur.row].len();
}
align_cursor(cur, size);
}
fn move_cursor_right(cur: &mut Cursor, buf: &Buffer, size: &Size) {
if cur.row < buf.len() {
if cur.col < buf[cur.row].len() {
cur.col += 1;
} else {
cur.row += 1;
cur.col = 0;
}
}
align_cursor(cur, size);
}
fn move_cursor_up(cur: &mut Cursor, buf: &Buffer, size: &Size) {
if cur.row > 0 {
cur.row -= 1;
} else {
cur.row = buf.len();
}
truncate_cursor_to_line(cur, buf);
align_cursor(cur, size);
}
fn move_cursor_down(cur: &mut Cursor, buf: &Buffer, size: &Size) {
if cur.row < buf.len() {
cur.row += 1;
} else {
cur.row = 0;
}
truncate_cursor_to_line(cur, buf);
align_cursor(cur, size);
}
fn move_cursor_end_of_prev_line(cur: &mut Cursor, buf: &Buffer, size: &Size) {
if cur.row == 0 {
panic!("tried to move cursor before start of buffer");
}
cur.row -= 1;
cur.col = buf[cur.row].len();
align_cursor(cur, size);
}
fn move_cursor_start_of_next_line(cur: &mut Cursor, buf: &Buffer, size: &Size) {
if cur.row >= buf.len() {
panic!("tried to move cursor past end of buffer");
}
cur.row += 1;
cur.col = 0;
align_cursor(cur, size);
}
fn get_char(cur: &mut Cursor, buf: &Buffer) -> char {
buf[cur.row].as_bytes()[cur.col] as char
}
fn is_whitespace(c: char) -> bool {
c.is_ascii_whitespace()
}
fn is_blank(cur: &mut Cursor, buf: &Buffer) -> bool {
cur.row >= buf.len() || buf[cur.row].len() == cur.col || is_whitespace(get_char(cur, buf))
}
fn is_blank_line(cur: &mut Cursor, buf: &Buffer) -> bool {
if cur.row < buf.len() && buf[cur.row].len() > 0 {
for c in buf[cur.row].chars() {
if !is_whitespace(c) {
return false;
}
}
}
true
}
fn move_cursor_to_next_blank(cur: &mut Cursor, buf: &Buffer, size: &Size) {
while !is_blank(cur, buf) {
move_cursor_right(cur, buf, size);
}
while is_blank(cur, buf) {
move_cursor_right(cur, buf, size);
}
}
fn move_cursor_to_prev_blank(cur: &mut Cursor, buf: &Buffer, size: &Size) {
while !is_blank(cur, buf) {
move_cursor_left(cur, buf, size);
}
while is_blank(cur, buf) {
move_cursor_left(cur, buf, size);
}
}
fn move_cursor_to_next_blank_line(cur: &mut Cursor, buf: &Buffer, size: &Size) {
while !is_blank_line(cur, buf) {
move_cursor_down(cur, buf, size);
}
while is_blank_line(cur, buf) {
move_cursor_down(cur, buf, size);
}
}
fn move_cursor_to_prev_blank_line(cur: &mut Cursor, buf: &Buffer, size: &Size) {
while !is_blank_line(cur, buf) {
move_cursor_up(cur, buf, size);
}
while is_blank_line(cur, buf) {
move_cursor_up(cur, buf, size);
}
}
fn align_cursor(cur: &mut Cursor, size: &Size) {
if cur.col < cur.left {
cur.left = cur.col;
}
if cur.col > cur.left + size.cols - 1{
cur.left = cur.col - size.cols + 1;
}
if cur.row < cur.top {
cur.top = cur.row;
}
if cur.row > cur.top + size.rows - 1{
cur.top = cur.row - size.rows + 1;
}
}
fn truncate_cursor_to_line(cur: &mut Cursor, buf: &Buffer) {
if cur.row < buf.len() {
if cur.col > buf[cur.row].len() {
cur.col = buf[cur.row].len();
}
} else {
cur.col = 0;
}
}
// Editing helpers
fn break_line_and_return_cursor(cur: &mut Cursor, buf: &mut Buffer, size: &Size) {
break_line_at(cur, buf);
move_cursor_start_of_next_line(cur, buf, size);
}
fn insert_and_move_cursor(
ch: char,
cur: &mut Cursor,
buf: &mut Buffer,
size: &Size,
) {
push_new_line_if_at_end(cur, buf);
insert_at(ch, cur, buf);
move_cursor_right(cur, buf, size);
}
fn delete_in_place(cur: &mut Cursor, buf: &mut Buffer, _size: &Size) {
if cur.row < buf.len() && cur.col < buf[cur.row].len() {
delete_at(cur, buf);
} else if cur.row + 1 < buf.len() && cur.col == buf[cur.row].len() {
merge_next_line_into(cur, buf);
}
}
fn delete_and_move_cursor(cur: &mut Cursor, buf: &mut Buffer, size: &Size) {
if cur.col > 0 {
delete_before(cur, buf);
move_cursor_left(cur, buf, size);
} else if cur.row > 0 {
move_cursor_end_of_prev_line(cur, buf, size);
if cur.row + 1 < buf.len() {
merge_next_line_into(cur, buf);
}
}
}
fn delete_line(cur: &mut Cursor, src: &mut Buffer, size: &Size) {
src.remove(cur.row);
truncate_cursor_to_line(cur, src);
align_cursor(cur, size);
}
fn cut_line(cur: &mut Cursor, src: &mut Buffer, dst: &mut Buffer, size: &Size) {
dst.push(src.remove(cur.row));
truncate_cursor_to_line(cur, src);
align_cursor(cur, size);
}
fn copy_line(cur: &mut Cursor, src: &Buffer, dst: &mut Buffer) {
src.get(cur.row).map(|line| dst.push(line.clone()));
}
fn paste_line(cur: &mut Cursor, src: &mut Buffer, dst: &mut Buffer, size: &Size) {
src.pop().map(|line| dst.insert(cur.row, line));
truncate_cursor_to_line(cur, dst);
align_cursor(cur, size);
}
enum Mode {
Insert,
Normal,
Quit,
}
fn handle_key_insert_mode(
key: Key,
cur: &mut Cursor,
buf: &mut Buffer,
size: &Size
) -> io::Result<Mode> {
match key {
Key::Char('\n') => break_line_and_return_cursor(cur, buf, size),
Key::Char(ch) => insert_and_move_cursor(ch, cur, buf, size),
Key::Delete => delete_in_place(cur, buf, size),
Key::Backspace => delete_and_move_cursor(cur, buf, size),
Key::Esc => return Ok(Mode::Normal),
_ => (),
};
Ok(Mode::Insert)
}
fn handle_key_normal_mode(
key: Key,
path: &str,
cur: &mut Cursor,
buf: &mut Buffer,
clip: &mut Buffer,
size: &Size
) -> io::Result<Mode> {
match key {
Key::Char('i') => return Ok(Mode::Insert),
Key::Delete => {
delete_in_place(cur, buf, size);
return Ok(Mode::Insert);
}
Key::Backspace => {
delete_and_move_cursor(cur, buf, size);
return Ok(Mode::Insert);
}
// movement
Key::Char('h') => move_cursor_left(cur, buf, size),
Key::Char('l') => move_cursor_right(cur, buf, size),
Key::Char('k') => move_cursor_up(cur, buf, size),
Key::Char('j') => move_cursor_down(cur, buf, size),
Key::Char('H') => move_cursor_to_prev_blank(cur, buf, size),
Key::Char('L') => move_cursor_to_next_blank(cur, buf, size),
Key::Char('K') => move_cursor_to_prev_blank_line(cur, buf, size),
Key::Char('J') => move_cursor_to_next_blank_line(cur, buf, size),
// cut-paste buffer
Key::Char('d') => delete_line(cur, buf, size),
Key::Char('c') => {
copy_line(cur, buf, clip);
move_cursor_down(cur, buf, size);
},
Key::Char('v') => paste_line(cur, clip, buf, size),
Key::Char('x') => cut_line(cur, buf, clip, size),
Key::Char('s') => write_file(path, buf)?,
Key::Char('q') => return Ok(Mode::Quit),
_ => (),
};
Ok(Mode::Normal)
}
fn edit_buffer(path: &str, buf: &mut Buffer) -> io::Result<()> {
let mut scr = init_screen()?;
let mut cur = Cursor::new();
let mut clip = Buffer::new();
let mut size = get_screen_size()?;
let mut mode = Mode::Normal;
update_screen(&mut scr, &cur, buf, &size)?;
for res in io::stdin().keys() {
let key = res?;
size = get_screen_size()?;
mode = match mode {
Mode::Insert => handle_key_insert_mode(key, &mut cur, buf, &size)?,
Mode::Normal => handle_key_normal_mode(key, path, &mut cur, buf, &mut clip, &size)?,
_ => Mode::Quit,
};
match mode {
Mode::Quit => break,
_ => (),
}
update_screen(&mut scr, &cur, buf, &size)?;
}
Ok(())
}
fn main() -> io::Result<()> {
match env::args().skip(1).next() {
Some(path) => {
let mut buf = read_file(&path)?;
init_buffer_if_empty(&mut buf);
edit_buffer(&path, &mut buf)
}
None => Ok(()),
}
}
|
use env_logger::init as log_init;
use failure::Error;
use std::fs;
use std::sync::Arc;
use super::configuration::configuration as read_configuration;
use super::server::{server, Context};
use super::store::redis::new_redis_store;
pub fn run_app() -> Result<(), Error> {
log_init();
let config = read_configuration()
.map_err(|e| format_err!("an error occured while reading configuration: {}", e))?;
let _ = are_static_files_present(&config.server.folder)
.map_err(|e| format_err!("an error occured while opening static files folder {}", e))?;
let redis = new_redis_store(&config.redis_address)
.map_err(|e| format_err!("an error occured while connecting to store: {}", e))?;
server(Context {
configuration: Arc::new(config),
store: Arc::new(redis),
})
}
fn are_static_files_present(path: &str) -> Result<(), Error> {
fs::read_dir(path)
.map(|paths| {
for entry in paths {
match entry {
Ok(f) => debug!("static files: {}", f.path().display()),
Err(e) => debug!("an error occured while reading a file: {}", e),
}
}
Ok(())
})
.map_err(|err| format_err!("an error occured while opening {}: {}", path, err))?
}
|
// Definition for a binary tree node.
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
pub val: i32,
pub left: Option<Rc<RefCell<TreeNode>>>,
pub right: Option<Rc<RefCell<TreeNode>>>,
}
impl TreeNode {
#[inline]
pub fn new(val: i32) -> Self {
TreeNode {
val,
left: None,
right: None,
}
}
}
use std::cell::RefCell;
use std::rc::Rc;
struct Solution;
use std::collections::LinkedList;
impl Solution {
// 只使用一个队列。
pub fn level_order_bottom(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
if root.is_none() {
return Vec::new();
}
let mut ans = Vec::new();
let mut queue = LinkedList::new();
queue.push_back(root.unwrap());
while !queue.is_empty() {
// 使用长度来标记这一层是否遍历完了。
let n = queue.len();
let mut level = Vec::new();
for _i in 0..n {
let node = queue.pop_front().unwrap();
let mut node = node.borrow_mut();
level.push(node.val);
if let Some(left) = node.left.take() {
queue.push_back(left);
}
if let Some(right) = node.right.take() {
queue.push_back(right);
}
}
ans.push(level);
}
ans.reverse();
ans
}
// by zhangyuchen.
// 我用两个队列来回倒腾。
pub fn level_order_bottom1(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
let mut queue1 = LinkedList::new();
let mut queue2 = LinkedList::new();
queue1.push_back(root);
let mut ans = Vec::new();
while !queue1.is_empty() {
let mut one_level = Vec::new();
while let Some(node) = queue1.pop_front() {
if let Some(n) = node {
one_level.push(n.borrow().val);
queue2.push_back(n.borrow_mut().left.take());
queue2.push_back(n.borrow_mut().right.take());
}
}
if !one_level.is_empty() {
ans.push(one_level);
}
let tmp = queue1;
queue1 = queue2;
queue2 = tmp;
}
ans.reverse();
ans
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_level_order_bottom() {
let root = node(TreeNode {
val: 3,
left: node(TreeNode::new(9)),
right: node(TreeNode {
val: 20,
left: node(TreeNode::new(15)),
right: node(TreeNode::new(7)),
}),
});
let want = vec![vec![15, 7], vec![9, 20], vec![3]];
assert_eq!(Solution::level_order_bottom(root), want);
}
fn node(n: TreeNode) -> Option<Rc<RefCell<TreeNode>>> {
Some(Rc::new(RefCell::new(n)))
}
}
|
pub mod exp;
pub mod module;
pub mod stm;
pub mod util;
|
// Convenience functions for creating mappings for
// US keyboards
// vim: shiftwidth=2
use crate::keys::{KeyCode, Mapping, Repeat};
use std::collections::HashMap;
use KeyCode::*;
use lazy_static::lazy_static;
use std::default::Default;
pub struct USKeyboardLayout {
pub tilde: char,
pub tilde_shift: char,
pub tilde_alt_gr: char,
pub tilde_shift_alt_gr: char,
pub row_1: String,
pub row_1_shift: String,
pub row_1_alt_gr: String,
pub row_1_shift_alt_gr: String,
pub row_q: String,
pub row_q_shift: String,
pub row_q_alt_gr: String,
pub row_q_shift_alt_gr: String,
pub row_a: String,
pub row_a_shift: String,
pub row_a_alt_gr: String,
pub row_a_shift_alt_gr: String,
pub row_z: String,
pub row_z_shift: String,
pub row_z_alt_gr: String,
pub row_z_shift_alt_gr: String,
}
lazy_static! {
static ref CHAR_ACCESS_MAP: HashMap<char, SinkKey> = _char_access_map();
}
struct SinkKey {
sh: bool,
k: KeyCode
}
fn adapt(sink_key: &SinkKey, shift_key: &KeyCode) -> Vec<KeyCode> {
if !sink_key.sh {
vec![sink_key.k]
}
else if *shift_key == LEFTSHIFT {
vec![LEFTSHIFT, sink_key.k]
}
else if *shift_key == RIGHTSHIFT {
vec![RIGHTSHIFT, sink_key.k]
}
else {
vec![LEFTSHIFT, sink_key.k]
}
}
fn _char_access_map() -> HashMap<char, SinkKey> {
let mut res = HashMap::new();
res.insert('0', SinkKey { sh: false, k: K0 });
res.insert('1', SinkKey { sh: false, k: K1 });
res.insert('2', SinkKey { sh: false, k: K2 });
res.insert('3', SinkKey { sh: false, k: K3 });
res.insert('4', SinkKey { sh: false, k: K4 });
res.insert('5', SinkKey { sh: false, k: K5 });
res.insert('6', SinkKey { sh: false, k: K6 });
res.insert('7', SinkKey { sh: false, k: K7 });
res.insert('8', SinkKey { sh: false, k: K8 });
res.insert('9', SinkKey { sh: false, k: K9 });
res.insert('a', SinkKey { sh: false, k: A });
res.insert('b', SinkKey { sh: false, k: B });
res.insert('c', SinkKey { sh: false, k: C });
res.insert('d', SinkKey { sh: false, k: D });
res.insert('e', SinkKey { sh: false, k: E });
res.insert('f', SinkKey { sh: false, k: F });
res.insert('g', SinkKey { sh: false, k: G });
res.insert('h', SinkKey { sh: false, k: H });
res.insert('i', SinkKey { sh: false, k: I });
res.insert('j', SinkKey { sh: false, k: J });
res.insert('k', SinkKey { sh: false, k: K });
res.insert('l', SinkKey { sh: false, k: L });
res.insert('m', SinkKey { sh: false, k: M });
res.insert('n', SinkKey { sh: false, k: N });
res.insert('o', SinkKey { sh: false, k: O });
res.insert('p', SinkKey { sh: false, k: P });
res.insert('q', SinkKey { sh: false, k: Q });
res.insert('r', SinkKey { sh: false, k: R });
res.insert('s', SinkKey { sh: false, k: S });
res.insert('t', SinkKey { sh: false, k: T });
res.insert('u', SinkKey { sh: false, k: U });
res.insert('v', SinkKey { sh: false, k: V });
res.insert('w', SinkKey { sh: false, k: W });
res.insert('x', SinkKey { sh: false, k: X });
res.insert('y', SinkKey { sh: false, k: Y });
res.insert('z', SinkKey { sh: false, k: Z });
res.insert('A', SinkKey { sh: true, k: A });
res.insert('B', SinkKey { sh: true, k: B });
res.insert('C', SinkKey { sh: true, k: C });
res.insert('D', SinkKey { sh: true, k: D });
res.insert('E', SinkKey { sh: true, k: E });
res.insert('F', SinkKey { sh: true, k: F });
res.insert('G', SinkKey { sh: true, k: G });
res.insert('H', SinkKey { sh: true, k: H });
res.insert('I', SinkKey { sh: true, k: I });
res.insert('J', SinkKey { sh: true, k: J });
res.insert('K', SinkKey { sh: true, k: K });
res.insert('L', SinkKey { sh: true, k: L });
res.insert('M', SinkKey { sh: true, k: M });
res.insert('N', SinkKey { sh: true, k: N });
res.insert('O', SinkKey { sh: true, k: O });
res.insert('P', SinkKey { sh: true, k: P });
res.insert('Q', SinkKey { sh: true, k: Q });
res.insert('R', SinkKey { sh: true, k: R });
res.insert('S', SinkKey { sh: true, k: S });
res.insert('T', SinkKey { sh: true, k: T });
res.insert('U', SinkKey { sh: true, k: U });
res.insert('V', SinkKey { sh: true, k: V });
res.insert('W', SinkKey { sh: true, k: W });
res.insert('X', SinkKey { sh: true, k: X });
res.insert('Y', SinkKey { sh: true, k: Y });
res.insert('Z', SinkKey { sh: true, k: Z });
res.insert('!', SinkKey { sh: true, k: K1 });
res.insert('@', SinkKey { sh: true, k: K2 });
res.insert('#', SinkKey { sh: true, k: K3 });
res.insert('$', SinkKey { sh: true, k: K4 });
res.insert('%', SinkKey { sh: true, k: K5 });
res.insert('^', SinkKey { sh: true, k: K6 });
res.insert('&', SinkKey { sh: true, k: K7 });
res.insert('*', SinkKey { sh: true, k: K8 });
res.insert('(', SinkKey { sh: true, k: K9 });
res.insert(')', SinkKey { sh: true, k: K0 });
res.insert(',', SinkKey { sh: false, k: COMMA });
res.insert('.', SinkKey { sh: false, k: DOT });
res.insert('`', SinkKey { sh: false, k: GRAVE });
res.insert('-', SinkKey { sh: false, k: MINUS });
res.insert('=', SinkKey { sh: false, k: EQUAL });
res.insert('[', SinkKey { sh: false, k: LEFTBRACE });
res.insert(']', SinkKey { sh: false, k: RIGHTBRACE });
res.insert(';', SinkKey { sh: false, k: SEMICOLON });
res.insert('\'', SinkKey { sh: false, k: APOSTROPHE });
res.insert('/', SinkKey { sh: false, k: SLASH });
res.insert('\\', SinkKey { sh: false, k: BACKSLASH });
res.insert('~', SinkKey { sh: true, k: GRAVE });
res.insert('_', SinkKey { sh: true, k: MINUS });
res.insert('+', SinkKey { sh: true, k: EQUAL });
res.insert('{', SinkKey { sh: true, k: LEFTBRACE });
res.insert('}', SinkKey { sh: true, k: RIGHTBRACE });
res.insert(':', SinkKey { sh: true, k: SEMICOLON });
res.insert('"', SinkKey { sh: true, k: APOSTROPHE });
res.insert('<', SinkKey { sh: true, k: COMMA });
res.insert('>', SinkKey { sh: true, k: DOT });
res.insert('?', SinkKey { sh: true, k: SLASH });
res.insert('|', SinkKey { sh: true, k: BACKSLASH });
res
}
pub struct USKeyCodeMap {
tilde: KeyCode,
row_1: Vec<KeyCode>,
row_q: Vec<KeyCode>,
row_a: Vec<KeyCode>,
row_z: Vec<KeyCode>,
}
lazy_static! {
static ref US_KEYCODES: USKeyCodeMap = _us_keycodes();
}
fn _us_keycodes() -> USKeyCodeMap {
USKeyCodeMap {
tilde: GRAVE,
row_1: vec![K1, K2, K3, K4, K5, K6, K7, K8, K9, K0, MINUS, EQUAL],
row_q: vec![Q, W, E, R, T, Y, U, I, O, P, LEFTBRACE, RIGHTBRACE],
row_a: vec![A, S, D, F, G, H, J, K, L, SEMICOLON, APOSTROPHE],
row_z: vec![Z, X, C, V, B, N, M, COMMA, DOT, SLASH],
}
}
lazy_static! {
static ref US_SHIFT_KEYS: Vec<KeyCode> = vec![LEFTSHIFT, RIGHTSHIFT];
}
fn string_mappings(hardware_keys: &Vec<KeyCode>, desired_chars: String, shift_down: bool, alt_gr_down: bool, shift_keys: &Vec<KeyCode>, alt_gr_keys: &Vec<KeyCode>, disable_repeats: bool, absorb_shift: bool) -> Vec<Mapping> {
let mut key_iter = hardware_keys.iter();
let mut char_iter = desired_chars.chars();
let mut res = Vec::new();
let repeat = {
if disable_repeats {
Repeat::Disabled
}
else {
Repeat::Normal
}
};
let shift_absorbing = |sk: KeyCode| {
if absorb_shift {
vec![sk]
}
else {
vec![]
}
};
loop {
let next_key = key_iter.next();
let next_char = char_iter.next();
match next_char {
None => break,
Some(ch) => match next_key {
None => panic!("More chars than keys in the row"),
Some(k) => {
if ch != ' ' {
match CHAR_ACCESS_MAP.get(&ch) {
None => panic!("Don't know how to type char {:?}", ch),
Some(sink_key) => {
if shift_down {
if alt_gr_down {
for sk in shift_keys {
for ak in alt_gr_keys {
res.push(Mapping { from: vec![*sk, *ak, *k], to: adapt(sink_key, sk), repeat: repeat.clone(), absorbing: shift_absorbing(*sk), ..Default::default() });
}
}
}
else {
for sk in shift_keys {
res.push(Mapping { from: vec![*sk, *k], to: adapt(sink_key, sk), repeat: repeat.clone(), absorbing: shift_absorbing(*sk), ..Default::default() });
}
}
}
else {
if alt_gr_down {
for ak in alt_gr_keys {
res.push(Mapping { from: vec![*ak, *k], to: adapt(sink_key, &LEFTSHIFT), repeat: repeat.clone(), ..Default::default() });
}
}
else {
res.push(Mapping { from: vec![*k], to: adapt(sink_key, &LEFTSHIFT), repeat: repeat.clone(), ..Default::default() });
}
}
}
}
}
}
}
}
}
res
}
pub fn make_us_mappings(layout: USKeyboardLayout, alt_gr_keys: &Vec<KeyCode>, disable_repeats: bool, absorb_shift: bool) -> Vec<Mapping> {
let shift_keys = &*US_SHIFT_KEYS;
let us_keycodes = &*US_KEYCODES;
let mut mappings = Vec::new();
mappings.append(&mut string_mappings(&vec![us_keycodes.tilde], layout.tilde.to_string(), false, false, &shift_keys, alt_gr_keys, disable_repeats, absorb_shift));
mappings.append(&mut string_mappings(&vec![us_keycodes.tilde], layout.tilde_shift.to_string(), true, false, &shift_keys, alt_gr_keys, disable_repeats, absorb_shift));
mappings.append(&mut string_mappings(&vec![us_keycodes.tilde], layout.tilde_alt_gr.to_string(), false, true, &shift_keys, alt_gr_keys, disable_repeats, absorb_shift));
mappings.append(&mut string_mappings(&vec![us_keycodes.tilde], layout.tilde_shift_alt_gr.to_string(), true, true, &shift_keys, alt_gr_keys, disable_repeats, absorb_shift));
mappings.append(&mut string_mappings(&us_keycodes.row_1, layout.row_1, false, false, &shift_keys, alt_gr_keys, disable_repeats, absorb_shift));
mappings.append(&mut string_mappings(&us_keycodes.row_1, layout.row_1_shift, true, false, &shift_keys, alt_gr_keys, disable_repeats, absorb_shift));
mappings.append(&mut string_mappings(&us_keycodes.row_1, layout.row_1_alt_gr, false, true, &shift_keys, alt_gr_keys, disable_repeats, absorb_shift));
mappings.append(&mut string_mappings(&us_keycodes.row_1, layout.row_1_shift_alt_gr, true, true, &shift_keys, alt_gr_keys, disable_repeats, absorb_shift));
mappings.append(&mut string_mappings(&us_keycodes.row_q, layout.row_q, false, false, &shift_keys, alt_gr_keys, disable_repeats, absorb_shift));
mappings.append(&mut string_mappings(&us_keycodes.row_q, layout.row_q_shift, true, false, &shift_keys, alt_gr_keys, disable_repeats, absorb_shift));
mappings.append(&mut string_mappings(&us_keycodes.row_q, layout.row_q_alt_gr, false, true, &shift_keys, alt_gr_keys, disable_repeats, absorb_shift));
mappings.append(&mut string_mappings(&us_keycodes.row_q, layout.row_q_shift_alt_gr, true, true, &shift_keys, alt_gr_keys, disable_repeats, absorb_shift));
mappings.append(&mut string_mappings(&us_keycodes.row_a, layout.row_a, false, false, &shift_keys, alt_gr_keys, disable_repeats, absorb_shift));
mappings.append(&mut string_mappings(&us_keycodes.row_a, layout.row_a_shift, true, false, &shift_keys, alt_gr_keys, disable_repeats, absorb_shift));
mappings.append(&mut string_mappings(&us_keycodes.row_a, layout.row_a_alt_gr, false, true, &shift_keys, alt_gr_keys, disable_repeats, absorb_shift));
mappings.append(&mut string_mappings(&us_keycodes.row_a, layout.row_a_shift_alt_gr, true, true, &shift_keys, alt_gr_keys, disable_repeats, absorb_shift));
mappings.append(&mut string_mappings(&us_keycodes.row_z, layout.row_z, false, false, &shift_keys, alt_gr_keys, disable_repeats, absorb_shift));
mappings.append(&mut string_mappings(&us_keycodes.row_z, layout.row_z_shift, true, false, &shift_keys, alt_gr_keys, disable_repeats, absorb_shift));
mappings.append(&mut string_mappings(&us_keycodes.row_z, layout.row_z_alt_gr, false, true, &shift_keys, alt_gr_keys, disable_repeats, absorb_shift));
mappings.append(&mut string_mappings(&us_keycodes.row_z, layout.row_z_shift_alt_gr, true, true, &shift_keys, alt_gr_keys, disable_repeats, absorb_shift));
mappings
}
|
mod mongoclient;
use mongoclient::MongoClient;
#[tokio::main]
async fn main() -> std::io::Result<()> {
// let my_mongo_client = MongoClient::from_environment().await;
// let collection = MongoClient::collection_wrap(of: "something");
let coll = MongoClient::proxy_for("db", "collection").await;
coll.simple_greet("Mongo proxy almost there !").await;
// Interface outline:
// coll.find_matching(filter) {}
// coll.update(filter, new_document) {}
// coll.delete(filter, new_document) {}
// coll.get_all() {}
Ok(())
} |
pub mod prelude {
pub use super::HttpStatus;
}
pub enum HttpStatus {
Ok,
NotFound,
}
impl HttpStatus {
pub fn code(&self) -> u32 {
match self {
HttpStatus::Ok => 200,
HttpStatus::NotFound => 404,
}
}
pub fn msg(&self) -> &str {
match self {
HttpStatus::Ok => "OK",
HttpStatus::NotFound => "Not Found",
}
}
pub fn status_line(&self) -> String {
const STATUS_LINE_PREFIX: &str = "HTTP/1.1";
format!("{} {} {}", STATUS_LINE_PREFIX, self.code(), self.msg())
}
}
|
const WHITE_XYZ: [f64; 3] = [0.95047, 1.0, 1.08883];
const CIELAB_D: f64 = 6.0 / 29.0;
const CIELAB_M: f64 = (29.0 / 6.0) * (29.0 / 6.0) / 3.0;
const CIELAB_C: f64 = 4.0 / 29.0;
const CIELAB_A: f64 = 3.0;
const CIELAB_MATRIX: [[f64; 3]; 3] = [
[ 0.0 , 1.16, 0.0 ],
[ 5.0 , -5.0 , 0.0 ],
[ 0.0 , 2.0 , -2.0 ],
];
const CIELAB_MATRIX_INV: [[f64; 3]; 3] = [
[ 0.86206897, 0.2 , 0.0 ],
[ 0.86206897, 0.0 , 0.0 ],
[ 0.86206897, 0.0 , -0.5 ],
];
const CIELAB_OFFSET: [f64; 3] = [-0.16, 0.0, 0.0];
fn cielab_from_linear(x: f64) -> f64 {
if x <= CIELAB_D.powf(CIELAB_A) {
CIELAB_M * x + CIELAB_C
} else {
x.powf(1.0 / CIELAB_A)
}
}
fn cielab_to_linear(y: f64) -> f64 {
if y <= CIELAB_D {
(y - CIELAB_C) / CIELAB_M
} else {
y.powf(CIELAB_A)
}
}
fn dot_mat_vec(m: [[f64; 3]; 3], v: [f64; 3]) -> [f64; 3] {
[
m[0][0] * v[0] + m[0][1] * v[1] + m[0][2] * v[2],
m[1][0] * v[0] + m[1][1] * v[1] + m[1][2] * v[2],
m[2][0] * v[0] + m[2][1] * v[1] + m[2][2] * v[2],
]
}
fn map_vec<F, T, R>(v: [T; 3], mut f: F) -> [R; 3]
where F: FnMut(T) -> R, T: Copy
{
[
f(v[0]),
f(v[1]),
f(v[2]),
]
}
fn zip_vec_with<F, T, U, R>(v: [T; 3], w: [U; 3], mut f: F) -> [R; 3]
where F: FnMut(T, U) -> R, T: Copy, U: Copy
{
[
f(v[0], w[0]),
f(v[1], w[1]),
f(v[2], w[2]),
]
}
fn add_vec(v: [f64; 3], w: [f64; 3]) -> [f64; 3] {
zip_vec_with(v, w, |x, y| x + y)
}
fn sub_vec(v: [f64; 3], w: [f64; 3]) -> [f64; 3] {
zip_vec_with(v, w, |x, y| x - y)
}
fn mul_vec(v: [f64; 3], w: [f64; 3]) -> [f64; 3] {
zip_vec_with(v, w, |x, y| x * y)
}
fn div_vec(v: [f64; 3], w: [f64; 3]) -> [f64; 3] {
zip_vec_with(v, w, |x, y| x / y)
}
fn cielab_to_xyz(lab: [f64; 3]) -> [f64; 3] {
let xyz = dot_mat_vec(CIELAB_MATRIX_INV, sub_vec(lab, CIELAB_OFFSET));
mul_vec(map_vec(xyz, cielab_to_linear), WHITE_XYZ)
}
fn cielab_from_xyz(xyz: [f64; 3]) -> [f64; 3] {
let xyz = map_vec(div_vec(xyz, WHITE_XYZ), cielab_from_linear);
add_vec(dot_mat_vec(CIELAB_MATRIX, xyz), CIELAB_OFFSET)
}
const SRGB_D: f64 = 0.04045;
const SRGB_M: f64 = 12.92;
const SRGB_A: f64 = 2.4;
const SRGB_K: f64 = 0.055;
const SRGB_MATRIX: [[f64; 3]; 3] = [
[ 3.2406, -1.5372, -0.4986],
[-0.9689, 1.8758, 0.0415],
[ 0.0557, -0.204 , 1.057 ],
];
const SRGB_MATRIX_INV: [[f64; 3]; 3] = [
[ 0.41239559, 0.35758343, 0.18049265],
[ 0.21258623, 0.7151703 , 0.0722005 ],
[ 0.01929722, 0.11918386, 0.95049713],
];
fn srgb_from_linear(x: f64) -> f64 {
let x = x.max(0.0).min(1.0);
if x <= SRGB_D / SRGB_M {
SRGB_M * x
} else {
(1.0 + SRGB_K) * x.powf(1.0 / SRGB_A) - SRGB_K
}
}
fn srgb_to_linear(y: f64) -> f64 {
let y = y.max(0.0).min(1.0);
if y <= SRGB_D {
y / SRGB_M
} else {
((y + SRGB_K) / (1.0 + SRGB_K)).powf(SRGB_A)
}
}
fn srgb_from_xyz(xyz: [f64; 3]) -> [f64; 3] {
map_vec(dot_mat_vec(SRGB_MATRIX, xyz), srgb_from_linear)
}
fn srgb_to_xyz(rgb: [f64; 3]) -> [f64; 3] {
dot_mat_vec(SRGB_MATRIX_INV, map_vec(rgb, srgb_to_linear))
}
#[no_mangle]
pub extern fn cielab_to_srgb(r: f64, g: f64, b: f64, out: &mut [f64; 3]) {
*out = srgb_from_xyz(cielab_to_xyz([r, g, b]));
}
#[no_mangle]
pub extern fn cielab_from_srgb(rgb: [f64; 3]) -> [f64; 3] {
cielab_from_xyz(srgb_to_xyz(rgb))
}
fn main() {}
|
#![doc = "generated by AutoRust 0.1.0"]
#![allow(unused_mut)]
#![allow(unused_variables)]
#![allow(unused_imports)]
use super::{models, API_VERSION};
#[non_exhaustive]
#[derive(Debug, thiserror :: Error)]
#[allow(non_camel_case_types)]
pub enum Error {
#[error(transparent)]
VaultCertificates_Create(#[from] vault_certificates::create::Error),
#[error(transparent)]
RegisteredIdentities_Delete(#[from] registered_identities::delete::Error),
#[error(transparent)]
ReplicationUsages_List(#[from] replication_usages::list::Error),
#[error(transparent)]
PrivateLinkResources_List(#[from] private_link_resources::list::Error),
#[error(transparent)]
PrivateLinkResources_Get(#[from] private_link_resources::get::Error),
#[error(transparent)]
RecoveryServices_CheckNameAvailability(#[from] recovery_services::check_name_availability::Error),
#[error(transparent)]
Vaults_ListBySubscriptionId(#[from] vaults::list_by_subscription_id::Error),
#[error(transparent)]
Operations_List(#[from] operations::list::Error),
#[error(transparent)]
Vaults_ListByResourceGroup(#[from] vaults::list_by_resource_group::Error),
#[error(transparent)]
Vaults_Get(#[from] vaults::get::Error),
#[error(transparent)]
Vaults_CreateOrUpdate(#[from] vaults::create_or_update::Error),
#[error(transparent)]
Vaults_Update(#[from] vaults::update::Error),
#[error(transparent)]
Vaults_Delete(#[from] vaults::delete::Error),
#[error(transparent)]
VaultExtendedInfo_Get(#[from] vault_extended_info::get::Error),
#[error(transparent)]
VaultExtendedInfo_CreateOrUpdate(#[from] vault_extended_info::create_or_update::Error),
#[error(transparent)]
VaultExtendedInfo_Update(#[from] vault_extended_info::update::Error),
#[error(transparent)]
Usages_ListByVaults(#[from] usages::list_by_vaults::Error),
}
pub mod vault_certificates {
use super::{models, API_VERSION};
pub async fn create(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
vault_name: &str,
certificate_name: &str,
certificate_request: &models::CertificateRequest,
) -> std::result::Result<models::VaultCertificateResponse, create::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/Subscriptions/{}/resourceGroups/{}/providers/Microsoft.RecoveryServices/vaults/{}/certificates/{}",
operation_config.base_path(),
subscription_id,
resource_group_name,
vault_name,
certificate_name
);
let mut url = url::Url::parse(url_str).map_err(create::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PUT);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(create::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(certificate_request).map_err(create::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(create::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(create::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::VaultCertificateResponse =
serde_json::from_slice(rsp_body).map_err(|source| create::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
Err(create::Error::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
})
}
}
}
pub mod create {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("Unexpected HTTP status code {}", status_code)]
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod registered_identities {
use super::{models, API_VERSION};
pub async fn delete(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
vault_name: &str,
identity_name: &str,
) -> std::result::Result<(), delete::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/Subscriptions/{}/resourceGroups/{}/providers/Microsoft.RecoveryServices/vaults/{}/registeredIdentities/{}",
operation_config.base_path(),
subscription_id,
resource_group_name,
vault_name,
identity_name
);
let mut url = url::Url::parse(url_str).map_err(delete::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::DELETE);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(delete::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(delete::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(delete::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::NO_CONTENT => Ok(()),
status_code => {
let rsp_body = rsp.body();
Err(delete::Error::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
})
}
}
}
pub mod delete {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("Unexpected HTTP status code {}", status_code)]
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod replication_usages {
use super::{models, API_VERSION};
pub async fn list(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
vault_name: &str,
) -> std::result::Result<models::ReplicationUsageList, list::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/Subscriptions/{}/resourceGroups/{}/providers/Microsoft.RecoveryServices/vaults/{}/replicationUsages",
operation_config.base_path(),
subscription_id,
resource_group_name,
vault_name
);
let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::ReplicationUsageList =
serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
Err(list::Error::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
})
}
}
}
pub mod list {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("Unexpected HTTP status code {}", status_code)]
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod private_link_resources {
use super::{models, API_VERSION};
pub async fn list(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
vault_name: &str,
) -> std::result::Result<models::PrivateLinkResources, list::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.RecoveryServices/vaults/{}/privateLinkResources",
operation_config.base_path(),
subscription_id,
resource_group_name,
vault_name
);
let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::PrivateLinkResources =
serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
Err(list::Error::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
})
}
}
}
pub mod list {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("Unexpected HTTP status code {}", status_code)]
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn get(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
vault_name: &str,
private_link_resource_name: &str,
) -> std::result::Result<models::PrivateLinkResource, get::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.RecoveryServices/vaults/{}/privateLinkResources/{}",
operation_config.base_path(),
subscription_id,
resource_group_name,
vault_name,
private_link_resource_name
);
let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::PrivateLinkResource =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
Err(get::Error::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
})
}
}
}
pub mod get {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("Unexpected HTTP status code {}", status_code)]
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod recovery_services {
use super::{models, API_VERSION};
pub async fn check_name_availability(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
location: &str,
input: &models::CheckNameAvailabilityParameters,
) -> std::result::Result<models::CheckNameAvailabilityResult, check_name_availability::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.RecoveryServices/locations/{}/checkNameAvailability",
operation_config.base_path(),
subscription_id,
resource_group_name,
location
);
let mut url = url::Url::parse(url_str).map_err(check_name_availability::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(check_name_availability::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(input).map_err(check_name_availability::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(check_name_availability::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(check_name_availability::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::CheckNameAvailabilityResult = serde_json::from_slice(rsp_body)
.map_err(|source| check_name_availability::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
Err(check_name_availability::Error::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
})
}
}
}
pub mod check_name_availability {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("Unexpected HTTP status code {}", status_code)]
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod vaults {
use super::{models, API_VERSION};
pub async fn list_by_subscription_id(
operation_config: &crate::OperationConfig,
subscription_id: &str,
) -> std::result::Result<models::VaultList, list_by_subscription_id::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.RecoveryServices/vaults",
operation_config.base_path(),
subscription_id
);
let mut url = url::Url::parse(url_str).map_err(list_by_subscription_id::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_subscription_id::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_subscription_id::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_subscription_id::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::VaultList = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_subscription_id::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
Err(list_by_subscription_id::Error::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
})
}
}
}
pub mod list_by_subscription_id {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("Unexpected HTTP status code {}", status_code)]
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list_by_resource_group(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
) -> std::result::Result<models::VaultList, list_by_resource_group::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.RecoveryServices/vaults",
operation_config.base_path(),
subscription_id,
resource_group_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_resource_group::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_resource_group::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_resource_group::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_resource_group::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::VaultList = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_resource_group::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
Err(list_by_resource_group::Error::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
})
}
}
}
pub mod list_by_resource_group {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("Unexpected HTTP status code {}", status_code)]
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn get(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
vault_name: &str,
) -> std::result::Result<models::Vault, get::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.RecoveryServices/vaults/{}",
operation_config.base_path(),
subscription_id,
resource_group_name,
vault_name
);
let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::Vault =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
Err(get::Error::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
})
}
}
}
pub mod get {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("Unexpected HTTP status code {}", status_code)]
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn create_or_update(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
vault_name: &str,
vault: &models::Vault,
) -> std::result::Result<create_or_update::Response, create_or_update::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.RecoveryServices/vaults/{}",
operation_config.base_path(),
subscription_id,
resource_group_name,
vault_name
);
let mut url = url::Url::parse(url_str).map_err(create_or_update::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PUT);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(create_or_update::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(vault).map_err(create_or_update::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(create_or_update::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(create_or_update::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::Vault = serde_json::from_slice(rsp_body)
.map_err(|source| create_or_update::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(create_or_update::Response::Ok200(rsp_value))
}
http::StatusCode::CREATED => {
let rsp_body = rsp.body();
let rsp_value: models::Vault = serde_json::from_slice(rsp_body)
.map_err(|source| create_or_update::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(create_or_update::Response::Created201(rsp_value))
}
status_code => {
let rsp_body = rsp.body();
Err(create_or_update::Error::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
})
}
}
}
pub mod create_or_update {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200(models::Vault),
Created201(models::Vault),
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("Unexpected HTTP status code {}", status_code)]
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn update(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
vault_name: &str,
vault: &models::PatchVault,
) -> std::result::Result<update::Response, update::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.RecoveryServices/vaults/{}",
operation_config.base_path(),
subscription_id,
resource_group_name,
vault_name
);
let mut url = url::Url::parse(url_str).map_err(update::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PATCH);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(update::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(vault).map_err(update::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(update::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(update::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::Vault =
serde_json::from_slice(rsp_body).map_err(|source| update::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(update::Response::Ok200(rsp_value))
}
http::StatusCode::CREATED => {
let rsp_body = rsp.body();
let rsp_value: models::Vault =
serde_json::from_slice(rsp_body).map_err(|source| update::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(update::Response::Created201(rsp_value))
}
status_code => {
let rsp_body = rsp.body();
Err(update::Error::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
})
}
}
}
pub mod update {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200(models::Vault),
Created201(models::Vault),
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("Unexpected HTTP status code {}", status_code)]
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn delete(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
vault_name: &str,
) -> std::result::Result<(), delete::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.RecoveryServices/vaults/{}",
operation_config.base_path(),
subscription_id,
resource_group_name,
vault_name
);
let mut url = url::Url::parse(url_str).map_err(delete::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::DELETE);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(delete::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(delete::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(delete::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => Ok(()),
status_code => {
let rsp_body = rsp.body();
Err(delete::Error::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
})
}
}
}
pub mod delete {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("Unexpected HTTP status code {}", status_code)]
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod operations {
use super::{models, API_VERSION};
pub async fn list(operation_config: &crate::OperationConfig) -> std::result::Result<models::ClientDiscoveryResponse, list::Error> {
let http_client = operation_config.http_client();
let url_str = &format!("{}/providers/Microsoft.RecoveryServices/operations", operation_config.base_path(),);
let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::ClientDiscoveryResponse =
serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
Err(list::Error::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
})
}
}
}
pub mod list {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("Unexpected HTTP status code {}", status_code)]
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod vault_extended_info {
use super::{models, API_VERSION};
pub async fn get(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
vault_name: &str,
) -> std::result::Result<models::VaultExtendedInfoResource, get::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.RecoveryServices/vaults/{}/extendedInformation/vaultExtendedInfo",
operation_config.base_path(),
subscription_id,
resource_group_name,
vault_name
);
let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::VaultExtendedInfoResource =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
Err(get::Error::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
})
}
}
}
pub mod get {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("Unexpected HTTP status code {}", status_code)]
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn create_or_update(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
vault_name: &str,
resource_resource_extended_info_details: &models::VaultExtendedInfoResource,
) -> std::result::Result<models::VaultExtendedInfoResource, create_or_update::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.RecoveryServices/vaults/{}/extendedInformation/vaultExtendedInfo",
operation_config.base_path(),
subscription_id,
resource_group_name,
vault_name
);
let mut url = url::Url::parse(url_str).map_err(create_or_update::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PUT);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(create_or_update::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(resource_resource_extended_info_details).map_err(create_or_update::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(create_or_update::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(create_or_update::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::VaultExtendedInfoResource = serde_json::from_slice(rsp_body)
.map_err(|source| create_or_update::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
Err(create_or_update::Error::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
})
}
}
}
pub mod create_or_update {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("Unexpected HTTP status code {}", status_code)]
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn update(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
vault_name: &str,
resource_resource_extended_info_details: &models::VaultExtendedInfoResource,
) -> std::result::Result<models::VaultExtendedInfoResource, update::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.RecoveryServices/vaults/{}/extendedInformation/vaultExtendedInfo",
operation_config.base_path(),
subscription_id,
resource_group_name,
vault_name
);
let mut url = url::Url::parse(url_str).map_err(update::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PATCH);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(update::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(resource_resource_extended_info_details).map_err(update::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(update::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(update::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::VaultExtendedInfoResource =
serde_json::from_slice(rsp_body).map_err(|source| update::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
Err(update::Error::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
})
}
}
}
pub mod update {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("Unexpected HTTP status code {}", status_code)]
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod usages {
use super::{models, API_VERSION};
pub async fn list_by_vaults(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
vault_name: &str,
) -> std::result::Result<models::VaultUsageList, list_by_vaults::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/Subscriptions/{}/resourceGroups/{}/providers/Microsoft.RecoveryServices/vaults/{}/usages",
operation_config.base_path(),
subscription_id,
resource_group_name,
vault_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_vaults::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_vaults::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(list_by_vaults::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_vaults::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::VaultUsageList =
serde_json::from_slice(rsp_body).map_err(|source| list_by_vaults::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
Err(list_by_vaults::Error::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
})
}
}
}
pub mod list_by_vaults {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("Unexpected HTTP status code {}", status_code)]
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
|
/*
MIT License
Copyright (c) 2021 Philipp Schuster
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
//! Library + CLI-Tool to measure the TTFB (time to first byte) of HTTP requests.
//! Additionally, this crate measures the times of DNS lookup, TCP connect and
//! TLS handshake. This crate currently only supports HTTP/1.1. It can cope with
//! TLS 1.2 and 1.3.LICENSE.
//!
//! See [`ttfb`] which is the main function of the public interface.
//!
//! ## Cross Platform
//! CLI + lib work on Linux, MacOS, and Windows.
use std::io::{Read as IoRead, Write as IoWrite};
use std::net::{IpAddr, TcpStream};
use std::str::FromStr;
use std::time::{Duration, Instant};
use native_tls::TlsConnector;
use regex::Regex;
use trust_dns_resolver::Resolver as DnsResolver;
use url::Url;
use crate::error::{InvalidUrlError, ResolveDnsError, TtfbError};
use crate::outcome::TtfbOutcome;
pub mod error;
pub mod outcome;
const CRATE_VERSION: &'static str = env!("CARGO_PKG_VERSION");
trait IoReadAndWrite: IoWrite + IoRead {}
impl<T: IoRead + IoWrite> IoReadAndWrite for T {}
/// Common super trait for TCP-Stream or TLS<TCP>-Stream.
trait TcpWithMaybeTlsStream: IoWrite + IoRead {}
/// Takes a URL and connects to it via http/1.1. Measures time for
/// DNS lookup, TCP connection start, TLS handshake, and TTFB (Time to First Byte)
/// of HTML content.
///
/// ## Parameters
/// - `input`: Url. Can be one of
/// - `phip1611.de` (defaults to `http://`)
/// - `http://phip1611.de`
/// - `https://phip1611.de`
/// - `https://phip1611.de?foo=bar`
/// - `https://sub.domain.phip1611.de?foo=bar`
/// - `http://12.34.56.78/foobar`
/// - `12.34.56.78/foobar` (defaults to `http://`)
/// - `12.34.56.78` (defaults to `http://`)
/// - `allow_insecure_certificates`: if illegal certificates (untrusted, expired) should be accepted
/// when https is used. Similar to `-k/--insecure` in `curl`.
///
/// ## Return value
/// [`TtfbOutcome`] or [`TtfbError`].
pub fn ttfb(input: String, allow_insecure_certificates: bool) -> Result<TtfbOutcome, TtfbError> {
if input.is_empty() {
return Err(TtfbError::InvalidUrl(InvalidUrlError::MissingInput));
}
let input = prepend_default_scheme_if_necessary(input);
let url = parse_input_as_url(&input)?;
assert_scheme_is_allowed(&url)?;
let (addr, dns_duration) = resolve_dns_if_necessary(&url)?;
let port = url.port_or_known_default().unwrap();
let (tcp, tcp_connect_duration) = tcp_connect(addr, port)?;
// Does TLS handshake if necessary: returns regular TCP stream if regular HTTP is used.
// We can write to the "tcp" trait object whatever content we want to. The underlying
// implementation will either send plain text or encrypt it for TLS.
let (mut tcp, tls_handshake_duration) = tls_handshake_if_necessary(tcp, &url, allow_insecure_certificates)?;
let (http_get_send_duration, http_ttfb_duration) = execute_http_get(&mut tcp, &url)?;
Ok(TtfbOutcome::new(
input,
addr,
port,
dns_duration,
tcp_connect_duration,
tls_handshake_duration,
http_get_send_duration,
http_ttfb_duration,
// http_content_download_duration,
))
}
/// Initializes the TCP connection to the IP address. Measures the duration.
fn tcp_connect(addr: IpAddr, port: u16) -> Result<(TcpStream, Duration), TtfbError> {
let addr_w_port = (addr, port);
let now = Instant::now();
let mut tcp = TcpStream::connect(addr_w_port).map_err(|err| TtfbError::CantConnectTcp(err))?;
tcp.flush()
.map_err(|err| TtfbError::OtherStreamError(err))?;
let tcp_connect_duration = now.elapsed();
Ok((tcp, tcp_connect_duration))
}
/// If the scheme is "https", this replaces the TCP-Stream with a TLS<TCP>-stream.
/// All data will be encrypted using the TLS-functionality of the crate `native-tls`.
/// If TLS is used, it measures the time of the TLS handshake.
fn tls_handshake_if_necessary(
tcp: TcpStream,
url: &Url,
allow_insecure_certificates: bool,
) -> Result<(Box<dyn IoReadAndWrite>, Option<Duration>), TtfbError> {
if url.scheme() == "https" {
assert_https_requires_domain_name(&url)?;
let tls = TlsConnector::builder()
.danger_accept_invalid_hostnames(allow_insecure_certificates)
.danger_accept_invalid_certs(allow_insecure_certificates)
.build()
.map_err(|err| TtfbError::CantConnectTls(err))?;
let now = Instant::now();
// hostname not used for DNS, only for certificate validation
let mut stream = tls
.connect(url.host_str().unwrap_or(""), tcp)
.map_err(|err| TtfbError::CantVerifyTls(err))?;
stream
.flush()
.map_err(|err| TtfbError::OtherStreamError(err))?;
let tls_handshake_duration = now.elapsed();
Ok((Box::new(stream), Some(tls_handshake_duration)))
} else {
Ok((Box::new(tcp), None))
}
}
/// Executes the HTTP/1.1 GET-Request on the given socket. This works with TCP or TLS<TCP>.
/// Afterwards, it waits for the first byte and measures all the times.
fn execute_http_get(
tcp: &mut Box<dyn IoReadAndWrite>,
url: &Url,
) -> Result<(Duration, Duration), TtfbError> {
let header = build_http11_header(url);
let now = Instant::now();
tcp.write_all(header.as_bytes())
.map_err(|err| TtfbError::CantConnectHttp(err))?;
tcp.flush()
.map_err(|err| TtfbError::OtherStreamError(err))?;
let get_request_send_duration = now.elapsed();
let mut one_byte_buf = [0_u8];
let now = Instant::now();
tcp.read_exact(&mut one_byte_buf)
.map_err(|err| TtfbError::CantConnectHttp(err))?;
let http_ttfb_duration = now.elapsed();
// todo can lead to error, not every server responds with EOF
// need to parse the request header and get the length from that
/*tcp.read_to_end(&mut content)
.map_err(|_| TtfbError::CantConnectHttp)?;
let http_content_download_duration = now.elapsed();
println!("http content:\n{}", unsafe {
String::from_utf8_unchecked(content)
});*/
Ok((
get_request_send_duration,
http_ttfb_duration,
// http_content_download_duration,
))
}
/// Constructs the header for a HTTP/1.1 GET-Request.
fn build_http11_header(url: &Url) -> String {
// with gzip, deflate, br we prevent
format!(
"GET {path} HTTP/1.1\r\n\
Host: {host}\r\n\
User-Agent: ttfb/{version}\r\n\
Accept: */*\r\n\
Accept-Encoding: gzip, deflate, br\r\n\
\r\n",
path = url.path(),
host = url.host_str().unwrap(),
version = CRATE_VERSION
)
}
/// Parses the string input into an [`Url`] object.
fn parse_input_as_url(input: &str) -> Result<Url, TtfbError> {
Url::parse(&input)
.map_err(|e| TtfbError::InvalidUrl(InvalidUrlError::WrongFormat(e.to_string())))
}
/// Prepends the default scheme "http://" is necessary. Without a scheme, [`parse_input_as_url`]
/// will fail.
fn prepend_default_scheme_if_necessary(url: String) -> String {
let regex = Regex::new("^(?P<scheme>.*://)?").unwrap();
let captures = regex.captures(&url);
let url_with_default_scheme = String::from("http://") + &url;
if captures.is_none() {
url_with_default_scheme
} else {
let captures = captures.unwrap();
if captures.name("scheme").is_some() {
url
} else {
url_with_default_scheme
}
}
}
/// If the user specifies the "https" scheme, we must have a domain name and no IP.
/// Otherwise we can't check the certificate.
fn assert_https_requires_domain_name(url: &Url) -> Result<(), TtfbError> {
if url.domain().is_none() && url.scheme() == "https" {
Err(TtfbError::InvalidUrl(
InvalidUrlError::HttpsRequiresDomainName,
))
} else {
Ok(())
}
}
/// Assert the scheme is on the allow list. Currently, we only allow "http" and "https".
fn assert_scheme_is_allowed(url: &Url) -> Result<(), TtfbError> {
let allowed_scheme = url.scheme() == "http" || url.scheme() == "https";
if allowed_scheme {
Ok(())
} else {
Err(TtfbError::InvalidUrl(InvalidUrlError::WrongScheme))
}
}
/// Checks from the URL if we already have an IP address or not.
/// If the user gave us a domain name, we resolve it using the [`trust-dns-resolver`]
/// crate and measure the time for it.
fn resolve_dns_if_necessary(url: &Url) -> Result<(IpAddr, Option<Duration>), TtfbError> {
Ok(if url.domain().is_none() {
let mut ip_str = url.host_str().unwrap();
// [a::b::c::d::e::f::0::1] => ipv6 address
if ip_str.starts_with('[') {
ip_str = &ip_str[1..ip_str.len() - 1];
}
let addr = IpAddr::from_str(ip_str)
.map_err(|e| TtfbError::InvalidUrl(InvalidUrlError::WrongFormat(e.to_string())))?;
(addr, None)
} else {
resolve_dns(&url).map(|(addr, dur)| (addr, Some(dur)))?
})
}
/// Actually resolves a domain using the systems default DNS resolver.
/// Helper function for [`resolve_dns_if_necessary`].
fn resolve_dns(url: &Url) -> Result<(IpAddr, Duration), TtfbError> {
// Construct a new DNS Resolver
// On Unix/Posix systems, this will read: /etc/resolv.conf
let resolver = DnsResolver::from_system_conf().unwrap();
let begin = Instant::now();
// at least on Linux this gets cached somehow in the background
// probably the DNS implementation/OS has a DNS cache
let response = resolver
.lookup_ip(url.host_str().unwrap())
.map_err(|err| TtfbError::CantResolveDns(ResolveDnsError::Other(err)))?;
let duration = begin.elapsed();
let ipv4_addrs = response
.iter()
.filter(|addr| addr.is_ipv4())
.collect::<Vec<_>>();
let ipv6_addrs = response
.iter()
.filter(|addr| addr.is_ipv6())
.collect::<Vec<_>>();
if !ipv4_addrs.is_empty() {
Ok((ipv4_addrs[0], duration))
} else if !ipv6_addrs.is_empty() {
Ok((ipv6_addrs[0], duration))
} else {
Err(TtfbError::CantResolveDns(ResolveDnsError::NoResults))
}
}
#[cfg(test)]
mod tests {
use crate::parse_input_as_url;
use super::*;
#[test]
fn test_parse_input_as_url() {
parse_input_as_url("http://google.com").expect("to be valid");
parse_input_as_url("https://google.com:443").expect("to be valid");
parse_input_as_url("http://google.com:80").expect("to be valid");
parse_input_as_url("google.com:80").expect("to be valid");
parse_input_as_url("http://google.com/foobar").expect("to be valid");
parse_input_as_url("https://google.com:443/foobar").expect("to be valid");
parse_input_as_url("https://goo-gle.com:443/foobar").expect("to be valid");
parse_input_as_url("https://goo-gle.com:443/foobar?124141").expect("to be valid");
parse_input_as_url("https://subdomain.goo-gle.com:443/foobar?124141").expect("to be valid");
parse_input_as_url("https://192.168.1.102:443/foobar?124141").expect("to be valid");
}
#[test]
fn test_append_scheme_if_necessary() {
assert_eq!(
prepend_default_scheme_if_necessary("phip1611.de".to_owned()),
"http://phip1611.de"
);
assert_eq!(
prepend_default_scheme_if_necessary("https://phip1611.de".to_owned()),
"https://phip1611.de"
);
assert_eq!(
prepend_default_scheme_if_necessary("192.168.1.102:443/foobar?124141".to_owned()),
"http://192.168.1.102:443/foobar?124141"
);
assert_eq!(
prepend_default_scheme_if_necessary(
"https://192.168.1.102:443/foobar?124141".to_owned()
),
"https://192.168.1.102:443/foobar?124141"
);
assert_eq!(
prepend_default_scheme_if_necessary("ftp://192.168.1.102:443/foobar?124141".to_owned()),
"ftp://192.168.1.102:443/foobar?124141"
);
}
#[test]
fn test_check_scheme() {
assert_scheme_is_allowed(
&Url::from_str(&prepend_default_scheme_if_necessary(
"phip1611.de".to_owned(),
))
.unwrap(),
)
.expect("must accept http");
assert_scheme_is_allowed(
&Url::from_str(&prepend_default_scheme_if_necessary(
"https://phip1611.de".to_owned(),
))
.unwrap(),
)
.expect("must accept http");
assert_scheme_is_allowed(
&Url::from_str(&prepend_default_scheme_if_necessary(
"ftp://phip1611.de".to_owned(),
))
.unwrap(),
)
.expect_err("must not accept ftp");
}
#[test]
fn test_resolve_dns_if_necessary() {
let url1 = Url::from_str("http://phip1611.de").expect("must be valid");
let url2 = Url::from_str("https://phip1611.de").expect("must be valid");
let url3 = Url::from_str("http://192.168.1.102").expect("must be valid");
let url4 = Url::from_str("http://[2001:0db8:3c4d:0015::1a2f:1a2b]").expect("must be valid");
let url5 = Url::from_str("http://[2001:0db8:3c4d:0015:0000:0000:1a2f:1a2b]")
.expect("must be valid");
resolve_dns_if_necessary(&url1).expect("must be valid");
resolve_dns_if_necessary(&url2).expect("must be valid");
resolve_dns_if_necessary(&url3).expect("must be valid");
resolve_dns_if_necessary(&url4).expect("must be valid");
resolve_dns_if_necessary(&url5).expect("must be valid");
}
// we ignore this test, because it relies on the given domain being available
#[ignore]
#[test]
fn test_single_run() {
let r = ttfb("http://phip1611.de".to_string(), false).unwrap();
assert!(r.dns_duration_rel().is_some());
assert!(r.tls_handshake_duration_rel().is_none());
let r = ttfb("https://phip1611.de".to_string(), false).unwrap();
assert!(r.dns_duration_rel().is_some());
assert!(r.tls_handshake_duration_rel().is_some());
let r = ttfb("https://expired.badssl.com".to_string(), false);
assert!(r.is_err());
let r = ttfb("https://expired.badssl.com".to_string(), true).unwrap();
assert!(r.dns_duration_rel().is_some());
assert!(r.tls_handshake_duration_rel().is_some());
}
}
|
/*
* 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 proc_macro2::{Span, TokenTree};
use quote::{format_ident, quote};
use std::collections::HashSet;
use syn::{
parse::ParseStream, parse_macro_input, token, Data, DeriveInput, Error, Expr, GenericArgument,
Ident, Path, PathArguments, ReturnType, Token, Type,
};
// This macro does two related derivations depending on whether there are any generic parameters.
//
// struct A(B) ==> coerce both ways between A and B
// struct A<T>(...) => coerce A<T1> to A<T2> if coerce T1 to T2 and all the fields support it
pub fn derive_coerce(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = parse_macro_input!(input as DeriveInput);
if let Err(err) = check_repr(&input) {
return err.into_compile_error().into();
}
if input.generics.type_params().count() == 0 {
let field = match &input.data {
Data::Struct(x) if x.fields.len() == 1 => x.fields.iter().next().unwrap(),
_ => {
return syn::Error::new_spanned(
input,
"Type-parameter free types must be a single field struct",
)
.into_compile_error()
.into();
}
};
let type1 = input.ident;
let type2 = &field.ty;
let lifetimes = input.generics.lifetimes().collect::<Vec<_>>();
let gen = quote! {
unsafe impl < #(#lifetimes),* > gazebo::coerce::Coerce<#type1< #(#lifetimes),* >> for #type2 {}
unsafe impl < #(#lifetimes),* > gazebo::coerce::Coerce<#type2> for #type1< #(#lifetimes),* > {}
};
gen.into()
} else {
// unsafe impl <To__T, From__T> Coerce<X<To__T>> X<From__T> where ...
let name = &input.ident;
let mut ty_args = HashSet::new();
let mut ty_args_to = Vec::new();
let mut ty_args_from = Vec::new();
for t in input.generics.type_params() {
ty_args.insert(t.ident.clone());
ty_args_to.push(format_ident!("To{}", t.ident));
ty_args_from.push(format_ident!("From{}", t.ident));
}
let mut constraints = Vec::new();
let fields: Vec<_> = match &input.data {
Data::Struct(x) => x.fields.iter().collect(),
Data::Enum(x) => x.variants.iter().flat_map(|x| &x.fields).collect(),
_ => {
return syn::Error::new_spanned(input, "Type-parameter cannot be a union")
.into_compile_error()
.into();
}
};
for x in fields {
let mut to_ty = x.ty.clone();
let mut from_ty = x.ty.clone();
let to = replace_type(&mut to_ty, &ty_args, "To");
let from = replace_type(&mut from_ty, &ty_args, "From");
if to.is_none() || from.is_none() {
return syn::Error::new_spanned(
&input,
"Don't know how to deal with some of the fields",
)
.into_compile_error()
.into();
}
if to_ty != from_ty {
constraints.push(quote! { #from_ty : gazebo::coerce::Coerce< #to_ty >});
}
}
let gen = quote! {
unsafe impl < #(#ty_args_from),* , #(#ty_args_to),* >
gazebo::coerce::Coerce<#name < #(#ty_args_to),* >>
for #name < #(#ty_args_from),* >
where #(#constraints),* {}
};
gen.into()
}
}
fn replace_type(ty: &mut Type, idents: &HashSet<Ident>, prefix: &str) -> Option<()> {
match ty {
Type::Path(x)
if x.qself.is_none()
&& x.path.segments.len() == 1
&& x.path.segments[0].arguments.is_empty() =>
{
let i = &mut x.path.segments[0].ident;
if idents.contains(i) {
*i = format_ident!("{}{}", prefix, i);
}
Some(())
}
_ => descend_type(ty, |ty| replace_type(ty, idents, prefix)),
}
}
/// Descend into all the nested type values within a type, or return None if you don't know how
fn descend_type(ty: &mut Type, op: impl Fn(&mut Type) -> Option<()>) -> Option<()> {
match ty {
Type::Array(x) => op(&mut x.elem),
Type::Group(x) => op(&mut x.elem),
Type::Never(_) => Some(()),
Type::Paren(x) => op(&mut x.elem),
Type::Path(x) => {
if let Some(qself) = &mut x.qself {
op(&mut qself.ty)?;
}
for p in x.path.segments.iter_mut() {
match &mut p.arguments {
PathArguments::None => {}
PathArguments::AngleBracketed(x) => {
x.args.iter_mut().try_for_each(|x| match x {
GenericArgument::Type(x) => op(x),
_ => Some(()),
})?
}
PathArguments::Parenthesized(x) => {
x.inputs.iter_mut().try_for_each(&op)?;
if let ReturnType::Type(_, ty) = &mut x.output {
op(ty)?;
}
}
}
}
Some(())
}
Type::Ptr(x) => op(&mut x.elem),
Type::Reference(x) => op(&mut x.elem),
Type::Slice(x) => op(&mut x.elem),
Type::Tuple(xs) => xs.elems.iter_mut().try_for_each(op),
_ => None,
}
}
// Taken from ref_cast: https://github.com/dtolnay/ref-cast/blob/eadd839cc0db116e4fc9bfee5dd29dde82089eed/derive/src/lib.rs#L91
fn check_repr(input: &DeriveInput) -> syn::Result<()> {
let mut has_repr = false;
let mut errors = None;
let mut push_error = |error| match &mut errors {
Some(errors) => Error::combine(errors, error),
None => errors = Some(error),
};
for attr in &input.attrs {
if attr.path.is_ident("repr") {
if let Err(error) = attr.parse_args_with(|input: ParseStream| {
while !input.is_empty() {
let path = input.call(Path::parse_mod_style)?;
if path.is_ident("C") || path.is_ident("transparent") {
has_repr = true;
} else if path.is_ident("packed") {
// ignore
} else {
let meta_item_span = if input.peek(token::Paren) {
let group: TokenTree = input.parse()?;
quote!(#path #group)
} else if input.peek(Token![=]) {
let eq_token: Token![=] = input.parse()?;
let value: Expr = input.parse()?;
quote!(#path #eq_token #value)
} else {
quote!(#path)
};
let msg = if path.is_ident("align") {
"aligned repr on struct that implements Coerce is not supported"
} else {
"unrecognized repr on struct that implements Coerce"
};
push_error(Error::new_spanned(meta_item_span, msg));
}
if !input.is_empty() {
input.parse::<Token![,]>()?;
}
}
Ok(())
}) {
push_error(error);
}
}
}
if !has_repr {
let mut requires_repr = Error::new(
Span::call_site(),
"Coerce trait requires #[repr(C)] or #[repr(transparent)]",
);
if let Some(errors) = errors {
requires_repr.combine(errors);
}
errors = Some(requires_repr);
}
match errors {
None => Ok(()),
Some(errors) => Err(errors),
}
}
|
// Underlying typed representation of task fields, shared across other parts of the code base
use std::ops::RangeInclusive;
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Annotation;
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Context<'a>(&'a str);
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct End<'a>(pub &'a str);
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Entry<'a>(pub &'a str);
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Key<'a>(&'a str);
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Marker;
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Normal<'a>(&'a str);
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Number(usize);
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Pair<'a> {
pub key: Key<'a>,
pub value: Value<'a>,
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Priority(u8);
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Project<'a>(&'a str);
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Space<'a>(&'a str);
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Value<'a>(&'a str);
#[derive(Clone, Copy, PartialEq, PartialOrd)]
pub enum Stage {
Marker,
End,
Priority,
Entry,
Body,
}
impl Annotation {
pub fn new(str: &str) -> Option<Self> {
match str == "|" {
true => Some(Annotation),
false => None,
}
}
pub fn len(&self) -> usize {
"|".len()
}
}
impl<'a> Context<'a> {
pub fn new(str: &'a str) -> Option<Self> {
match str.starts_with('@') {
true => Some(Context(str)),
false => None,
}
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn as_str(&self) -> &str {
self.0
}
}
impl<'a> End<'a> {
pub fn new(str: &'a str, stage: Stage) -> Option<Self> {
match stage == Stage::End && is_yyyy_mm_dd(str) {
true => Some(End(str)),
false => None,
}
}
pub fn as_str(&self) -> &'a str {
self.0
}
pub fn len(&self) -> usize {
self.0.len()
}
}
impl<'a> Entry<'a> {
pub fn new(str: &'a str, stage: Stage) -> Option<Self> {
match stage <= Stage::Entry && is_yyyy_mm_dd(str) {
true => Some(Entry(str)),
false => None,
}
}
pub fn as_str(&self) -> &'a str {
self.0
}
pub fn len(&self) -> usize {
self.0.len()
}
}
impl<'a> Key<'a> {
pub fn new(str: &'a str) -> Self {
Key(str)
}
pub fn as_str(&self) -> &'a str {
self.0
}
pub fn len(&self) -> usize {
self.0.len()
}
}
impl Marker {
pub fn new(str: &str, stage: Stage) -> Option<Self> {
match stage == Stage::Marker && str == "x" {
true => Some(Marker),
false => None,
}
}
pub fn len(&self) -> usize {
"x".len()
}
}
impl<'a> Normal<'a> {
pub fn new(str: &'a str) -> Self {
Normal(str)
}
pub fn as_str(&self) -> &'a str {
self.0
}
pub fn len(&self) -> usize {
self.0.len()
}
}
impl Number {
pub fn from_enumerate(nr: usize) -> Self {
// enumerate is zero indexed, line numbers are one indexed
Number(nr + 1)
}
pub const fn from_usize(nr: usize) -> Self {
Number(nr)
}
pub fn from_str(str: &str) -> Option<Self> {
Some(Number(str.parse::<usize>().ok()?))
}
pub fn new_range(str: &str) -> Option<RangeInclusive<Self>> {
let (a, b) = str.split_once('-')?;
let a = Number::from_str(a)?;
let b = Number::from_str(b)?;
match a <= b {
true => Some(a..=b),
false => Some(b..=a),
}
}
pub fn new_list(str: &str) -> Option<Vec<Self>> {
let mut nrs = Vec::new();
for str in str.split(',') {
nrs.push(Number::from_str(str)?);
}
Some(nrs)
}
pub const fn digits(&self) -> usize {
let mut nr = self.0;
let mut len = 0;
while nr > 0 {
nr /= 10;
len += 1;
}
len
}
pub fn as_usize(&self) -> usize {
self.0
}
}
impl<'a> Pair<'a> {
pub fn new(str: &'a str) -> Option<Self> {
str.split_once(':').map(|(k, v)| Pair {
key: Key(k),
value: Value(v),
})
}
pub fn len(&self) -> usize {
self.key.len() + ":".len() + self.value.len()
}
}
impl Priority {
pub fn new(str: &str, stage: Stage) -> Option<Self> {
if stage > Stage::Priority {
return None;
}
str.strip_prefix('(')
.and_then(|str| str.strip_suffix(')'))
.filter(|str| str.len() == 1)
.and_then(|str| str.chars().next())
.and_then(Priority::from_char)
}
pub fn new_range(str: &str) -> Option<RangeInclusive<Self>> {
let mut chars = Some(str)
.filter(|str| str.len() == 5)
.and_then(|str| str.strip_prefix('('))
.and_then(|str| str.strip_suffix(')'))
.map(|str| str.chars())?;
let a = Priority::from_char(chars.next()?)?;
let _ = chars.next().filter(|&c| c == '-')?;
let b = Priority::from_char(chars.next()?)?;
match a <= b {
true => Some(a..=b),
false => Some(b..=a),
}
}
pub fn from_char(c: char) -> Option<Self> {
match ('A'..='Z').contains(&c) {
true => Some(Priority(c as u8)),
false => None,
}
}
pub fn as_u8(&self) -> u8 {
self.0 as u8
}
pub fn len(&self) -> usize {
"(x)".len()
}
}
impl<'a> Project<'a> {
pub fn new(str: &'a str) -> Option<Self> {
match str.starts_with('+') {
true => Some(Project(str)),
false => None,
}
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn as_str(&self) -> &str {
self.0
}
}
impl<'a> Space<'a> {
pub fn new(str: &'a str) -> Option<Self> {
match str.chars().all(|c| c.is_ascii_whitespace()) {
true => Some(Space(str)),
false => None,
}
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn as_str(&self) -> &str {
self.0
}
}
impl Stage {
pub fn new() -> Stage {
Stage::Marker
}
}
impl<'a> Value<'a> {
pub fn new(str: &'a str) -> Self {
Value(str)
}
pub fn as_str(&self) -> &'a str {
self.0
}
pub fn len(&self) -> usize {
self.0.len()
}
}
fn is_yyyy_mm_dd(str: &str) -> bool {
let mut chars = str.chars();
chars.next().map(|c| c.is_ascii_digit()) == Some(true)
&& chars.next().map(|c| c.is_ascii_digit()) == Some(true)
&& chars.next().map(|c| c.is_ascii_digit()) == Some(true)
&& chars.next().map(|c| c.is_ascii_digit()) == Some(true)
&& chars.next().map(|c| c == '-') == Some(true)
&& chars.next().map(|c| c == '0' || c == '1') == Some(true)
&& chars.next().map(|c| c.is_ascii_digit()) == Some(true)
&& chars.next().map(|c| c == '-') == Some(true)
&& chars.next().map(|c| ('0'..='3').contains(&c)) == Some(true)
&& chars.next().map(|c| c.is_ascii_digit()) == Some(true)
&& chars.next().is_none()
}
|
#![allow(clippy::missing_safety_doc)]
use libc::*;
use std::ffi::CString;
use std::slice;
// types
pub enum CSymbolTable {}
pub enum CExpression {}
pub enum CParser {}
pub enum CppString {}
// simple types used for communications with C++
#[repr(C)]
pub struct Pair<T, U>(pub T, pub U);
pub type CStrList = Pair<size_t, *const *const c_char>;
impl CStrList {
pub unsafe fn get_slice(&self) -> &[*const c_char] {
slice::from_raw_parts(self.1, self.0 as usize)
}
}
#[repr(C)]
pub struct CParseError {
pub is_err: bool,
pub mode: c_int,
pub token_type: *const c_char,
pub token_value: *const c_char,
pub diagnostic: *const c_char,
pub error_line: *const c_char,
pub line_no: size_t,
pub column_no: size_t,
}
// for deallocating CString from C
#[no_mangle]
pub unsafe extern "C" fn free_rust_cstring(s: *mut c_char) {
let _ = CString::from_raw(s);
}
// functions without polymorphism
extern "C" {
// these methods depend on a specific precision
pub fn symbol_table_new() -> *mut CSymbolTable;
pub fn symbol_table_add_variable(
t: *mut CSymbolTable,
variable_name: *const c_char,
value: *const c_double,
is_constant: bool,
) -> bool;
pub fn symbol_table_add_constant(
t: *mut CSymbolTable,
variable_name: *const c_char,
value: c_double,
) -> bool;
pub fn symbol_table_create_variable(
t: *mut CSymbolTable,
variable_name: *const c_char,
value: c_double,
) -> bool;
pub fn symbol_table_add_stringvar(
t: *mut CSymbolTable,
variable_name: *const c_char,
string: *mut CppString,
is_const: bool,
) -> bool;
pub fn symbol_table_create_stringvar(
t: *mut CSymbolTable,
variable_name: *const c_char,
string: *const c_char,
) -> bool;
pub fn symbol_table_add_vector(
t: *mut CSymbolTable,
variable_name: *const c_char,
ptr: *const c_double,
len: size_t,
) -> bool;
pub fn symbol_table_remove_variable(t: *mut CSymbolTable, name: *const c_char) -> bool;
pub fn symbol_table_remove_stringvar(t: *mut CSymbolTable, name: *const c_char) -> bool;
pub fn symbol_table_remove_vector(t: *mut CSymbolTable, name: *const c_char) -> bool;
pub fn symbol_table_clear_variables(t: *mut CSymbolTable);
pub fn symbol_table_clear_strings(t: *mut CSymbolTable);
pub fn symbol_table_clear_vectors(t: *mut CSymbolTable);
pub fn symbol_table_clear_local_constants(t: *mut CSymbolTable);
pub fn symbol_table_clear_functions(t: *mut CSymbolTable);
pub fn symbol_table_variable_ref(
t: *mut CSymbolTable,
variable_name: *const c_char,
) -> *mut c_double;
pub fn symbol_table_stringvar_ref(
t: *mut CSymbolTable,
variable_name: *const c_char,
) -> *mut CppString;
pub fn symbol_table_vector_ptr(
t: *mut CSymbolTable,
variable_name: *const c_char,
) -> *const c_double;
pub fn symbol_table_set_string(
t: *mut CSymbolTable,
ptr: *const CppString,
string: *const c_char,
);
pub fn symbol_table_variable_count(t: *mut CSymbolTable) -> size_t;
pub fn symbol_table_stringvar_count(t: *mut CSymbolTable) -> size_t;
pub fn symbol_table_vector_count(t: *mut CSymbolTable) -> size_t;
pub fn symbol_table_function_count(t: *mut CSymbolTable) -> size_t;
pub fn symbol_table_add_pi(t: *mut CSymbolTable) -> bool;
pub fn symbol_table_add_epsilon(t: *mut CSymbolTable) -> bool;
pub fn symbol_table_add_infinity(t: *mut CSymbolTable) -> bool;
pub fn symbol_table_get_variable_list(t: *mut CSymbolTable) -> *mut CStrList;
pub fn symbol_table_get_stringvar_list(t: *mut CSymbolTable) -> *mut CStrList; //StringPtrList;
pub fn symbol_table_get_vector_list(t: *mut CSymbolTable) -> *mut CStrList;
pub fn symbol_table_valid(t: *mut CSymbolTable) -> bool;
pub fn symbol_table_symbol_exists(t: *mut CSymbolTable, name: *const c_char) -> bool;
pub fn symbol_table_load_from(t: *mut CSymbolTable, other: *const CSymbolTable);
pub fn symbol_table_add_constants(t: *mut CSymbolTable) -> bool;
pub fn symbol_table_is_constant_node(t: *mut CSymbolTable, name: *const c_char) -> bool;
pub fn symbol_table_is_constant_string(t: *mut CSymbolTable, name: *const c_char) -> bool;
pub fn symbol_table_destroy(t: *mut CSymbolTable);
// // blocked by #5668
// macro_rules! func_declare {
// ($add_name:ident, $free_name:ident, $($ty:ty),*) => {
// pub fn $add_name(t: *mut CSymbolTable, name: *const c_char,
// cb: extern fn (*mut c_void, $($ty),*) -> c_double,
// user_data: *mut c_void) -> Pair<bool, *mut c_void>;
// pub fn $free_name(c_func: *mut c_void);
// }
// }
pub fn symbol_table_add_func1(
t: *mut CSymbolTable,
name: *const c_char,
cb: extern "C" fn(*mut c_void, c_double) -> c_double,
user_data: *mut c_void,
) -> Pair<bool, *mut c_void>;
pub fn symbol_table_free_func1(c_func: *mut c_void);
pub fn symbol_table_add_func2(
t: *mut CSymbolTable,
name: *const c_char,
cb: extern "C" fn(*mut c_void, c_double, c_double) -> c_double,
user_data: *mut c_void,
) -> Pair<bool, *mut c_void>;
pub fn symbol_table_free_func2(c_func: *mut c_void);
pub fn symbol_table_add_func3(
t: *mut CSymbolTable,
name: *const c_char,
cb: extern "C" fn(*mut c_void, c_double, c_double, c_double) -> c_double,
user_data: *mut c_void,
) -> Pair<bool, *mut c_void>;
pub fn symbol_table_free_func3(c_func: *mut c_void);
pub fn symbol_table_add_func4(
t: *mut CSymbolTable,
name: *const c_char,
cb: extern "C" fn(*mut c_void, c_double, c_double, c_double, c_double) -> c_double,
user_data: *mut c_void,
) -> Pair<bool, *mut c_void>;
pub fn symbol_table_free_func4(c_func: *mut c_void);
pub fn symbol_table_add_func5(
t: *mut CSymbolTable,
name: *const c_char,
cb: extern "C" fn(
*mut c_void,
c_double,
c_double,
c_double,
c_double,
c_double,
) -> c_double,
user_data: *mut c_void,
) -> Pair<bool, *mut c_void>;
pub fn symbol_table_free_func5(c_func: *mut c_void);
pub fn symbol_table_add_func6(
t: *mut CSymbolTable,
name: *const c_char,
cb: extern "C" fn(
*mut c_void,
c_double,
c_double,
c_double,
c_double,
c_double,
c_double,
) -> c_double,
user_data: *mut c_void,
) -> Pair<bool, *mut c_void>;
pub fn symbol_table_free_func6(c_func: *mut c_void);
pub fn symbol_table_add_func7(
t: *mut CSymbolTable,
name: *const c_char,
cb: extern "C" fn(
*mut c_void,
c_double,
c_double,
c_double,
c_double,
c_double,
c_double,
c_double,
) -> c_double,
user_data: *mut c_void,
) -> Pair<bool, *mut c_void>;
pub fn symbol_table_free_func7(c_func: *mut c_void);
pub fn symbol_table_add_func8(
t: *mut CSymbolTable,
name: *const c_char,
cb: extern "C" fn(
*mut c_void,
c_double,
c_double,
c_double,
c_double,
c_double,
c_double,
c_double,
c_double,
) -> c_double,
user_data: *mut c_void,
) -> Pair<bool, *mut c_void>;
pub fn symbol_table_free_func8(c_func: *mut c_void);
pub fn symbol_table_add_func9(
t: *mut CSymbolTable,
name: *const c_char,
cb: extern "C" fn(
*mut c_void,
c_double,
c_double,
c_double,
c_double,
c_double,
c_double,
c_double,
c_double,
c_double,
) -> c_double,
user_data: *mut c_void,
) -> Pair<bool, *mut c_void>;
pub fn symbol_table_free_func9(c_func: *mut c_void);
pub fn symbol_table_add_func10(
t: *mut CSymbolTable,
name: *const c_char,
cb: extern "C" fn(
*mut c_void,
c_double,
c_double,
c_double,
c_double,
c_double,
c_double,
c_double,
c_double,
c_double,
c_double,
) -> c_double,
user_data: *mut c_void,
) -> Pair<bool, *mut c_void>;
pub fn symbol_table_free_func10(c_func: *mut c_void);
// Expression
pub fn expression_new() -> *mut CExpression;
pub fn expression_register_symbol_table(e: *mut CExpression, t: *const CSymbolTable);
pub fn expression_value(e: *mut CExpression) -> c_double;
pub fn expression_destroy(e: *mut CExpression);
pub fn parser_new() -> *mut CParser;
pub fn parser_destroy(p: *mut CParser);
pub fn parser_compile(p: *mut CParser, s: *const c_char, e: *const CExpression) -> bool;
pub fn parser_compile_resolve(
p: *mut CParser,
s: *const c_char,
e: *const CExpression,
cb: extern "C" fn(*const c_char, *mut c_void) -> *const c_char,
fn_pointer: *mut c_void,
) -> bool;
pub fn parser_error(p: *mut CParser) -> *const CParseError;
pub fn parser_error_free(p: *const CParseError);
pub fn string_array_free(l: *mut CStrList);
pub fn cpp_string_create(s: *const c_char, len: size_t) -> *mut CppString;
pub fn cpp_string_set(s: *mut CppString, replacement: *const c_char, len: size_t);
pub fn cpp_string_get(s: *const CppString) -> *const c_char;
pub fn cpp_string_free(s: *mut CppString);
}
|
// Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
use core::cmp;
use math::FieldElement;
use utils::collections::Vec;
// CONSTANTS
// ================================================================================================
const MIN_BLOWUP_FACTOR: usize = 2;
const MIN_CYCLE_LENGTH: usize = 2;
// TRANSITION CONSTRAINT GROUP
// ================================================================================================
/// A group of transition constraints all having the same degree.
///
/// A transition constraint group does not actually store transition constraints - it stores only
/// their indexes and the info needed to compute their random linear combination. The indexes are
/// assumed to be consistent with the order in which constraint evaluations are written into the
/// `evaluation` table by the [Air::evaluate_transition()](crate::Air::evaluate_transition)
/// function.
///
/// A transition constraint is described by a ration function of the form $\frac{C(x)}{z(x)}$,
/// where:
/// * $C(x)$ is the constraint polynomial.
/// * $z(x)$ is the constraint divisor polynomial.
///
/// The divisor polynomial is the same for all transition constraints (see
/// [Air::transition_constraint_divisor()](crate::Air::transition_constraint_divisor())) and for
/// this reason is not stored in a transition constraint group.
#[derive(Clone, Debug)]
pub struct TransitionConstraintGroup<E: FieldElement> {
degree: TransitionConstraintDegree,
degree_adjustment: u32,
indexes: Vec<usize>,
coefficients: Vec<(E, E)>,
}
impl<E: FieldElement> TransitionConstraintGroup<E> {
// CONSTRUCTOR
// --------------------------------------------------------------------------------------------
/// Returns a new transition constraint group to hold constraints of the specified degree.
pub(super) fn new(
degree: TransitionConstraintDegree,
trace_poly_degree: usize,
composition_degree: usize,
) -> Self {
// We want to make sure that once we divide a constraint polynomial by its divisor, the
// degree of the resulting polynomial will be exactly equal to the composition_degree.
// For transition constraints, divisor degree = deg(trace). So, target degree for all
// transitions constraints is simply: deg(composition) + deg(trace)
let target_degree = composition_degree + trace_poly_degree;
let evaluation_degree = degree.get_evaluation_degree(trace_poly_degree + 1);
let degree_adjustment = (target_degree - evaluation_degree) as u32;
TransitionConstraintGroup {
degree,
degree_adjustment,
indexes: vec![],
coefficients: vec![],
}
}
// PUBLIC ACCESSORS
// --------------------------------------------------------------------------------------------
/// Returns indexes of all constraints in this group.
pub fn indexes(&self) -> &[usize] {
&self.indexes
}
/// Returns degree descriptors for all constraints in this group.
pub fn degree(&self) -> &TransitionConstraintDegree {
&self.degree
}
/// Adds a new constraint to the group. The constraint is identified by an index in the
/// evaluation table.
pub fn add(&mut self, constraint_idx: usize, coefficients: (E, E)) {
self.indexes.push(constraint_idx);
self.coefficients.push(coefficients);
}
// EVALUATOR
// --------------------------------------------------------------------------------------------
/// Computes a linear combination of evaluations relevant to this constraint group.
///
/// The linear combination is computed as follows:
/// $$
/// \sum_{i=0}^{k-1}{C_i(x) \cdot (\alpha_i + \beta_i \cdot x^d)}
/// $$
/// where:
/// * $C_i(x)$ is the evaluation of the $i$th constraint at `x` (same as `evaluations[i]`).
/// * $\alpha$ and $\beta$ are random field elements. In the interactive version of the
/// protocol, these are provided by the verifier.
/// * $d$ is the degree adjustment factor computed as $D + (n - 1) - deg(C_i(x))$, where
/// $D$ is the degree of the composition polynomial, $n$ is the length of the execution
/// trace, and $deg(C_i(x))$ is the evaluation degree of the $i$th constraint.
///
/// There are two things to note here. First, the degree adjustment factor $d$ is the same
/// for all constraints in the group (since all constraints have the same degree). Second,
/// the merged evaluations represent a polynomial of degree $D + n - 1$, which is higher
/// then the target degree of the composition polynomial. This is because at this stage,
/// we are merging only the numerators of transition constraints, and we will need to divide
/// them by the divisor later on. The degree of the divisor for transition constraints is
/// always $n - 1$. Thus, once we divide out the divisor, the evaluations will represent a
/// polynomial of degree $D$.
pub fn merge_evaluations<B>(&self, evaluations: &[B], x: B) -> E
where
B: FieldElement,
E: From<B>,
{
// compute degree adjustment factor for this group
let xp = E::from(x.exp(self.degree_adjustment.into()));
// compute linear combination of evaluations as D(x) * (cc_0 + cc_1 * x^p), where D(x)
// is an evaluation of a particular constraint, and x^p is the degree adjustment factor
let mut result = E::ZERO;
for (&constraint_idx, coefficients) in self.indexes.iter().zip(self.coefficients.iter()) {
let evaluation = E::from(evaluations[constraint_idx]);
result += evaluation * (coefficients.0 + coefficients.1 * xp);
}
result
}
}
// TRANSITION CONSTRAINT DEGREE
// ================================================================================================
/// Degree descriptor of a transition constraint.
///
/// Describes constraint degree as a combination of multiplications of periodic and trace
/// registers. For example, degree of a constraint which requires multiplication of two trace
/// registers can be described as: `base: 2, cycles: []`. A constraint which requires
/// multiplication of 3 trace registers and a periodic register with a period of 32 steps can be
/// described as: `base: 3, cycles: [32]`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TransitionConstraintDegree {
base: usize,
cycles: Vec<usize>,
}
impl TransitionConstraintDegree {
/// Creates a new transition constraint degree descriptor for constraints which involve
/// multiplications of trace registers only.
///
/// For example, if a constraint involves multiplication of two trace registers, `degree`
/// should be set to 2. If a constraint involves multiplication of three trace registers,
/// `degree` should be set to 3 etc.
///
/// # Panics
/// Panics if the provided `degree` is zero.
pub fn new(degree: usize) -> Self {
assert!(
degree > 0,
"transition constraint degree must be at least one, but was zero"
);
TransitionConstraintDegree {
base: degree,
cycles: vec![],
}
}
/// Creates a new transition degree descriptor for constraints which involve multiplication
/// of trace registers and periodic columns.
///
/// For example, if a constraint involves multiplication of two trace registers and one
/// periodic column with a period length of 32 steps, `base_degree` should be set to 2,
/// and `cycles` should be set to `vec![32]`.
///
/// # Panics
/// Panics if:
/// * `base_degree` is zero.
/// * Any of the values in the `cycles` vector is smaller than two or is not powers of two.
pub fn with_cycles(base_degree: usize, cycles: Vec<usize>) -> Self {
assert!(
base_degree > 0,
"transition constraint degree must be at least one, but was zero"
);
for (i, &cycle) in cycles.iter().enumerate() {
assert!(
cycle >= MIN_CYCLE_LENGTH,
"cycle length must be at least {}, but was {} for cycle {}",
MIN_CYCLE_LENGTH,
cycle,
i
);
assert!(
cycle.is_power_of_two(),
"cycle length must be a power of two, but was {} for cycle {}",
cycle,
i
);
}
TransitionConstraintDegree {
base: base_degree,
cycles,
}
}
/// Computes a degree to which this degree description expands in the context of execution
/// trace of the specified length.
///
/// The expanded degree is computed as follows:
///
/// $$
/// b \cdot (n - 1) + \sum_{i = 0}^{k - 1}{\frac{n \cdot (c_i - 1)}{c_i}}
/// $$
///
/// where: $b$ is the base degree, $n$ is the `trace_length`, $c_i$ is a cycle length of
/// periodic column $i$, and $k$ is the total number of periodic columns for this degree
/// descriptor.
///
/// Thus, evaluation degree of a transition constraint which involves multiplication of two
/// trace registers and one periodic column with a period length of 32 steps when evaluated
/// over an execution trace of 64 steps would be:
///
/// $$
/// 2 \cdot (64 - 1) + \frac{64 \cdot (32 - 1)}{32} = 126 + 62 = 188
/// $$
pub fn get_evaluation_degree(&self, trace_length: usize) -> usize {
let mut result = self.base * (trace_length - 1);
for cycle_length in self.cycles.iter() {
result += (trace_length / cycle_length) * (cycle_length - 1);
}
result
}
/// Returns a minimum blowup factor needed to evaluate constraint of this degree.
///
/// This is guaranteed to be a power of two, greater than one.
pub fn min_blowup_factor(&self) -> usize {
cmp::max(
(self.base + self.cycles.len()).next_power_of_two(),
MIN_BLOWUP_FACTOR,
)
}
}
// EVALUATION FRAME
// ================================================================================================
/// A set of execution trace rows required for evaluation of transition constraints.
///
/// In the current implementation, an evaluation frame always contains two consecutive rows of the
/// execution trace. It is passed in as one of the parameters into
/// [Air::evaluate_transition()](crate::Air::evaluate_transition) function.
#[derive(Debug, Clone)]
pub struct EvaluationFrame<E: FieldElement> {
current: Vec<E>,
next: Vec<E>,
}
impl<E: FieldElement> EvaluationFrame<E> {
// CONSTRUCTORS
// --------------------------------------------------------------------------------------------
/// Returns a new evaluation frame instantiated with the specified number of registers.
///
/// # Panics
/// Panics if `num_registers` is zero.
pub fn new(num_registers: usize) -> Self {
assert!(
num_registers > 0,
"number of registers must be greater than zero"
);
EvaluationFrame {
current: E::zeroed_vector(num_registers),
next: E::zeroed_vector(num_registers),
}
}
/// Returns a new evaluation frame instantiated from the provided rows.
///
/// # Panics
/// Panics if:
/// * Lengths of the provided rows are zero.
/// * Lengths of the provided rows are not the same.
pub fn from_rows(current: Vec<E>, next: Vec<E>) -> Self {
assert!(!current.is_empty(), "a row must contain at least one value");
assert_eq!(
current.len(),
next.len(),
"number of values in the rows must be the same"
);
Self { current, next }
}
// ROW ACCESSORS
// --------------------------------------------------------------------------------------------
/// Returns a reference to the current row.
#[inline(always)]
pub fn current(&self) -> &[E] {
&self.current
}
/// Returns a mutable reference to the current row.
#[inline(always)]
pub fn current_mut(&mut self) -> &mut [E] {
&mut self.current
}
/// Returns a reference to the next row.
#[inline(always)]
pub fn next(&self) -> &[E] {
&self.next
}
/// Returns a mutable reference to the next row.
#[inline(always)]
pub fn next_mut(&mut self) -> &mut [E] {
&mut self.next
}
}
|
mod util;
mod scanner;
mod parser;
mod resolver;
mod bash_backend;
mod rust_backend;
use std::env;
use std::process;
use std::fs;
fn usage(cmd: &str) {
eprintln!("Usage: {} {{-t|--target bash|rust}} <source.rss>", cmd);
process::exit(1);
}
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() != 4 ||
(args[1] != "-t" && args[1] != "--target") ||
(args[2] != "bash" && args[2] != "rust") {
usage(&args[0]);
}
let (target, filename) = (&args[2], &args[3]);
compile(filename, target);
}
fn compile(filename: &str, target: &str) {
let file: Vec<char> = fs::read_to_string(filename)
.expect("error reading file")
.chars()
.collect();
let tokens = scanner::scan(file);
let stmts = parser::parse(tokens);
let sym_table = resolver::gen_sym_table(&stmts);
if target == "bash" {
bash_backend::gen_code(&stmts,
&String::from(filename).replace(".rss", ".sh"));
} else {
rust_backend::gen_code(&stmts,
&sym_table,
&String::from(filename).replace(".rss", ".rs"));
}
}
|
// Copyright (C) 2020 Sebastian Dröge <sebastian@centricular.com>
//
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use super::*;
/// `CSeq` header ([RFC 7826 section 18.20](https://tools.ietf.org/html/rfc7826#section-18.20)).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct CSeq(u32);
impl std::ops::Deref for CSeq {
type Target = u32;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl std::ops::DerefMut for CSeq {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl AsRef<u32> for CSeq {
fn as_ref(&self) -> &u32 {
&self.0
}
}
impl AsMut<u32> for CSeq {
fn as_mut(&mut self) -> &mut u32 {
&mut self.0
}
}
impl From<u32> for CSeq {
fn from(v: u32) -> CSeq {
CSeq(v)
}
}
impl From<CSeq> for u32 {
fn from(v: CSeq) -> u32 {
v.0
}
}
impl super::TypedHeader for CSeq {
fn from_headers(headers: impl AsRef<Headers>) -> Result<Option<Self>, HeaderParseError> {
let headers = headers.as_ref();
let header = match headers.get(&CSEQ) {
None => return Ok(None),
Some(header) => header,
};
let cseq = header
.as_str()
.parse::<u32>()
.map(CSeq)
.map_err(|_| HeaderParseError)?;
Ok(Some(cseq))
}
fn insert_into(&self, mut headers: impl AsMut<Headers>) {
let headers = headers.as_mut();
headers.insert(CSEQ, self.0.to_string());
}
}
|
use std::{io::{Read, Result, Write}, net::{TcpListener, TcpStream}};
use std::time::Duration;
use std::thread;
fn handle_connection(mut stream: TcpStream, wait_time: u64) -> Result<()> {
let mut buf = [0; 1024];
// 服务端需要接受用户输入, 但是为了而防止恶意输入, 不能无限等待用户, 需要设置一定的缓冲区
// 客户端可以通过\n表示返回信息结束
loop {
let buf_read = stream.read(&mut buf)?;
if buf_read == 0 {
return Ok(())
}
println!("read 1 {} buf_now {}", buf_read, String::from_utf8_lossy(&buf));
thread::sleep(Duration::from_secs(wait_time));
stream.write("foo -------------".as_bytes())?;
stream.write(&buf[..buf_read])?;
stream.write("这是第二段请求反正".as_bytes())?;
stream.write("\n".as_bytes())?;
}
}
fn main() -> Result<()> {
let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
for stream in listener.incoming() {
handle_connection(stream?, 1)?;
}
Ok(())
} |
#![feature(box_syntax, box_patterns)]
use core::fmt::Debug;
use std::collections::VecDeque;
use std::collections::HashMap;
#[derive(Debug, Clone)]
enum Term {
Literal(String),
Int(i64),
LogicVariable(String),
Pair(Box<Term>, Box<Term>),
Three(Box<Term>, Box<Term>, Box<Term>)
}
impl Into<Term> for &i64 {
fn into(self) -> Term {
Term::Int(*self)
}
}
impl Into<Term> for i64 {
fn into(self) -> Term {
Term::Int(self)
}
}
impl Into<Term> for &str {
fn into(self) -> Term {
self.to_string().into()
}
}
impl Into<Term> for String {
fn into(self) -> Term {
if self.starts_with("?") {
Term::LogicVariable(self)
} else {
Term::Literal(self)
}
}
}
impl Into<Term> for &String {
fn into(self) -> Term {
Term::Literal(self.to_string())
}
}
impl<T : Into<Term>, S : Into<Term>> Into<Term> for (T, S) {
fn into(self) -> Term {
Term::Pair(Box::new(self.0.into()), Box::new(self.1.into()))
}
}
impl<T : Into<Term>, S : Into<Term>, R : Into<Term>> Into<Term> for (T, S, R) {
fn into(self) -> Term {
Term::Three(Box::new(self.0.into()), Box::new(self.1.into()), Box::new(self.2.into()))
}
}
impl<T : Into<Term>, S : Into<Term>> Into<Rule> for (T, S) {
fn into(self) -> Rule {
Rule {
left: self.0.into(),
right: self.1.into(),
}
}
}
struct TermIter {
queue: VecDeque<Box<Term>>,
}
impl TermIter {
fn new(term: Term) -> TermIter {
let mut queue = VecDeque::new();
for child in term.children_not_mut() {
queue.push_front(child);
};
TermIter {
queue: queue,
}
}
// I didn't implement a real iterator. But hopefully
// this is some start to one.
// Going to run into problems with lifetimes in associated types?
// https://lukaskalbertodt.github.io/2018/08/03/solving-the-generalized-streaming-iterator-problem-without-gats.html
fn next(&mut self) -> Option<Box<Term>> {
let mut fuel = 0;
loop {
fuel += 1;
if fuel > 20 {
println!("Fuel Ran Out!");
return None
}
if let Some(child) = self.queue.pop_front() {
match child {
box Term::Int(_) => return Some(child),
box Term::Literal(_) => return Some(child),
box Term::LogicVariable(_) => return Some(child),
box Term::Pair(l, r) => {
self.queue.push_front(r);
if l.is_atom() {
return Some(l);
} else {
for child in l.children_not_mut() {
self.queue.push_front(child)
}
continue;
}
},
box Term::Three(l, m, r) => {
self.queue.push_front(r);
self.queue.push_front(m);
if l.is_atom() {
return Some(l);
} else {
for child in l.children_not_mut() {
self.queue.push_front(child)
}
}
}
};
} else {
return None
}
}
}
}
impl Term {
fn is_atom(&self) -> bool {
match self {
Term::Int(_) => true,
Term::Literal(_) => true,
Term::LogicVariable(_) => true,
_ => false,
}
}
fn children<'a>(&'a mut self) -> Vec<&'a mut Box<Term>> {
match self {
Term::Pair(ref mut t1, ref mut t2) => vec![t2, t1],
Term::Three(ref mut t1, ref mut t2, ref mut t3) => vec![t3, t2, t1],
_ => vec![]
}
}
fn children_not_mut<'a>(self) -> Vec<Box<Term>> {
match self {
Term::Pair(t1, t2) => vec![t2, t1],
Term::Three(t1, t2, t3) => vec![t3, t2, t1],
_ => vec![]
}
}
// This strategy is wrong sadly. See comment below
// So maybe, I keep state between calls in the form of the queue?
// not 100% sure how that would work out, but seems doable.
fn rewrite_once<F>(&mut self, f: F) -> bool where
F: Fn(& Term) -> Option<Term>{
let mut queue = VecDeque::new();
let result = f(self);
if result.is_some() {
*self = result.unwrap();
return true;
}
for child in self.children() {
queue.push_front(child);
}
while !queue.is_empty() {
let node = queue.pop_front().unwrap();
let result = f(node);
if result.is_some() {
**node = result.unwrap();
return true;
} else {
for child in node.children() {
queue.push_front(child)
}
}
}
return false;
}
}
#[derive(Debug, Clone)]
struct TermContext {
finished: bool
}
impl Default for TermContext {
fn default() -> Self {
TermContext { finished: false }
}
}
#[derive(Debug, Clone)]
struct Rule {
left: Term,
right: Term,
}
// Maybe I do something like this.
// get next node
// rewrite
// if rule applied next is self
// else next iterates through children
// So I can say, give me node, rewrite, give me node rewrite, forever until done.alloc
// Rewrite does need to go through the phases. But that seems reasonable.
// So this works. I'm not sure if it is right or not.
// Intuitively it does seem like I need to always start from the outside and work my way in.
// What if a rewrite rule makes it so that some more general rule matches?
// I need to actual make rules and logic variables, with real substitution.
// I need meta-evaluation. I need phases. I need some ffi?
impl Rule {
fn run(self, term : & Term) -> Option<Term> {
let mut env : HashMap<String, Term> = HashMap::new();
let mut queue = VecDeque::new();
queue.push_front((&self.left, term));
let mut failed = false;
while !queue.is_empty() && !failed {
let elem = queue.pop_front().unwrap();
match elem {
// Need to handle non-linear
(Term::LogicVariable(s), t) => {
env.insert(s.to_string(), t.clone());
},
(Term::Literal(ref s1), Term::Literal(ref s2)) if s1 == s2 => {},
(Term::Int(ref n1), Term::Int(ref n2)) if n1 == n2 => {},
(Term::Pair(a1, b1), Term::Pair(a2, b2)) => {
queue.push_front((&*a1, &*a2));
queue.push_front((&*b1, &*b2));
},
(Term::Three(a1, b1, c1), Term::Three(a2, b2, c2)) => {
queue.push_front((&*a1, &*a2));
queue.push_front((&*b1, &*b2));
queue.push_front((&*c1, &*c2));
},
_ => {
failed = true;
}
};
};
let f = |term : & Term| {
match term {
Term::LogicVariable(s) => Some(env.get(s).unwrap().clone()),
_ => None
}
};
let mut right = self.right.clone();
if !failed {
while right.rewrite_once(f) {}
Some(right)
} else {
None
}
}
}
fn main() {
let fib = |term : & Term| {
match term {
Term::Pair(box Term::Literal(ref fib), box Term::Int(ref number)) if fib == "fib" && *number == 0 => Some(0.into()),
Term::Pair(box Term::Literal(ref fib), box Term::Int(ref number)) if fib == "fib" && *number == 1 => Some(1.into()),
Term::Pair(box Term::Literal(ref fib), box Term::Int(n)) if fib == "fib"=>
Some(("+", ("fib", ("-", n, 1),
("fib", ("-", n, 2)))).into()),
Term::Three(box Term::Literal(ref f), box Term::Int(n), box Term::Int(m)) if f == "-" => Some(Term::Int(n - m)),
Term::Three(box Term::Literal(ref f), box Term::Int(n), box Term::Int(m)) if f == "+" => Some(Term::Int(n + m)),
_ => None
}
};
let fact = |term : & Term| {
match term {
Term::Pair(box Term::Literal(ref fact), box Term::Int(ref number)) if fact == "fact" && *number == 0 => Some(1.into()),
Term::Pair(box Term::Literal(ref fact), box Term::Int(n)) if fact == "fact"=>
Some(("*", n, ("fact", ("-", n, 1))).into()),
Term::Three(box Term::Literal(ref f), box Term::Int(n), box Term::Int(m)) if f == "-" => Some(Term::Int(n - m)),
Term::Three(box Term::Literal(ref f), box Term::Int(n), box Term::Int(m)) if f == "+" => Some(Term::Int(n + m)),
Term::Three(box Term::Literal(ref f), box Term::Int(n), box Term::Int(m)) if f == "*" => Some(Term::Int(n * m)),
_ => None
}
};
let my_rule = Rule {
left: "?x".into(),
right: "thing".into(),
};
// let t = my_rule.run(& "test".into());
// println!("{:?}", t);
// It seems that this proves that my evaluation strategy is wrong.
// If we do fact(1) => 1 * fact(1 - 1)
// then our fact(?n) rule is going to match on fact(1 - 1)
// which will then expand infinitely.
// let fact2 = |term : & Term| {
// let fact0 : Rule = (("fact", 0), 1).into();
// let fact_n : Rule = (("fact", "?x"), ("*", "?x", ("fact", ("-", "?x", 1)))).into();
// let math = |term : & Term| {
// match term {
// Term::Three(box Term::Literal(ref f), box Term::Int(n), box Term::Int(m)) if f == "-" => Some(Term::Int(n - m)),
// Term::Three(box Term::Literal(ref f), box Term::Int(n), box Term::Int(m)) if f == "+" => Some(Term::Int(n + m)),
// Term::Three(box Term::Literal(ref f), box Term::Int(n), box Term::Int(m)) if f == "*" => Some(Term::Int(n * m)),
// _ => None
// }
// };
// fact0.run(term).or_else(|| math(term)).or_else(|| fact_n.run(term))
// };
// let fact0 : Rule = (("fact", 0), 1).into();
// let t1 = fact0.run(& ("fact", 0).into());
// println!("{:?}", t1);
let my_fact_test : Term = (("fact", 1)).into();
let mut iter = TermIter::new(my_fact_test);
let mut x = iter.next().unwrap();
let y = iter.next();
*x = Term::Int(2);
let z = iter.next();
println!("{:?}, {:?}, {:?}", x, y, z);
// println!("{:?}", my_fact_test);
// let y = iter.next();
// println!("{:?}", my_fact_test);
// let mut fuel = 0;
// while my_fact_test.rewrite_once(fact) && fuel < 3 {
// println!("{:?}", my_fact_test);
// fuel += 1;
// }
// println!("{:?}", my_fact_test);
}
|
use std::f32;
use types::Point2;
#[derive(Clone, Copy, Debug)]
pub struct BoundingBox {
pub topleft: Point2,
pub bottomright: Point2,
}
impl BoundingBox {
pub fn new(l: f32, r: f32, t: f32, b: f32) -> BoundingBox {
BoundingBox {
topleft: Point2::new(l, t),
bottomright: Point2::new(r, b),
}
}
/*pub fn new_empty() -> BoundingBox {
BoundingBox::new(f32::INFINITY, -f32::INFINITY, f32::INFINITY, -f32::INFINITY)
}
pub fn top(&self) -> f32 { self.topleft.y }
pub fn bottom(&self) -> f32 { self.bottomright.y }
pub fn left(&self) -> f32 { self.topleft.x }
pub fn right(&self) -> f32 { self.bottomright.x }
pub fn merge(&mut self, other: &BoundingBox) {
self.topleft.x = f32::min(self.topleft.x, other.topleft.x);
self.topleft.y = f32::min(self.topleft.y, other.topleft.y);
self.bottomright.x = f32::max(self.bottomright.x, other.bottomright.x);
self.bottomright.y = f32::max(self.bottomright.y, other.bottomright.y);
}
pub fn is_hit(&self, x: f32, y: f32) -> bool {
x >= self.topleft.x && y >= self.topleft.y && x <= self.bottomright.x && y <= self.bottomright.y
}*/
pub fn intersects(&self, other: &BoundingBox) -> bool {
let ax = self.topleft.x + self.bottomright.x;
let ay = self.topleft.y + self.bottomright.y;
let bx = other.topleft.x + other.bottomright.x;
let by = other.topleft.y + other.bottomright.y;
let aw = self.bottomright.x - self.topleft.x;
let ah = self.bottomright.y - self.topleft.y;
let bw = other.bottomright.x - other.topleft.x;
let bh = other.bottomright.y - other.topleft.y;
f32::abs(ax - bx) < (aw + bw) && f32::abs(ay - by) < (ah + bh)
}
}
|
use std::sync::Arc;
use async_trait::async_trait;
use axum::{
extract::{rejection::JsonRejection, Extension, FromRequest},
routing::{get, post, Router},
};
use svc_utils::middleware::{CorsLayer, LogLayer, MeteredRoute};
use super::api::v1::class::{
commit_edition, create_timestamp, read, read_by_scope, read_property, recreate, update,
update_by_scope, update_property,
};
use super::api::v1::minigroup::{
create as create_minigroup, create_whiteboard, download as download_minigroup,
};
use super::api::v1::p2p::{convert as convert_p2p, create as create_p2p};
use super::api::v1::webinar::{
convert_webinar, create_webinar, create_webinar_replica, download_webinar,
};
use super::api::v1::{
account, minigroup::restart_transcoding as restart_transcoding_minigroup,
webinar::restart_transcoding as restart_transcoding_webinar,
};
use super::api::{
redirect_to_frontend, rollback, v1::create_event, v1::healthz,
v1::redirect_to_frontend as redirect_to_frontend2,
};
use super::info::{list_frontends, list_scopes};
use super::{api::v1::authz::proxy as proxy_authz, error::ErrorExt};
use crate::app::AppContext;
use crate::db::class::{MinigroupType, P2PType, WebinarType};
pub fn router(ctx: Arc<dyn AppContext>, authn: svc_authn::jose::ConfigMap) -> Router {
let router = redirects_router()
.merge(webinars_router())
.merge(p2p_router())
.merge(minigroups_router())
.merge(authz_router())
.merge(utils_router());
router
.layer(Extension(Arc::new(authn)))
.layer(Extension(ctx))
.layer(LogLayer::new())
}
fn redirects_router() -> Router {
Router::new()
.metered_route("/info/scopes", get(list_scopes))
.metered_route("/info/frontends", get(list_frontends))
.metered_route(
"/redirs/tenants/:tenant/apps/:app",
get(redirect_to_frontend),
)
.metered_route("/api/scopes/:scope/rollback", post(rollback))
.metered_route("/healthz", get(healthz))
.metered_route("/api/v1/scopes/:scope/rollback", post(rollback))
.metered_route("/api/v1/redirs", get(redirect_to_frontend2))
.metered_route(
"/api/v1/redirs/tenants/:tenant/apps/:app",
get(redirect_to_frontend2),
)
}
fn webinars_router() -> Router {
Router::new()
.metered_route(
"/api/v1/webinars/:id",
get(read::<WebinarType>).put(update::<WebinarType>),
)
.metered_route(
"/api/v1/audiences/:audience/webinars/:scope",
get(read_by_scope::<WebinarType>),
)
.metered_route(
"/api/v1/webinars/:id/timestamps",
post(create_timestamp::<WebinarType>),
)
.metered_route("/api/v1/webinars/:id/events", post(create_event))
.metered_route(
"/api/v1/webinars/:id/properties/:property_id",
get(read_property).put(update_property),
)
.layer(CorsLayer)
.metered_route("/api/v1/webinars", post(create_webinar))
.metered_route(
"/api/v1/webinars/:id/replicas",
post(create_webinar_replica),
)
.metered_route("/api/v1/webinars/convert", post(convert_webinar))
.metered_route("/api/v1/webinars/:id/download", get(download_webinar))
.metered_route(
"/api/v1/webinars/:id/recreate",
post(recreate::<WebinarType>),
)
}
fn p2p_router() -> Router {
Router::new()
.metered_route("/api/v1/p2p/:id", get(read::<P2PType>))
.metered_route(
"/api/v1/audiences/:audience/p2p/:scope",
get(read_by_scope::<P2PType>),
)
.metered_route(
"/api/v1/p2p/:id/properties/:property_id",
get(read_property).put(update_property),
)
.layer(CorsLayer)
.metered_route("/api/v1/p2p", post(create_p2p))
.metered_route("/api/v1/p2p/convert", post(convert_p2p))
.metered_route("/api/v1/p2p/:id/events", post(create_event))
}
fn minigroups_router() -> Router {
Router::new()
.metered_route(
"/api/v1/minigroups/:id",
get(read::<MinigroupType>).put(update::<MinigroupType>),
)
.metered_route(
"/api/v1/audiences/:audience/minigroups/:scope",
get(read_by_scope::<MinigroupType>).put(update_by_scope::<MinigroupType>),
)
.metered_route(
"/api/v1/minigroups/:id/timestamps",
post(create_timestamp::<MinigroupType>),
)
.metered_route(
"/api/v1/minigroups/:id/properties/:property_id",
get(read_property).put(update_property),
)
.layer(CorsLayer)
.metered_route(
"/api/v1/minigroups/:id/recreate",
post(recreate::<MinigroupType>),
)
.metered_route("/api/v1/minigroups", post(create_minigroup))
.metered_route("/api/v1/minigroups/:id/download", get(download_minigroup))
.metered_route("/api/v1/minigroups/:id/events", post(create_event))
.metered_route("/api/v1/minigroups/:id/whiteboard", post(create_whiteboard))
}
fn authz_router() -> Router {
Router::new().metered_route("/api/v1/authz/:audience", post(proxy_authz))
}
fn utils_router() -> Router {
Router::new()
.metered_route(
"/api/v1/audiences/:audience/classes/:scope/editions/:id",
post(commit_edition),
)
.metered_route(
"/api/v1/account/properties/:property_id",
get(account::read_property).put(account::update_property),
)
.metered_route(
"/api/v1/transcoding/minigroup/:id/restart",
post(restart_transcoding_minigroup),
)
.metered_route(
"/api/v1/transcoding/webinar/:id/restart",
post(restart_transcoding_webinar),
)
.layer(CorsLayer)
}
pub struct Json<T>(pub T);
#[async_trait]
impl<B, T> FromRequest<B> for Json<T>
where
axum::Json<T>: FromRequest<B, Rejection = JsonRejection>,
B: Send + 'static,
{
type Rejection = super::error::Error;
async fn from_request(
req: &mut axum::extract::RequestParts<B>,
) -> Result<Self, Self::Rejection> {
match axum::Json::<T>::from_request(req).await {
Ok(value) => Ok(Self(value.0)),
Err(rejection) => {
let kind = match rejection {
JsonRejection::JsonDataError(_)
| JsonRejection::JsonSyntaxError(_)
| JsonRejection::MissingJsonContentType(_) => {
super::error::ErrorKind::InvalidPayload
}
_ => super::error::ErrorKind::InternalFailure,
};
Err(rejection).error(kind)
}
}
}
}
|
// Copyright 2019, 2020 Wingchain
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use futures::prelude::*;
use futures::task::{Context, Poll};
use futures_timer::Delay;
use std::pin::Pin;
use std::time::{Duration, SystemTime};
pub struct Scheduler {
duration: Option<u64>,
delay: Option<Delay>,
}
impl Scheduler {
pub fn new(duration: Option<u64>) -> Self {
Self {
duration,
delay: None,
}
}
}
#[derive(Clone, Debug)]
pub struct ScheduleInfo {
pub timestamp: u64,
}
impl Stream for Scheduler {
type Item = ScheduleInfo;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let duration = match self.duration {
Some(v) => v,
None => return Poll::Pending,
};
self.delay = match self.delay.take() {
None => {
// schedule wait.
let wait_duration = time_until_next(duration_now(), duration);
Some(Delay::new(wait_duration))
}
Some(d) => Some(d),
};
if let Some(ref mut delay) = self.delay {
match Future::poll(Pin::new(delay), cx) {
Poll::Pending => return Poll::Pending,
Poll::Ready(()) => {}
}
}
self.delay = None;
let timestamp = duration_now().as_millis() as u64;
let schedule_info = ScheduleInfo { timestamp };
Poll::Ready(Some(schedule_info))
}
}
fn time_until_next(now: Duration, duration: u64) -> Duration {
let remaining_full_millis = duration - (now.as_millis() as u64 % duration) - 1;
Duration::from_millis(remaining_full_millis)
}
fn duration_now() -> Duration {
let now = SystemTime::now();
now.duration_since(SystemTime::UNIX_EPOCH)
.unwrap_or_else(|e| {
panic!(
"Current time {:?} is before unix epoch. Something is wrong: {:?}",
now, e,
)
})
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.