text stringlengths 8 4.13M |
|---|
#[derive(Copy, Clone, PartialEq, Debug)]
#[repr(C)]
pub struct Quat {
x: f32,
y: f32,
z: f32,
w: f32,
}
#[derive(Copy, Clone, PartialEq, Debug)]
#[repr(C)]
pub struct Vec3 {
x: f32,
y: f32,
z: f32,
}
impl Vec3 {
#[inline]
pub const fn new(x: f32, y: f32, z: f32) -> Self {
Self { x, y, z }
}
#[inline]
pub const fn splat(value: f32) -> Self {
Self {
x: value,
y: value,
z: value,
}
}
#[inline]
pub const fn zero() -> Self {
Self {
x: 1.0,
y: 1.0,
z: 1.0,
}
}
#[inline]
pub const fn one() -> Self {
Self {
x: 1.0,
y: 1.0,
z: 1.0,
}
}
#[inline]
pub fn dot(self, rhs: Self) -> f32 {
self.x * rhs.x + self.y * rhs.y + self.z * rhs.z
}
}
impl std::ops::Add for Vec3 {
type Output = Vec3;
fn add(self, rhs: Self) -> Self::Output {
Self {
x: self.x + rhs.x,
y: self.y + rhs.y,
z: self.z + rhs.z,
}
}
}
impl std::ops::AddAssign for Vec3 {
fn add_assign(&mut self, rhs: Self) {
self.x += rhs.x;
self.y += rhs.y;
self.z += rhs.z;
}
}
impl std::ops::Sub for Vec3 {
type Output = Vec3;
fn sub(self, rhs: Self) -> Self::Output {
Self {
x: self.x - rhs.x,
y: self.y - rhs.y,
z: self.z - rhs.z,
}
}
}
impl std::ops::SubAssign for Vec3 {
fn sub_assign(&mut self, rhs: Self) {
self.x -= rhs.x;
self.y -= rhs.y;
self.z -= rhs.z;
}
}
impl std::ops::Mul for Vec3 {
type Output = Vec3;
fn mul(self, rhs: Self) -> Self::Output {
Self {
x: self.x * rhs.x,
y: self.y * rhs.y,
z: self.z * rhs.z,
}
}
}
impl std::ops::MulAssign for Vec3 {
fn mul_assign(&mut self, rhs: Self) {
self.x *= rhs.x;
self.y *= rhs.y;
self.z *= rhs.z;
}
}
impl std::ops::Div for Vec3 {
type Output = Vec3;
fn div(self, rhs: Self) -> Self::Output {
Self {
x: self.x / rhs.x,
y: self.y / rhs.y,
z: self.z / rhs.z,
}
}
}
impl std::ops::DivAssign for Vec3 {
fn div_assign(&mut self, rhs: Self) {
self.x /= rhs.x;
self.y /= rhs.y;
self.z /= rhs.z;
}
}
unsafe impl crate::blit::Blit for Vec3 {}
|
/*
* Datadog API V1 Collection
*
* Collection of all Datadog Public endpoints.
*
* The version of the OpenAPI document: 1.0
* Contact: support@datadoghq.com
* Generated by: https://openapi-generator.tech
*/
/// UsageSyntheticsBrowserHour : Number of Synthetics Browser tests run for each hour for a given organization.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UsageSyntheticsBrowserHour {
/// Contains the number of Synthetics Browser tests run.
#[serde(rename = "browser_check_calls_count", skip_serializing_if = "Option::is_none")]
pub browser_check_calls_count: Option<i64>,
/// The hour for the usage.
#[serde(rename = "hour", skip_serializing_if = "Option::is_none")]
pub hour: Option<String>,
}
impl UsageSyntheticsBrowserHour {
/// Number of Synthetics Browser tests run for each hour for a given organization.
pub fn new() -> UsageSyntheticsBrowserHour {
UsageSyntheticsBrowserHour {
browser_check_calls_count: None,
hour: None,
}
}
}
|
// Copyright 2018-2020 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
//! A module that implements instrumented code cache.
//!
//! - In order to run contract code we need to instrument it with gas metering.
//! To do that we need to provide the schedule which will supply exact gas costs values.
//! We cache this code in the storage saving the schedule version.
//! - Before running contract code we check if the cached code has the schedule version that
//! is equal to the current saved schedule.
//! If it is equal then run the code, if it isn't reinstrument with the current schedule.
//! - When we update the schedule we want it to have strictly greater version than the current saved
//! one:
//! this guarantees that every instrumented contract code in cache cannot have the version equal to
//! the current one. Thus, before executing a contract it should be reinstrument with new schedule.
use crate::wasm::{prepare, runtime::Env, PrefabWasmModule};
use crate::{CodeHash, CodeStorage, PristineCode, Schedule, Trait};
use frame_support::StorageMap;
use sp_runtime::traits::Hash;
use sp_std::prelude::*;
/// Put code in the storage. The hash of code is used as a key and is returned
/// as a result of this function.
///
/// This function instruments the given code and caches it in the storage.
pub fn save<T: Trait>(
original_code: Vec<u8>,
schedule: &Schedule,
) -> Result<CodeHash<T>, &'static str> {
let prefab_module = prepare::prepare_contract::<Env>(&original_code, schedule)?;
let code_hash = T::Hashing::hash(&original_code);
<CodeStorage<T>>::insert(code_hash, prefab_module);
<PristineCode<T>>::insert(code_hash, original_code);
Ok(code_hash)
}
/// Load code with the given code hash.
///
/// If the module was instrumented with a lower version of schedule than
/// the current one given as an argument, then this function will perform
/// re-instrumentation and update the cache in the storage.
pub fn load<T: Trait>(
code_hash: &CodeHash<T>,
schedule: &Schedule,
) -> Result<PrefabWasmModule, &'static str> {
let mut prefab_module = <CodeStorage<T>>::get(code_hash).ok_or_else(|| "code is not found")?;
if prefab_module.schedule_version < schedule.version {
// The current schedule version is greater than the version of the one cached
// in the storage.
//
// We need to re-instrument the code with the latest schedule here.
let original_code =
<PristineCode<T>>::get(code_hash).ok_or_else(|| "pristine code is not found")?;
prefab_module = prepare::prepare_contract::<Env>(&original_code, schedule)?;
<CodeStorage<T>>::insert(&code_hash, &prefab_module);
}
Ok(prefab_module)
}
|
extern crate somepackage;
use somepackage::indirect_access;
use somepackage::somemod;
// import from other local file
mod otherfile;
// import c code
extern { fn c_function_example(); }
use otherfile::mod_in_otherfile;
fn main() {
println!("Hello, world!");
somepackage::public_function();
indirect_access();
somemod::public_mod_function();
otherfile::fn_from_otherfile();
mod_in_otherfile::some_func();
unsafe {
c_function_example();
}
}
|
#![no_std]
#![feature(start)]
#![no_main]
use ferr_os_librust::syscall;
use ferr_os_librust::io;
extern crate alloc;
use alloc::string::{String, ToString};
#[no_mangle]
pub extern "C" fn _start(heap_address: u64, heap_size: u64, _args: u64) {
unsafe {
syscall::set_screen_size(1, 10);
syscall::set_screen_pos(0, 0);
}
ferr_os_librust::allocator::init(heap_address, heap_size);
main();
}
#[inline(never)]
fn main() {
let mut compteur = 0_usize;
loop {
let new_id = unsafe { syscall::fork() };
compteur += 1;
if new_id == 0 {
return
}
let mut sortie = String::from("\n");
sortie.push_str(&compteur.to_string());
io::print(&sortie);
wait_end();
}
}
fn wait_end() {
loop {
let (rax, _rdi) = unsafe { syscall::listen() };
if rax == 0 {
unsafe {
syscall::sleep()
};
} else {
return;
}
}
}
|
use std::collections::HashMap;
use std::io;
use crate::base::Part;
pub fn part1(r: &mut dyn io::Read) -> Result<String, String> {
solve(r, Part::One)
}
pub fn part2(r: &mut dyn io::Read) -> Result<String, String> {
solve(r, Part::Two)
}
fn solve(r: &mut dyn io::Read, part: Part) -> Result<String, String> {
let mut input = String::new();
r.read_to_string(&mut input).map_err(|e| e.to_string())?;
let banks = parse_input(&input);
let (redistributions, loop_size) = count_redistributions(&banks);
let answer = match part {
Part::One => redistributions,
Part::Two => loop_size,
};
Ok(answer.to_string())
}
fn parse_input(input: &str) -> Vec<u64> {
input
.trim()
.split_whitespace()
.map(str::parse)
.map(Result::unwrap)
.collect()
}
fn count_redistributions(banks: &[u64]) -> (u64, u64) {
let mut distributions: HashMap<Vec<u64>, u64> = HashMap::new();
let mut counter = 0;
let mut distribution = Vec::from(banks);
distributions.insert(distribution.clone(), counter as u64);
while counter < distributions.len() {
distribution = redistribute(&distribution);
counter += 1;
distributions
.entry(distribution.clone())
.or_insert(counter as u64);
}
let first_distribution_in_loop = &distributions[&distribution];
(counter as u64, counter as u64 - first_distribution_in_loop)
}
fn redistribute(banks: &[u64]) -> Vec<u64> {
let mut vec = Vec::from(banks);
let max_bank_index = find_max_index(&vec);
let mut blocks_to_redistribute = vec[max_bank_index];
vec[max_bank_index] = 0;
let len = vec.len();
let mut bank_to_increase_index = (max_bank_index + 1) % len;
while blocks_to_redistribute > 0 {
vec[bank_to_increase_index] += 1;
bank_to_increase_index = (bank_to_increase_index + 1) % len;
blocks_to_redistribute -= 1;
}
vec
}
fn find_max_index<T: Ord + Copy>(banks: &[T]) -> usize {
banks
.iter()
.enumerate()
.fold(0, |max_index, (index, &bank)| {
if bank > banks[max_index] {
index
} else {
max_index
}
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test;
mod part1 {
use super::*;
test!(example, "0 2 7 0", "5", part1);
test!(actual, file "../../../inputs/2017/06", "5042", part1);
}
mod part2 {
use super::*;
test!(example, "0 2 7 0", "4", part2);
test!(actual, file "../../../inputs/2017/06", "1086", part2);
}
}
|
pub mod checklists;
pub mod requirements;
|
//! Traits and code for emitting high-level structures as low-level, raw wasm
//! structures. E.g. translating from globally unique identifiers down to the
//! raw wasm structure's index spaces.
use crate::encode::{Encoder, MAX_U32_LENGTH};
use crate::ir::Local;
use crate::map::{IdHashMap, IdHashSet};
use crate::{CodeTransform, Global, GlobalId, Memory, MemoryId, Module, Table, TableId};
use crate::{Data, DataId, Element, ElementId, Function, FunctionId};
use crate::{Type, TypeId};
use std::ops::{Deref, DerefMut};
pub struct EmitContext<'a> {
pub module: &'a Module,
pub indices: &'a mut IdsToIndices,
pub encoder: Encoder<'a>,
pub locals: IdHashMap<Function, IdHashSet<Local>>,
pub code_transform: CodeTransform,
}
pub struct SubContext<'a, 'cx> {
cx: &'cx mut EmitContext<'a>,
write_size_to: usize,
}
/// Anything that can be lowered to raw wasm structures.
pub trait Emit {
/// Emit `self` into the given context.
fn emit(&self, cx: &mut EmitContext);
}
impl<'a, T: ?Sized + Emit> Emit for &'a T {
fn emit(&self, cx: &mut EmitContext) {
T::emit(self, cx)
}
}
/// Maps our high-level identifiers to the raw indices they end up emitted at.
///
/// As we lower to raw wasm structures, we cement various constructs' locations
/// in their respective index spaces. For example, a type with some id `A` ends
/// up being the `i^th` type emitted in the raw wasm type section. When a
/// function references that type, it needs to reference it by its `i` index
/// since the identifier `A` doesn't exist at the raw wasm level.
#[derive(Debug, Default)]
pub struct IdsToIndices {
tables: IdHashMap<Table, u32>,
types: IdHashMap<Type, u32>,
funcs: IdHashMap<Function, u32>,
globals: IdHashMap<Global, u32>,
memories: IdHashMap<Memory, u32>,
elements: IdHashMap<Element, u32>,
data: IdHashMap<Data, u32>,
pub(crate) locals: IdHashMap<Function, IdHashMap<Local, u32>>,
}
macro_rules! define_get_index {
( $(
$get_name:ident, $id_ty:ty, $member:ident;
)* ) => {
impl IdsToIndices {
$(
/// Get the index for the given identifier.
#[inline]
pub fn $get_name(&self, id: $id_ty) -> u32 {
self.$member.get(&id).cloned().unwrap_or_else(|| panic!(
"{}: Should never try and get the index for an identifier that has not already had \
its index set. This means that either we are attempting to get the index of \
an unused identifier, or that we are emitting sections in the wrong order. \n\n\
id = {:?}",
stringify!($get_name),
id,
))
}
)*
}
};
}
macro_rules! define_get_push_index {
( $(
$get_name:ident, $push_name:ident, $id_ty:ty, $member:ident;
)* ) => {
define_get_index!( $( $get_name, $id_ty, $member; )* );
impl IdsToIndices {
$(
/// Adds the given identifier to this set, assigning it the next
/// available index.
#[inline]
pub(crate) fn $push_name(&mut self, id: $id_ty) {
let idx = self.$member.len() as u32;
log::trace!(concat!(stringify!($push_name),": assigning index {} to {:?}"), idx, id);
self.$member.insert(id, idx);
}
)*
}
};
}
define_get_push_index! {
get_table_index, push_table, TableId, tables;
get_type_index, push_type, TypeId, types;
get_func_index, push_func, FunctionId, funcs;
get_global_index, push_global, GlobalId, globals;
get_memory_index, push_memory, MemoryId, memories;
get_element_index, push_element, ElementId, elements;
}
define_get_index! {
get_data_index, DataId, data;
}
impl IdsToIndices {
/// Sets the data index to the specified value
pub(crate) fn set_data_index(&mut self, id: DataId, idx: u32) {
self.data.insert(id, idx);
}
}
impl<'a> EmitContext<'a> {
pub fn start_section<'b>(&'b mut self, id: Section) -> SubContext<'a, 'b> {
self.subsection(id as u8)
}
pub fn subsection<'b>(&'b mut self, id: u8) -> SubContext<'a, 'b> {
self.encoder.byte(id);
let start = self.encoder.reserve_u32();
SubContext {
cx: self,
write_size_to: start,
}
}
pub fn custom_section<'b>(&'b mut self, name: &str) -> SubContext<'a, 'b> {
let mut cx = self.start_section(Section::Custom);
cx.encoder.str(name);
return cx;
}
pub fn list<T>(&mut self, list: T)
where
T: IntoIterator,
T::IntoIter: ExactSizeIterator,
T::Item: Emit,
{
let list = list.into_iter();
self.encoder.usize(list.len());
for item in list {
item.emit(self);
}
}
}
impl<'a> Deref for SubContext<'a, '_> {
type Target = EmitContext<'a>;
fn deref(&self) -> &EmitContext<'a> {
&self.cx
}
}
impl<'a> DerefMut for SubContext<'a, '_> {
fn deref_mut(&mut self) -> &mut EmitContext<'a> {
&mut self.cx
}
}
impl Drop for SubContext<'_, '_> {
fn drop(&mut self) {
let amt = self.cx.encoder.pos() - self.write_size_to - MAX_U32_LENGTH;
assert!(amt <= u32::max_value() as usize);
self.cx.encoder.u32_at(self.write_size_to, amt as u32);
}
}
pub enum Section {
Custom = 0,
Type = 1,
Import = 2,
Function = 3,
Table = 4,
Memory = 5,
Global = 6,
Export = 7,
Start = 8,
Element = 9,
Code = 10,
Data = 11,
DataCount = 12,
}
|
use crate::components::{TileMap, TileMapConfig};
use crate::resources::{get_screen_size, Board, Context, Game, State};
use crate::states::MainState;
use amethyst::{
core::Transform,
prelude::*,
renderer::Camera,
assets::{
Prefab,
PrefabLoader,
RonFormat,
Handle,
ProgressCounter,
Completion,
},
ui::{
UiCreator,
},
};
pub struct LoadingState {
load_complete: bool,
load_progress: ProgressCounter,
}
impl Default for LoadingState {
fn default() -> Self {
LoadingState {
load_complete: false,
load_progress: ProgressCounter::default(),
}
}
}
impl SimpleState for LoadingState {
fn on_start(&mut self, data: StateData<'_, GameData<'_, '_>>) {
let world = data.world;
world.exec(|mut creator: UiCreator| {
creator.create("ui/loading.ron", &mut self.load_progress);
});
world.register::<TileMap>();
initialise_camera(world);
world.add_resource(Context::new());
world.add_resource(Game::new(State::Loading));
let tile_config = TileMapConfig::from_path("resources/assets/tileset.ron");
let board = Board::new(tile_config.size_x, tile_config.size_y);
world.add_resource(board);
let tilemap = { TileMap::new(world, "assets/snake.png", "assets/snake.ron", &tile_config) };
let (width, height) = get_screen_size(world);
let mut transform = Transform::default();
transform.set_translation_xyz((width * 0.5) as f32, (height * 0.5) as f32, 0.0);
world.create_entity().with(transform).with(tilemap).build();
self.load_complete = true;
}
fn update(&mut self, _: &mut StateData<'_, GameData<'_, '_>>) -> SimpleTrans {
match &self.load_complete {
false => Trans::None,
true => {
match &self.load_progress.complete() {
Completion::Loading => Trans::None,
Completion::Complete => Trans::Switch(Box::new(MainState {})),
Completion::Failed => Trans::Quit,
}
},
}
}
fn on_resume(&mut self, mut data: StateData<'_, GameData<'_, '_>>) {
data.world
.write_resource::<Game>()
.set_state(State::Loading);
}
}
fn initialise_camera(world: &mut World) {
let (width, height) = get_screen_size(world);
let mut transform = Transform::default();
transform.set_translation_xyz(width * 0.5, height * 0.5, 1.0);
world
.create_entity()
.with(Camera::standard_2d(width, height))
.with(transform)
.build();
}
|
pub fn z_encode(s: &str) -> Option<String> {
let mut ret = String::with_capacity(s.len() * 2);
let mut chars = s.chars();
let mut next = chars.next();
while let Some(c) = next {
match c {
'(' => {
next = chars.next(); // consume '('
let mut consumed = false;
let mut unboxed = false;
let mut arity = 0;
loop {
match next {
Some('#') => {
unboxed = true;
next = chars.next(); // consume '#'
consumed = true;
}
Some(' ') => {
next = chars.next(); // consume ' '
consumed = true;
}
Some(')') => {
let kind = if unboxed { 'H' } else { 'T' };
ret.push_str(&format!("Z{}{}", arity, kind));
next = chars.next(); // consume ')'
break;
}
Some(',') => {
next = chars.next(); // consume ','
if arity == 0 {
arity = 2;
} else {
arity += 1;
}
while let Some(',') = next {
arity += 1;
next = chars.next(); // consume ','
}
consumed = true;
}
_ => {
if consumed {
return None;
} else {
ret.push_str("ZL");
break;
}
}
}
}
}
')' => {
ret.push_str("ZR");
next = chars.next();
}
'[' => {
ret.push_str("ZM");
next = chars.next();
}
']' => {
ret.push_str("ZN");
next = chars.next();
}
':' => {
ret.push_str("ZC");
next = chars.next();
}
'&' => {
ret.push_str("za");
next = chars.next();
}
'|' => {
ret.push_str("zb");
next = chars.next();
}
'^' => {
ret.push_str("zc");
next = chars.next();
}
'$' => {
ret.push_str("zd");
next = chars.next();
}
'=' => {
ret.push_str("ze");
next = chars.next();
}
'>' => {
ret.push_str("zg");
next = chars.next();
}
'#' => {
ret.push_str("zh");
next = chars.next();
}
'.' => {
ret.push_str("zi");
next = chars.next();
}
'<' => {
ret.push_str("zl");
next = chars.next();
}
'-' => {
ret.push_str("zm");
next = chars.next();
}
'!' => {
ret.push_str("zn");
next = chars.next();
}
'+' => {
ret.push_str("zp");
next = chars.next();
}
'\'' => {
ret.push_str("zq");
next = chars.next();
}
'\\' => {
ret.push_str("zr");
next = chars.next();
}
'/' => {
ret.push_str("zs");
next = chars.next();
}
'*' => {
ret.push_str("zt");
next = chars.next();
}
'_' => {
ret.push_str("zu");
next = chars.next();
}
'%' => {
ret.push_str("zv");
next = chars.next();
}
'z' => {
ret.push_str("zz");
next = chars.next();
}
'Z' => {
ret.push_str("ZZ");
next = chars.next();
}
c => {
ret.push(c);
next = chars.next();
}
}
}
debug_assert!(chars.next().is_none());
Some(ret)
}
#[test]
fn encode_test() {
assert_eq!(z_encode("("), Some("ZL".to_string()));
assert_eq!(z_encode(")"), Some("ZR".to_string()));
assert_eq!(z_encode("()"), Some("Z0T".to_string()));
assert_eq!(z_encode("(# #)"), Some("Z0H".to_string()));
assert_eq!(z_encode("(,)"), Some("Z2T".to_string()));
assert_eq!(z_encode("(,,)"), Some("Z3T".to_string()));
assert_eq!(z_encode("(#,#)"), Some("Z2H".to_string()));
assert_eq!(z_encode("(#,,#)"), Some("Z3H".to_string()));
assert_eq!(z_encode("Trak"), Some("Trak".to_string()));
assert_eq!(z_encode("foo_wib"), Some("foozuwib".to_string()));
assert_eq!(z_encode(">"), Some("zg".to_string()));
assert_eq!(z_encode(">1"), Some("zg1".to_string()));
assert_eq!(z_encode("foo#"), Some("foozh".to_string()));
assert_eq!(z_encode("foo##"), Some("foozhzh".to_string()));
assert_eq!(z_encode("foo##1"), Some("foozhzh1".to_string()));
assert_eq!(z_encode("fooZ"), Some("fooZZ".to_string()));
assert_eq!(z_encode(":+"), Some("ZCzp".to_string()));
}
|
use git2::Repository;
fn main() {
let repo = match Repository::init("/tmp/hello.git") {
Ok(repo) => repo,
Err(e) => panic!("failed to init: {}", e),
};
println!("success init repo");
}
|
extern crate env_logger;
// #[macro_use]
// extern crate log;
use fastping_rs::Pinger;
use timer::Timer;
use chrono::Duration;
use nix::unistd::{setuid, Uid};
use std::sync::mpsc;
use std::env;
use influent::client::Credentials;
mod log;
mod ping_result;
use ping_result::PingResult;
mod pinger;
use pinger::run_ping;
mod db;
use db::{Db, sqlitedb::SqliteDb, yamldb::YamlDb};
mod tsdb;
use tsdb::Tsdb;
static TIMEOUT: u64 = 100;
static TPING: i64 = 1000;
static NPING: u32 = 5;
#[derive(Debug, Clone)]
pub struct Target {
name: String,
target: String
}
#[derive(Debug)]
pub enum Error {
YamlDbError(db::yamldb::Error),
SqliteDbError(rusqlite::Error),
}
impl From<db::yamldb::Error> for Error {
fn from(e: db::yamldb::Error) -> Self { Self::YamlDbError(e) }
}
impl From<rusqlite::Error> for Error {
fn from(e: rusqlite::Error) -> Self { Self::SqliteDbError(e) }
}
fn getenv(name: &str, default: &str) -> String {
match env::var(&name) { Ok(s) => s, Err(_e) => default.to_string() }
}
fn main() -> Result<(), Error> {
if !Uid::current().is_root() {
match setuid(Uid::from_raw(0)) {
Err(e) => panic!("Error switching to root: {}", e),
_ => ()
}
}
let influx_host = getenv("INFLUXDB_HOST", "localhost");
let influx_cred = Credentials {
username: &getenv("INFLUXDB_USER", "influser"),
password: &getenv("INFLUXDB_PASS", "inflpass"),
database: &getenv("INFLUXDB_DB", "influxdb")
};
let tsdb = Tsdb::new(&influx_host, influx_cred);
env_logger::init();
let (pinger, results) = match Pinger::new(Some(TIMEOUT), None) {
Ok((pinger, results)) => (pinger, results),
Err(e) => panic!("Error creating pinger: {}", e)
};
let ips = if let Ok(db) = YamlDb::new() {
db.targets()?
}
else if let Ok(db) = SqliteDb::new() {
db.init()?;
db.targets()?
}
else {
panic!("No valid db found")
};
println!("Loaded from db: {:?}", ips);
for ip in &ips {
pinger.add_ipaddr(&ip.target);
}
let (results_tx, results_rx) = mpsc::channel();
// Create timer
let timer = Timer::new();
let ips_clone = ips.to_vec();
let _guard = timer.schedule_repeating(
Duration::milliseconds(TPING),
move || run_ping(&pinger, &results, &ips_clone, &results_tx, NPING));
loop {
match results_rx.recv() {
Ok((res, timestamp)) => {
println!("Summary:");
log::print_summary(&ips, &res);
tsdb.push_results(&ips, res, timestamp as i64);
},
Err(_) => panic!("Timer thread disconnected!")
}
}
}
|
#![crate_name = "server"]
#![crate_type = "bin"]
#![allow(dead_code)]
extern crate debug;
extern crate nanomsg;
use std::io::Writer;
use nanomsg::AF_SP;
use nanomsg::NN_PAIR;
use nanomsg::NanoSocket;
fn main() {
let socket_address = "tcp://127.0.0.1:5555";
println!("server binding to '{:?}'", socket_address);
// create and connect
let mut sock = match NanoSocket::new(AF_SP, NN_PAIR) {
Ok(s) => s,
Err(e) => fail!("Failed with err:{:?} {:?}", e.rc, e.errstr)
};
match sock.bind(socket_address) {
Ok(_) => {},
Err(e) =>{
fail!("Bind failed with err:{:?} {:?}", e.rc, e.errstr);
}
}
// receive
match sock.recv() {
Ok(v) => {
println!("actual_msg_size is {:?}", v.len());
match std::str::from_utf8(v.as_slice()) {
Some(msg) => println!("server: I received a {} byte long msg: '{:s}'", v.len(), msg),
None => println!("server: I received a {} byte long msg but it was None'", v.len()),
}
},
Err(e) => fail!("sock.recv -> failed with errno: {:?} '{:?}'", e.rc, e.errstr)
};
let b = "LUV";
// send
match sock.send(b.as_bytes()) {
Ok(_) => {},
Err(e) => fail!("send failed with err:{:?} {:?}", e.rc, e.errstr)
}
println!("server: I sent '{:s}'", b);
// send 2, using Writer interface
let b = "CAT";
sock.write(b.as_bytes()).unwrap();
println!("server: 2nd send, I sent '{:s}'", b);
}
|
extern crate spidy;
extern crate diesel;
use self::spidy::*;
use self::models::*;
use self::diesel::prelude::*;
fn main() {
use spidy::schema::movies::dsl::*;
let connection = establish_connection();
let results = movies.filter(published.eq(true))
.limit(5)
.load::<Movie>(&connection)
.expect("Error loading movies");
println!("Displaying {} movies", results.len());
for movie in results {
println!("{}", movie.title);
println!("------------\n");
println!("{}", movie.description);
}
}
|
use shopsite_aa::de as aa;
use std::{
fs::{File, OpenOptions},
io::{self, BufRead, BufReader, Write},
num::NonZeroU8,
path::PathBuf,
process::exit,
rc::Rc
};
use structopt::StructOpt;
#[derive(StructOpt)]
#[structopt(
about = "Converts a ShopSite `.aa` file to JSON."
)]
struct Opts {
/// Pretty-print the output JSON.
#[structopt(short, long)]
pretty: bool,
/// Indent size, in spaces, to use when pretty-printing [default: 4]
#[structopt(short = "s", long, requires = "pretty", conflicts_with = "indent-tabs")]
indent_spaces: Option<NonZeroU8>,
/// Use tabs instead of spaces for indentation when pretty-printing.
#[structopt(short = "t", long, requires = "pretty")]
indent_tabs: bool,
/// JSON file to write to, instead of standard output.
#[structopt(short, long)]
output: Option<PathBuf>,
/// .aa file to read from, instead of standard input.
#[structopt(name = "FILE")]
input: Option<PathBuf>
}
fn main() {
let opts: Opts = Opts::from_args();
let stdin = io::stdin();
let stdout = io::stdout();
let input: Box<dyn BufRead> = {
if let Some(ref input_file) = opts.input {
let open_result = File::open(input_file);
match open_result {
Ok(fh) => Box::new(BufReader::new(fh)),
Err(error) => {
eprintln!("Error opening input file {}: {}", input_file.to_string_lossy(), error);
exit(1)
}
}
}
else {
Box::new(stdin.lock())
}
};
let output: Box<dyn Write> = {
if let Some(ref output_file) = opts.output {
let open_result = OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.open(output_file);
match open_result {
Ok(fh) => Box::new(fh),
Err(error) => {
eprintln!("Error opening output file {}: {}", output_file.to_string_lossy(), error);
exit(1)
}
}
}
else {
Box::new(stdout.lock())
}
};
let de = aa::Deserializer::new(input, opts.input.map(Rc::from));
// `serde_json::ser::Formatter` can't be used as a trait object, so we get to do this insteadโฆ
fn do_transcode(mut de: aa::Deserializer<impl BufRead>, mut writer: impl Write, formatter: impl serde_json::ser::Formatter) -> Result<(), std::io::Error> {
let mut ser = serde_json::Serializer::with_formatter(&mut writer, formatter);
serde_transcode::transcode(&mut de, &mut ser)?;
writeln!(&mut writer)?;
writer.flush()
}
let result = {
if opts.pretty {
let mut indent_string_buf = Vec::<u8>::new();
let indent_string: &[u8] = {
if opts.indent_tabs {
b"\t"
}
else if let Some(indent_spaces) = opts.indent_spaces {
indent_string_buf.reserve_exact(indent_spaces.get() as usize);
for _ in 0..indent_spaces.get() {
indent_string_buf.push(b' ');
}
&indent_string_buf[..]
}
else {
b" "
}
};
do_transcode(de, output, serde_json::ser::PrettyFormatter::with_indent(indent_string))
}
else {
do_transcode(de, output, serde_json::ser::CompactFormatter)
}
};
if let Err(error) = result {
eprintln!("Error converting to JSON: {}", error);
exit(1);
}
}
|
use std::sync::{Arc, Mutex};
use std::thread;
use std::thread::JoinHandle;
fn closure_() {
let example_closure = |x| x;
let s = example_closure(String::from("hello")); // type of x is set to String after this line
// let n = example_closure(5);
// 5 | let n = example_closure(5);
// | ^
// | expected struct `std::string::String`, found integer
//closures have an additional capability that functions donโt have:
// they can capture their environment and access variables from the scope in which theyโre defined.
let x = 4;
let equal_to_x = |z| z == x;
let y = 4;
assert!(equal_to_x(y));
// functions are never allowed to capture their environment,
// fn equal_to_x(z: i32) -> bool {
// z == x
// }
// assert!(equal_to_x(y));
// 5 | z == x
// | ^
// |
// = help: use the `|| { ... }` closure form instead
}
fn shared_state() {
println!("shared_state -------------------");
let counter = Arc::new(Mutex::new(0));
let mut handles:Vec<JoinHandle<()>> = vec![];
// let mut handles= vec![];
for _ in 0..5 {
let counter = Arc::clone(&counter);
let handle = thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
println!("num = {:?}", num);
});
handles.push(handle);
}
for handle in handles {
println!("handle = {:?}", handle);
handle.join().unwrap();
}
println!("Result: {}", *counter.lock().unwrap());
}
pub fn closure_test() {
shared_state();
closure_();
} |
use nails_derive::Preroute;
#[derive(Preroute)]
#[nails(path = "/api/posts/{id}", foo)]
pub struct GetPostRequest {}
#[derive(Preroute)]
#[nails(path = "/api/posts/{id}")]
pub struct GetPostRequest2 {
#[nails(query, foo)]
query1: String,
}
fn main() {}
|
// Copyright 2017 Dmitry Tantsur <divius.inside@gmail.com>
//
// 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.
//! Simple authentication methods.
use reqwest::{Client, IntoUrl, Method, Url, UrlError};
use super::super::Result;
use super::super::session::RequestBuilder;
use super::AuthMethod;
/// Authentication method that provides no authentication.
///
/// This method always returns a constant fake token, and a pre-defined
/// endpoint.
#[derive(Clone, Debug)]
pub struct NoAuth {
client: Client,
endpoint: Url
}
impl NoAuth {
/// Create a new fake authentication method using a fixed endpoint.
///
/// This endpoint will be returned in response to all get_endpoint calls
/// of the [AuthMethod](trait.AuthMethod.html) trait.
pub fn new<U>(endpoint: U) -> ::std::result::Result<NoAuth, UrlError>
where U: IntoUrl {
Ok(NoAuth {
client: Client::new(),
endpoint: endpoint.into_url()?
})
}
}
impl AuthMethod for NoAuth {
/// Create a request.
fn request(&self, method: Method, url: Url) -> Result<RequestBuilder> {
Ok(RequestBuilder::new(self.client.request(method, url)))
}
/// Get a predefined endpoint for all service types
fn get_endpoint(&self, _service_type: String,
_endpoint_interface: Option<String>) -> Result<Url> {
Ok(self.endpoint.clone())
}
fn refresh(&mut self) -> Result<()> { Ok(()) }
}
#[cfg(test)]
pub mod test {
#![allow(unused_results)]
use super::super::AuthMethod;
use super::NoAuth;
#[test]
fn test_noauth_new() {
let a = NoAuth::new("http://127.0.0.1:8080/v1").unwrap();
let e = a.endpoint;
assert_eq!(e.scheme(), "http");
assert_eq!(e.host_str().unwrap(), "127.0.0.1");
assert_eq!(e.port().unwrap(), 8080u16);
assert_eq!(e.path(), "/v1");
}
#[test]
fn test_noauth_new_fail() {
NoAuth::new("foo bar").err().unwrap();
}
#[test]
fn test_noauth_get_endpoint() {
let a = NoAuth::new("http://127.0.0.1:8080/v1").unwrap();
let e = a.get_endpoint(String::from("foobar"), None).unwrap();
assert_eq!(e.scheme(), "http");
assert_eq!(e.host_str().unwrap(), "127.0.0.1");
assert_eq!(e.port().unwrap(), 8080u16);
assert_eq!(e.path(), "/v1");
}
}
|
use models::*;
use misc;
use std::collections::HashMap;
pub fn search_results(search_results: &Vec<SearchResult>) -> Vec<SearchResultFlat> {
let mut search_results_flat: Vec<SearchResultFlat> = Vec::new();
for search_result in search_results {
//flatten organism
let taxon_code;
let species;
let common_name;
match &search_result.organism {
&Some(ref organism) => {
taxon_code = organism.taxon_code.clone();
species = organism.species.clone();
common_name = organism.common_name.clone();
},
&None => {
taxon_code = None;
species = None;
common_name = None;
}
}
//flatten synonyms
let synonyms_flat = misc::str_vec_to_str(&search_result.synonyms);
//build flat search result
let search_result_flat = SearchResultFlat {
iptm_id : search_result.iptm_id.clone(),
protein_name: search_result.protein_name.clone(),
gene_name: search_result.gene_name.clone(),
synonyms: Some(synonyms_flat),
organism_taxon_code: taxon_code,
organism_species: species,
organism_common_name: common_name,
substrate_role: search_result.substrate_role.clone(),
substrate_num: search_result.substrate_num.clone(),
enzyme_role: search_result.enzyme_role.clone(),
enzyme_num: search_result.enzyme_num.clone(),
ptm_dependent_ppi_role : search_result.ptm_dependent_ppi_role.clone(),
ptm_dependent_ppi_num : search_result.ptm_dependent_ppi_num.clone(),
sites: search_result.sites.clone(),
isoforms: search_result.isoforms.clone(),
};
// add to vector
search_results_flat.push(search_result_flat);
}
return search_results_flat;
}
pub fn substrate_events(substrate_events: &HashMap<String,Vec<SubstrateEvent>>) -> Vec<SubstrateEventFlat> {
let mut substrate_events_flat:Vec<SubstrateEventFlat> = Vec::new();
for sub_from in substrate_events.iter() {
let events = sub_from.1;
for event in events {
//flatten enzymes
let mut enzymes_str = String::new();
for (index,enzyme) in event.enzymes.iter().enumerate() {
let mut enzyme_name = String::new();
let mut enzyme_id = String::new();
let mut enzyme_type = String::new();
match enzyme.name {
Some(ref value) => {
enzyme_name = value.clone();
},
None => {
}
}
match enzyme.id {
Some(ref value) => {
enzyme_id = value.clone();
},
None => {
}
}
match enzyme.enz_type {
Some(ref value) => {
enzyme_type = value.clone();
},
None => {
}
}
let current_str = format!("[{name},{id},{enz_type}]",name=enzyme_name,id=enzyme_id,enz_type=enzyme_type);
if index == 0 {
enzymes_str = current_str;
}else{
enzymes_str = format!("{prev_str},{curr_str}",prev_str=enzymes_str,curr_str=current_str);
}
};
let event_flat = SubstrateEventFlat {
sub_form: Some(sub_from.0.clone()),
residue: event.residue.clone(),
site: event.site.clone(),
ptm_type: event.ptm_type.clone(),
score: event.score.clone(),
sources: Some(sources(&event.sources)),
enzymes: Some(enzymes_str),
pmids: Some(misc::str_vec_to_str(&event.pmids))
};
substrate_events_flat.push(event_flat);
}
}
return substrate_events_flat;
}
pub fn enzyme_events(enzyme_events: &Vec<EnzymeEvent>) -> Vec<EnzymeEventFlat> {
let mut enzyme_events_flat : Vec<EnzymeEventFlat> = Vec::new();
for enzyme_event in enzyme_events {
let event_flat = EnzymeEventFlat {
substrate: enzyme_event.substrate.clone(),
substrate_symbol: enzyme_event.substrate_symbol.clone(),
site: enzyme_event.site.clone(),
score: enzyme_event.score.clone(),
sources: Some(sources(&enzyme_event.sources)),
pmids: Some(misc::str_vec_to_str(&enzyme_event.pmids))
};
enzyme_events_flat.push(event_flat);
}
return enzyme_events_flat;
}
pub fn proteoform(proteoforms: &Vec<Proteoform>) -> Vec<ProteoformFlat> {
let mut proteoforms_flat: Vec<ProteoformFlat> = Vec::new();
for proteoform in proteoforms {
// flatten ptm enzyme
let ptm_enzyme_id;
let ptm_enzyme_label;
match &proteoform.ptm_enzyme {
&Some(ref ptm_enzyme) => {
ptm_enzyme_id = ptm_enzyme.pro_id.clone();
ptm_enzyme_label = ptm_enzyme.label.clone();
},
&None => {
ptm_enzyme_id = None;
ptm_enzyme_label = None;
}
}
// flatten source
let source_name;
match &proteoform.source {
&Some(ref source) => {
source_name = source.name.clone();
},
&None => {
source_name = None;
}
}
//build the flat proteoform
let proteoform_flat = ProteoformFlat {
pro_id : proteoform.pro_id.clone(),
label: proteoform.label.clone(),
sites: Some(misc::str_vec_to_str(&proteoform.sites)),
ptm_enzyme_id: ptm_enzyme_id,
ptm_enzyme_label: ptm_enzyme_label,
source: source_name,
pmids: Some(misc::str_vec_to_str(&proteoform.sites))
};
//add to vector
proteoforms_flat.push(proteoform_flat);
}
return proteoforms_flat;
}
pub fn proteoform_ppis(proteoforms_ppi: &Vec<ProteoformPPI>) -> Vec<ProteoformPPIFlat> {
let mut proteoforms_ppi_flat: Vec<ProteoformPPIFlat> = Vec::new();
for proteoform_ppi in proteoforms_ppi {
//build protein_1
let protein_1_pro_id;
let protein_1_label;
match &proteoform_ppi.protein_1 {
&Some(ref protein_1) => {
protein_1_pro_id = protein_1.pro_id.clone();
protein_1_label = protein_1.label.clone();
},
&None => {
protein_1_pro_id = None;
protein_1_label = None;
}
}
//build protein_2
let protein_2_pro_id;
let protein_2_label;
match &proteoform_ppi.protein_2 {
&Some(ref protein_2) => {
protein_2_pro_id = protein_2.pro_id.clone();
protein_2_label = protein_2.label.clone();
},
&None => {
protein_2_pro_id = None;
protein_2_label = None;
}
}
//pmids
let pmids = misc::str_vec_to_str(&proteoform_ppi.pmids);
//source
let source_name;
match &proteoform_ppi.source {
&Some(ref source) => {
source_name = source.name.clone();
},
&None => {
source_name = None;
}
}
//build flat proteoform_ppi
let proteoform_ppi_flat = ProteoformPPIFlat {
protein_1_pro_id: protein_1_pro_id,
protein_1_label: protein_1_label,
protein_2_pro_id: protein_2_pro_id,
protein_2_label: protein_2_label,
relation: proteoform_ppi.relation.clone(),
source: source_name,
pmids: Some(pmids)
};
//add to vector
proteoforms_ppi_flat.push(proteoform_ppi_flat);
}
return proteoforms_ppi_flat;
}
pub fn ptm_ppi(ptm_ppis: &Vec<PTMPPI>) -> Vec<PTMPPIFlat> {
let mut ptm_ppis_flat: Vec<PTMPPIFlat> = Vec::new();
for ptm_ppi in ptm_ppis {
//flatten substrate
let substrate_uniprot_id;
let substrate_name;
match &ptm_ppi.substrate {
&Some(ref substrate) => {
substrate_uniprot_id = substrate.uniprot_id.clone();
substrate_name = substrate.name.clone();
},
&None => {
substrate_uniprot_id = None;
substrate_name = None;
}
}
//flatten interactant
let interactant_uniprot_id;
let interactant_name;
match &ptm_ppi.interactant {
&Some(ref interactant) => {
interactant_uniprot_id = interactant.uniprot_id.clone();
interactant_name = interactant.name.clone();
},
&None => {
interactant_uniprot_id = None;
interactant_name = None;
}
}
//source
let source_name;
match &ptm_ppi.source {
&Some(ref source) => {
source_name = source.name.clone();
},
&None => {
source_name = None;
}
}
//build flat ptm_ppi
let ptm_ppi_flat = PTMPPIFlat {
ptm_type: ptm_ppi.ptm_type.clone(),
substrate_uniprot_id: substrate_uniprot_id,
substrate_name: substrate_name,
site: ptm_ppi.site.clone(),
interactant_uniprot_id: interactant_uniprot_id,
interactant_name: interactant_name,
association_type: ptm_ppi.association_type.clone(),
source: source_name,
pmid: ptm_ppi.pmid.clone()
};
//add to vector
ptm_ppis_flat.push(ptm_ppi_flat);
}
return ptm_ppis_flat;
}
pub fn batch_ptm_enzymes(batch_ptm_enzymes: &Vec<BatchPTMEnzyme>) -> Vec<BatchPTMEnzymeFlat>{
let mut batch_ptm_enzymes_flat: Vec<BatchPTMEnzymeFlat> = Vec::new();
for batch_ptm_enzyme in batch_ptm_enzymes {
//flatten enzyme
let enz_name;
let enz_id;
match &batch_ptm_enzyme.enzyme {
&Some(ref enzyme) => {
enz_name = enzyme.name.clone();
enz_id = enzyme.uniprot_id.clone();
},
&None => {
enz_name = None;
enz_id = None;
}
}
//flatten substrate
let sub_name;
let sub_id;
match &batch_ptm_enzyme.substrate {
&Some(ref substrate) => {
sub_name = substrate.name.clone();
sub_id = substrate.uniprot_id.clone();
},
&None => {
sub_name = None;
sub_id = None;
}
}
//fatten sources
let sources = sources(&batch_ptm_enzyme.source);
//build flat batch_ptm_enzyme
let batch_ptm_enzyme_flat = BatchPTMEnzymeFlat {
enz_id: enz_id,
enz_name: enz_name,
sub_id: sub_id,
sub_name: sub_name,
ptm_type: batch_ptm_enzyme.ptm_type.clone(),
site: batch_ptm_enzyme.site.clone(),
site_position: batch_ptm_enzyme.site_position.clone(),
score: batch_ptm_enzyme.score.clone(),
source: Some(sources),
pmids: Some(misc::str_vec_to_str(&batch_ptm_enzyme.pmids)),
};
batch_ptm_enzymes_flat.push(batch_ptm_enzyme_flat);
}
return batch_ptm_enzymes_flat;
}
pub fn batch_ptm_ppi(batch_ptm_ppis: &Vec<BatchPTMPPI>) -> Vec<BatchPTMPPIFlat> {
let mut batch_ptm_ppis_flat: Vec<BatchPTMPPIFlat> = Vec::new();
for batch_ptm_ppi in batch_ptm_ppis {
//flatten interactant
let interactant_uniprot_id;
let interactant_name;
match &batch_ptm_ppi.interactant {
&Some(ref interactant) => {
interactant_uniprot_id = interactant.uniprot_id.clone();
interactant_name = interactant.name.clone();
},
&None => {
interactant_uniprot_id = None;
interactant_name = None;
}
}
//flatten substrate
let substrate_uniprot_id;
let substrate_name;
match &batch_ptm_ppi.substrate {
&Some(ref substrate) => {
substrate_uniprot_id = substrate.uniprot_id.clone();
substrate_name = substrate.name.clone();
},
&None => {
substrate_uniprot_id = None;
substrate_name = None;
}
}
//source
let source_name;
match &batch_ptm_ppi.source {
&Some(ref source) => {
source_name = source.name.clone();
},
&None => {
source_name = None;
}
}
// build flat batch_ptm_ppi
let batch_ptm_ppi_flat = BatchPTMPPIFlat {
ptm_type: batch_ptm_ppi.ptm_type.clone(),
site: batch_ptm_ppi.site.clone(),
site_position: batch_ptm_ppi.site_position.clone(),
association_type: batch_ptm_ppi.association_type.clone(),
interactant_id: interactant_uniprot_id,
interactant_name: interactant_name,
substrate_id: substrate_uniprot_id,
substrate_name: substrate_name,
source: source_name,
pmids: Some(misc::str_vec_to_str(&batch_ptm_ppi.pmids))
};
//add to vector
batch_ptm_ppis_flat.push(batch_ptm_ppi_flat);
}
return batch_ptm_ppis_flat;
}
pub fn sources(sources: &Vec<Source>) -> String {
let mut sources_str: String = String::new();
for (index,source) in sources.iter().enumerate(){
if index == 0 {
match &source.name {
&Some(ref name) => {sources_str = name.clone()},
&None => {}
}
}else {
match &source.name {
&Some(ref name) => {
sources_str = format!("{prev_str},{curr_str}",prev_str=sources_str,curr_str=name);
},
&None => {}
}
}
}
return sources_str;
} |
use std::rc::Rc;
pub type Getter<S, A> = dyn Fn(&S) -> A;
pub type Setter<S, A> = dyn Fn(&mut S, A);
pub struct Lens<S, A> {
pub view: Rc<Getter<S, A>>,
pub set: Rc<Setter<S, A>>,
}
pub fn lens<'a, S, A>(getter: Rc<Getter<S, A>>, setter: Rc<Setter<S, A>>) -> Lens<S, A> {
Lens {
view: getter,
set: setter,
}
}
pub fn compose<S, A, B>(lhs: Rc<Lens<S, A>>, rhs: Rc<Lens<A, B>>) -> Lens<S, B>
where S: 'static, A: 'static, B: 'static {
let rhs_clone = rhs.clone();
let lhs_clone = lhs.clone();
let rhs_clone2 = rhs.clone();
let lhs_clone2 = lhs.clone();
lens(Rc::new(move |s| (rhs_clone.view)(&(lhs_clone.view)(s))),
Rc::new(move |mut s, b| {
let mut a = (lhs_clone2.view)(s);
(rhs_clone2.set)(&mut a, b);
(lhs_clone2.set)(&mut s, a);
}))
}
|
// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
access_path::AccessPath,
account_config::constants::{
association_address, type_tag_for_currency_code, CORE_CODE_ADDRESS,
},
event::EventHandle,
};
use anyhow::Result;
use move_core_types::account_address::AccountAddress;
use move_core_types::{
identifier::{IdentStr, Identifier},
language_storage::{ResourceKey, StructTag},
move_resource::MoveResource,
};
use serde::{Deserialize, Serialize};
/// Struct that represents a CurrencyInfo resource
#[derive(Debug, Serialize, Deserialize)]
pub struct CurrencyInfoResource {
total_value: u128,
preburn_value: u64,
to_stc_exchange_rate: u64,
is_synthetic: bool,
scaling_factor: u64,
fractional_part: u64,
currency_code: Identifier,
can_mint: bool,
mint_events: EventHandle,
burn_events: EventHandle,
preburn_events: EventHandle,
cancel_burn_events: EventHandle,
}
impl MoveResource for CurrencyInfoResource {
const MODULE_NAME: &'static str = "Coin";
const STRUCT_NAME: &'static str = "CurrencyInfo";
}
impl CurrencyInfoResource {
pub fn currency_code(&self) -> &IdentStr {
&self.currency_code
}
pub fn scaling_factor(&self) -> u64 {
self.scaling_factor
}
pub fn fractional_part(&self) -> u64 {
self.fractional_part
}
pub fn convert_to_lbr(&self, amount: u64) -> u64 {
let mut mult = (amount as u128) * (self.to_stc_exchange_rate as u128);
mult >>= 32;
mult as u64
}
pub fn struct_tag_for(
currency_module_address: AccountAddress,
currency_code: Identifier,
) -> StructTag {
StructTag {
address: CORE_CODE_ADDRESS,
module: CurrencyInfoResource::module_identifier(),
name: CurrencyInfoResource::struct_identifier(),
type_params: vec![type_tag_for_currency_code(
Some(currency_module_address),
currency_code,
)],
}
}
pub fn resource_path_for(
currency_module_address: AccountAddress,
currency_code: Identifier,
) -> AccessPath {
let resource_address = if currency_module_address == CORE_CODE_ADDRESS {
association_address()
} else {
currency_module_address
};
let resource_key = ResourceKey::new(
resource_address,
CurrencyInfoResource::struct_tag_for(currency_module_address, currency_code),
);
AccessPath::resource_access_path(&resource_key)
}
pub fn access_path_for(
currency_module_address: AccountAddress,
currency_code: Identifier,
) -> Vec<u8> {
AccessPath::resource_access_vec(&CurrencyInfoResource::struct_tag_for(
currency_module_address,
currency_code,
))
}
pub fn try_from_bytes(bytes: &[u8]) -> Result<Self> {
scs::from_bytes(bytes).map_err(Into::into)
}
}
|
use std::collections::HashMap;
fn main() {
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);
let teams = vec![String::from("Blue"), String::from("Yellow")];
let initial_scores = vec![10, 50];
let scores_2: HashMap<_, _> = teams.into_iter().zip(initial_scores.into_iter()).collect();
// use get to fetch value from array by key (reference)
let score = scores_2.get(&String::from("Blue"));
if let Some(val) = score {
println!("Key 'Blue' has value: {}", val);
}
for (key, value) in &scores_2 {
println!("{}: {}", key, value);
}
// overwriting a value
scores.insert(String::from("Blue"), 44);
println!("{:?}", scores);
// only inserting a value if the key has no value
// or_insert: defined to retun a mutable reference to the value for the corresponding Entry
// key if that key exists, and if not, inserts the parameter as the new value for this
// key and returns a mutable reference to the new value
scores.entry(String::from("Yellow")).or_insert(50); // this will insert "Yellow": 50 since it doesn't exist
scores.entry(String::from("Blue")).or_insert(50); // this will see that "Blue" is already present
// and the entry will not be updated
println!("{:?}", scores);
// Updating a value based on the old value
let text = "hello world wonderful world";
let mut map = HashMap::new();
for word in text.split_whitespace() {
let count = map.entry(word).or_insert(0);
*count += 1;
}
println!("{:?}", map);
}
|
//! SRT Source stream
mod decoder;
pub mod filters;
mod graph;
mod media_stream;
mod srt_source;
mod stream_descriptor;
pub use decoder::Decoder;
pub use srt_source::SrtSource;
pub use stream_descriptor::StreamDescriptor;
|
// Copyright 2020 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use codec::{Decode, Encode};
use hash_db::{HashDB, Hasher};
use sp_std::vec::Vec;
/// A proof that some set of key-value pairs are included in the storage trie. The proof contains
/// the storage values so that the partial storage backend can be reconstructed by a verifier that
/// does not already have access to the key-value pairs.
///
/// The proof consists of the set of serialized nodes in the storage trie accessed when looking up
/// the keys covered by the proof. Verifying the proof requires constructing the partial trie from
/// the serialized nodes and performing the key lookups.
#[derive(Debug, PartialEq, Eq, Clone, Encode, Decode)]
pub struct StorageProof {
trie_nodes: Vec<Vec<u8>>,
}
impl StorageProof {
/// Constructs a storage proof from a subset of encoded trie nodes in a storage backend.
pub fn new(trie_nodes: Vec<Vec<u8>>) -> Self {
StorageProof { trie_nodes }
}
/// Returns a new empty proof.
///
/// An empty proof is capable of only proving trivial statements (ie. that an empty set of
/// key-value pairs exist in storage).
pub fn empty() -> Self {
StorageProof { trie_nodes: Vec::new() }
}
/// Returns whether this is an empty proof.
pub fn is_empty(&self) -> bool {
self.trie_nodes.is_empty()
}
/// Create an iterator over trie nodes constructed from the proof. The nodes are not guaranteed
/// to be traversed in any particular order.
pub fn iter_nodes(self) -> StorageProofNodeIterator {
StorageProofNodeIterator::new(self)
}
/// Creates a `MemoryDB` from `Self`.
pub fn into_memory_db<H: Hasher>(self) -> crate::MemoryDB<H> {
self.into()
}
/// Merges multiple storage proofs covering potentially different sets of keys into one proof
/// covering all keys. The merged proof output may be smaller than the aggregate size of the
/// input proofs due to deduplication of trie nodes.
pub fn merge<I>(proofs: I) -> Self
where
I: IntoIterator<Item = Self>,
{
let trie_nodes = proofs
.into_iter()
.flat_map(|proof| proof.iter_nodes())
.collect::<sp_std::collections::btree_set::BTreeSet<_>>()
.into_iter()
.collect();
Self { trie_nodes }
}
}
/// An iterator over trie nodes constructed from a storage proof. The nodes are not guaranteed to
/// be traversed in any particular order.
pub struct StorageProofNodeIterator {
inner: <Vec<Vec<u8>> as IntoIterator>::IntoIter,
}
impl StorageProofNodeIterator {
fn new(proof: StorageProof) -> Self {
StorageProofNodeIterator { inner: proof.trie_nodes.into_iter() }
}
}
impl Iterator for StorageProofNodeIterator {
type Item = Vec<u8>;
fn next(&mut self) -> Option<Self::Item> {
self.inner.next()
}
}
impl<H: Hasher> From<StorageProof> for crate::MemoryDB<H> {
fn from(proof: StorageProof) -> Self {
let mut db = crate::MemoryDB::default();
for item in proof.iter_nodes() {
db.insert(crate::EMPTY_PREFIX, &item);
}
db
}
}
|
use {
proc_macro2::{Span, TokenStream},
quote::{quote, ToTokens, TokenStreamExt},
std::collections::HashSet,
syn::parse,
};
#[derive(Debug)]
pub struct PathImplInput {
module: syn::Path,
comma: syn::Token![,],
path: syn::LitStr,
}
impl parse::Parse for PathImplInput {
fn parse(input: parse::ParseStream<'_>) -> parse::Result<Self> {
Ok(Self {
module: input.parse()?,
comma: input.parse()?,
path: input.parse()?,
})
}
}
pub fn path_impl(input: TokenStream) -> parse::Result<TokenStream> {
let input: PathImplInput = syn::parse2(input)?;
let path = &input.path.value();
let output = PathImplOutput {
path,
params: parse_literal(path, input.path.span())?,
module: input.module,
};
Ok(quote::quote_spanned!(input.path.span() => #output))
}
#[derive(Debug, Copy, Clone, PartialEq)]
enum Param<'a> {
Single(&'a str),
CatchAll(&'a str),
}
fn spanned_err<T>(span: Span, message: impl std::fmt::Display) -> parse::Result<T> {
Err(parse::Error::new(span, message))
}
fn parse_literal(path: &str, span: Span) -> parse::Result<Vec<Param<'_>>> {
match path {
"" => return spanned_err(span, "the path cannot be empty"),
"/" | "*" => return Ok(vec![]),
_ => {}
}
let mut iter = path.split('/').peekable();
if iter.next().map_or(false, |s| !s.is_empty()) {
return spanned_err(span, "the path must start with a slash.");
}
let mut params = vec![];
let mut names = HashSet::new();
while let Some(segment) = iter.next() {
match segment.split_at(1) {
(":", name) => {
if !names.insert(name) {
return spanned_err(
span,
format!("detected duplicate parameter name: '{}'", name),
);
}
params.push(Param::Single(name));
}
("*", name) => {
if !names.insert(name) {
return spanned_err(
span,
format!("detected duplicate parameter name: '{}'", name),
);
}
params.push(Param::CatchAll(name));
break;
}
_ => {
if segment.is_empty() && iter.peek().is_some() {
return spanned_err(span, "a segment must not be empty");
}
}
}
}
if iter.next().is_some() {
return spanned_err(span, "the catch-all parameter must be at the end of path");
}
Ok(params)
}
#[derive(Debug)]
pub struct PathImplOutput<'a> {
module: syn::Path,
path: &'a str,
params: Vec<Param<'a>>,
}
impl<'a> ToTokens for PathImplOutput<'a> {
#[allow(nonstandard_style)]
fn to_tokens(&self, tokens: &mut TokenStream) {
let path = self.path;
let module = &self.module;
let Path = quote!(#module::Path);
let Params = quote!(#module::Params);
let PercentEncoded = quote!(#module::PercentEncoded);
let FromPercentEncoded = quote!(#module::FromPercentEncoded);
let Error = quote!(#module::Error);
if self.params.is_empty() {
tokens.append_all(quote!(
fn call() -> &'static str {
#path
}
));
return;
}
let type_idents: Vec<_> = self
.params
.iter()
.enumerate()
.map(|(i, _)| syn::Ident::new(&format!("T{}", i), Span::call_site()))
.collect();
let type_idents = &type_idents[..];
let where_clause = {
let bounds = type_idents
.iter()
.map(|ty| quote!(#ty: #FromPercentEncoded));
quote!(where #(#bounds,)*)
};
let where_clause = &where_clause;
let extract = self.params.iter().zip(type_idents).map(|(param, ty)| {
let extract_raw = match param {
Param::Single(name) => quote!(params.name(#name).expect("missing parameter")),
Param::CatchAll(..) => {
quote!(params.catch_all().expect("missing catch-all parameter"))
}
};
quote!(
let #ty = <#ty as #FromPercentEncoded>::from_percent_encoded(
unsafe { #PercentEncoded::new_unchecked(#extract_raw) }
).map_err(Into::into)?;
)
});
tokens.append_all(quote! {
fn call<#(#type_idents),*>() -> impl #Path<Output = (#(#type_idents,)*)>
#where_clause
{
#[allow(missing_debug_implementations)]
struct __Extractor<#(#type_idents),*> {
_marker: std::marker::PhantomData<fn() -> (#(#type_idents,)*)>,
}
impl<#(#type_idents),*> #Path for __Extractor<#(#type_idents),*>
#where_clause
{
type Output = (#(#type_idents,)*);
fn as_str(&self) -> &str {
#path
}
#[allow(nonstandard_style)]
fn extract(params: Option<&#Params<'_>>)
-> std::result::Result<Self::Output, #Error>
{
let params = params.expect("missing Params");
#( #extract )*
Ok((#(#type_idents,)*))
}
}
__Extractor::<#(#type_idents),*> {
_marker: std::marker::PhantomData,
}
}
});
}
}
|
/// An enum to represent all characters in the CJKCompatibilityForms block.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum CJKCompatibilityForms {
/// \u{fe30}: '๏ธฐ'
PresentationFormForVerticalTwoDotLeader,
/// \u{fe31}: '๏ธฑ'
PresentationFormForVerticalEmDash,
/// \u{fe32}: '๏ธฒ'
PresentationFormForVerticalEnDash,
/// \u{fe33}: '๏ธณ'
PresentationFormForVerticalLowLine,
/// \u{fe34}: '๏ธด'
PresentationFormForVerticalWavyLowLine,
/// \u{fe35}: '๏ธต'
PresentationFormForVerticalLeftParenthesis,
/// \u{fe36}: '๏ธถ'
PresentationFormForVerticalRightParenthesis,
/// \u{fe37}: '๏ธท'
PresentationFormForVerticalLeftCurlyBracket,
/// \u{fe38}: '๏ธธ'
PresentationFormForVerticalRightCurlyBracket,
/// \u{fe39}: '๏ธน'
PresentationFormForVerticalLeftTortoiseShellBracket,
/// \u{fe3a}: '๏ธบ'
PresentationFormForVerticalRightTortoiseShellBracket,
/// \u{fe3b}: '๏ธป'
PresentationFormForVerticalLeftBlackLenticularBracket,
/// \u{fe3c}: '๏ธผ'
PresentationFormForVerticalRightBlackLenticularBracket,
/// \u{fe3d}: '๏ธฝ'
PresentationFormForVerticalLeftDoubleAngleBracket,
/// \u{fe3e}: '๏ธพ'
PresentationFormForVerticalRightDoubleAngleBracket,
/// \u{fe3f}: '๏ธฟ'
PresentationFormForVerticalLeftAngleBracket,
/// \u{fe40}: '๏น'
PresentationFormForVerticalRightAngleBracket,
/// \u{fe41}: '๏น'
PresentationFormForVerticalLeftCornerBracket,
/// \u{fe42}: '๏น'
PresentationFormForVerticalRightCornerBracket,
/// \u{fe43}: '๏น'
PresentationFormForVerticalLeftWhiteCornerBracket,
/// \u{fe44}: '๏น'
PresentationFormForVerticalRightWhiteCornerBracket,
/// \u{fe45}: '๏น
'
SesameDot,
/// \u{fe46}: '๏น'
WhiteSesameDot,
/// \u{fe47}: '๏น'
PresentationFormForVerticalLeftSquareBracket,
/// \u{fe48}: '๏น'
PresentationFormForVerticalRightSquareBracket,
/// \u{fe49}: '๏น'
DashedOverline,
/// \u{fe4a}: '๏น'
CentrelineOverline,
/// \u{fe4b}: '๏น'
WavyOverline,
/// \u{fe4c}: '๏น'
DoubleWavyOverline,
/// \u{fe4d}: '๏น'
DashedLowLine,
/// \u{fe4e}: '๏น'
CentrelineLowLine,
}
impl Into<char> for CJKCompatibilityForms {
fn into(self) -> char {
match self {
CJKCompatibilityForms::PresentationFormForVerticalTwoDotLeader => '๏ธฐ',
CJKCompatibilityForms::PresentationFormForVerticalEmDash => '๏ธฑ',
CJKCompatibilityForms::PresentationFormForVerticalEnDash => '๏ธฒ',
CJKCompatibilityForms::PresentationFormForVerticalLowLine => '๏ธณ',
CJKCompatibilityForms::PresentationFormForVerticalWavyLowLine => '๏ธด',
CJKCompatibilityForms::PresentationFormForVerticalLeftParenthesis => '๏ธต',
CJKCompatibilityForms::PresentationFormForVerticalRightParenthesis => '๏ธถ',
CJKCompatibilityForms::PresentationFormForVerticalLeftCurlyBracket => '๏ธท',
CJKCompatibilityForms::PresentationFormForVerticalRightCurlyBracket => '๏ธธ',
CJKCompatibilityForms::PresentationFormForVerticalLeftTortoiseShellBracket => '๏ธน',
CJKCompatibilityForms::PresentationFormForVerticalRightTortoiseShellBracket => '๏ธบ',
CJKCompatibilityForms::PresentationFormForVerticalLeftBlackLenticularBracket => '๏ธป',
CJKCompatibilityForms::PresentationFormForVerticalRightBlackLenticularBracket => '๏ธผ',
CJKCompatibilityForms::PresentationFormForVerticalLeftDoubleAngleBracket => '๏ธฝ',
CJKCompatibilityForms::PresentationFormForVerticalRightDoubleAngleBracket => '๏ธพ',
CJKCompatibilityForms::PresentationFormForVerticalLeftAngleBracket => '๏ธฟ',
CJKCompatibilityForms::PresentationFormForVerticalRightAngleBracket => '๏น',
CJKCompatibilityForms::PresentationFormForVerticalLeftCornerBracket => '๏น',
CJKCompatibilityForms::PresentationFormForVerticalRightCornerBracket => '๏น',
CJKCompatibilityForms::PresentationFormForVerticalLeftWhiteCornerBracket => '๏น',
CJKCompatibilityForms::PresentationFormForVerticalRightWhiteCornerBracket => '๏น',
CJKCompatibilityForms::SesameDot => '๏น
',
CJKCompatibilityForms::WhiteSesameDot => '๏น',
CJKCompatibilityForms::PresentationFormForVerticalLeftSquareBracket => '๏น',
CJKCompatibilityForms::PresentationFormForVerticalRightSquareBracket => '๏น',
CJKCompatibilityForms::DashedOverline => '๏น',
CJKCompatibilityForms::CentrelineOverline => '๏น',
CJKCompatibilityForms::WavyOverline => '๏น',
CJKCompatibilityForms::DoubleWavyOverline => '๏น',
CJKCompatibilityForms::DashedLowLine => '๏น',
CJKCompatibilityForms::CentrelineLowLine => '๏น',
}
}
}
impl std::convert::TryFrom<char> for CJKCompatibilityForms {
type Error = ();
fn try_from(c: char) -> Result<Self, Self::Error> {
match c {
'๏ธฐ' => Ok(CJKCompatibilityForms::PresentationFormForVerticalTwoDotLeader),
'๏ธฑ' => Ok(CJKCompatibilityForms::PresentationFormForVerticalEmDash),
'๏ธฒ' => Ok(CJKCompatibilityForms::PresentationFormForVerticalEnDash),
'๏ธณ' => Ok(CJKCompatibilityForms::PresentationFormForVerticalLowLine),
'๏ธด' => Ok(CJKCompatibilityForms::PresentationFormForVerticalWavyLowLine),
'๏ธต' => Ok(CJKCompatibilityForms::PresentationFormForVerticalLeftParenthesis),
'๏ธถ' => Ok(CJKCompatibilityForms::PresentationFormForVerticalRightParenthesis),
'๏ธท' => Ok(CJKCompatibilityForms::PresentationFormForVerticalLeftCurlyBracket),
'๏ธธ' => Ok(CJKCompatibilityForms::PresentationFormForVerticalRightCurlyBracket),
'๏ธน' => Ok(CJKCompatibilityForms::PresentationFormForVerticalLeftTortoiseShellBracket),
'๏ธบ' => Ok(CJKCompatibilityForms::PresentationFormForVerticalRightTortoiseShellBracket),
'๏ธป' => Ok(CJKCompatibilityForms::PresentationFormForVerticalLeftBlackLenticularBracket),
'๏ธผ' => Ok(CJKCompatibilityForms::PresentationFormForVerticalRightBlackLenticularBracket),
'๏ธฝ' => Ok(CJKCompatibilityForms::PresentationFormForVerticalLeftDoubleAngleBracket),
'๏ธพ' => Ok(CJKCompatibilityForms::PresentationFormForVerticalRightDoubleAngleBracket),
'๏ธฟ' => Ok(CJKCompatibilityForms::PresentationFormForVerticalLeftAngleBracket),
'๏น' => Ok(CJKCompatibilityForms::PresentationFormForVerticalRightAngleBracket),
'๏น' => Ok(CJKCompatibilityForms::PresentationFormForVerticalLeftCornerBracket),
'๏น' => Ok(CJKCompatibilityForms::PresentationFormForVerticalRightCornerBracket),
'๏น' => Ok(CJKCompatibilityForms::PresentationFormForVerticalLeftWhiteCornerBracket),
'๏น' => Ok(CJKCompatibilityForms::PresentationFormForVerticalRightWhiteCornerBracket),
'๏น
' => Ok(CJKCompatibilityForms::SesameDot),
'๏น' => Ok(CJKCompatibilityForms::WhiteSesameDot),
'๏น' => Ok(CJKCompatibilityForms::PresentationFormForVerticalLeftSquareBracket),
'๏น' => Ok(CJKCompatibilityForms::PresentationFormForVerticalRightSquareBracket),
'๏น' => Ok(CJKCompatibilityForms::DashedOverline),
'๏น' => Ok(CJKCompatibilityForms::CentrelineOverline),
'๏น' => Ok(CJKCompatibilityForms::WavyOverline),
'๏น' => Ok(CJKCompatibilityForms::DoubleWavyOverline),
'๏น' => Ok(CJKCompatibilityForms::DashedLowLine),
'๏น' => Ok(CJKCompatibilityForms::CentrelineLowLine),
_ => Err(()),
}
}
}
impl Into<u32> for CJKCompatibilityForms {
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 CJKCompatibilityForms {
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 CJKCompatibilityForms {
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 CJKCompatibilityForms {
/// The character with the lowest index in this unicode block
pub fn new() -> Self {
CJKCompatibilityForms::PresentationFormForVerticalTwoDotLeader
}
/// The character's name, in sentence case
pub fn name(&self) -> String {
let s = std::format!("CJKCompatibilityForms{:#?}", self);
string_morph::to_sentence_case(&s)
}
}
|
use crate::{http, Request, Response};
#[cfg(feature = "https")]
use rustls::{self, ClientConfig, ClientSession};
use std::env;
use std::io::{BufReader, BufWriter, Error, ErrorKind, Read, Write};
use std::net::{TcpStream, ToSocketAddrs};
#[cfg(feature = "https")]
use std::sync::Arc;
use std::time::Duration;
#[cfg(feature = "https")]
use webpki::DNSNameRef;
#[cfg(feature = "https")]
use webpki_roots::TLS_SERVER_ROOTS;
/// A connection to the server for sending
/// [`Request`](struct.Request.html)s.
pub struct Connection {
request: Request,
timeout: Option<u64>,
}
impl Connection {
/// Creates a new `Connection`. See
/// [`Request`](struct.Request.html) for specifics about *what* is
/// being sent.
pub(crate) fn new(request: Request) -> Connection {
let timeout = request
.timeout
.or_else(|| match env::var("MINREQ_TIMEOUT") {
Ok(t) => t.parse::<u64>().ok(),
Err(_) => None,
});
Connection { request, timeout }
}
/// Sends the [`Request`](struct.Request.html), consumes this
/// connection, and returns a [`Response`](struct.Response.html).
#[cfg(feature = "https")]
pub(crate) fn send_https(self) -> Result<Response, Error> {
let is_head = self.request.method == http::Method::Head;
let bytes = self.request.to_string().into_bytes();
// Rustls setup
let dns_name = &self.request.host;
let dns_name = dns_name.split(":").next().unwrap();
let dns_name = DNSNameRef::try_from_ascii_str(dns_name).unwrap();
let mut config = ClientConfig::new();
config
.root_store
.add_server_trust_anchors(&TLS_SERVER_ROOTS);
let mut sess = ClientSession::new(&Arc::new(config), dns_name);
// IO
let mut stream = create_tcp_stream(&self.request.host, self.timeout)?;
let mut tls = rustls::Stream::new(&mut sess, &mut stream);
tls.write(&bytes)?;
match read_from_stream(tls, is_head) {
Ok(result) => handle_redirects(self, Response::from_bytes(result)),
Err(err) => Err(err),
}
}
/// Sends the [`Request`](struct.Request.html), consumes this
/// connection, and returns a [`Response`](struct.Response.html).
pub(crate) fn send(self) -> Result<Response, Error> {
let is_head = self.request.method == http::Method::Head;
let bytes = self.request.to_string().into_bytes();
let tcp = create_tcp_stream(&self.request.host, self.timeout)?;
// Send request
let mut stream = BufWriter::new(tcp);
stream.write_all(&bytes)?;
// Receive response
let tcp = stream.into_inner()?;
let mut stream = BufReader::new(tcp);
match read_from_stream(&mut stream, is_head) {
Ok(response) => handle_redirects(self, Response::from_bytes(response)),
Err(err) => match err.kind() {
ErrorKind::WouldBlock | ErrorKind::TimedOut => Err(Error::new(
ErrorKind::TimedOut,
format!(
"Request timed out! Timeout: {:?}",
stream.get_ref().read_timeout()
),
)),
_ => Err(err),
},
}
}
}
fn handle_redirects(connection: Connection, response: Response) -> Result<Response, Error> {
let status_code = response.status_code;
match status_code {
301 | 302 | 303 | 307 => {
let url = response.headers.get("Location");
if url.is_none() {
return Err(Error::new(
ErrorKind::Other,
"'Location' header missing in redirect.",
));
}
let url = url.unwrap();
let mut request = connection.request;
if request.redirects.contains(&url) {
Err(Error::new(ErrorKind::Other, "Infinite redirection loop."))
} else {
request.redirect_to(url.clone());
if status_code == 303 {
match request.method {
http::Method::Post | http::Method::Put | http::Method::Delete => {
request.method = http::Method::Get;
}
_ => {}
}
}
request.send()
}
}
_ => Ok(response),
}
}
fn create_tcp_stream<A>(host: A, timeout: Option<u64>) -> Result<TcpStream, Error>
where
A: ToSocketAddrs,
{
let stream = TcpStream::connect(host)?;
if let Some(secs) = timeout {
let dur = Some(Duration::from_secs(secs));
stream.set_read_timeout(dur)?;
stream.set_write_timeout(dur)?;
}
Ok(stream)
}
/// Reads the stream until it can't or it reaches the end of the HTTP
/// response.
fn read_from_stream<T: Read>(stream: T, head: bool) -> Result<Vec<u8>, Error> {
let mut response = Vec::new();
let mut response_length = None;
let mut chunked = false;
let mut expecting_chunk_length = false;
let mut byte_count = 0;
let mut last_newline_index = 0;
let mut blank_line = false;
let mut status_code = None;
for byte in stream.bytes() {
let byte = byte?;
response.push(byte);
byte_count += 1;
if byte == b'\n' {
if status_code.is_none() {
// First line
status_code = Some(http::parse_status_line(&response).0);
}
if blank_line {
// Two consecutive blank lines, body should start here
if let Some(code) = status_code {
if head || code / 100 == 1 || code == 204 || code == 304 {
response_length = Some(response.len());
}
}
if response_length.is_none() {
if let Ok(response_str) = std::str::from_utf8(&response) {
let len = get_response_length(response_str);
response_length = Some(len);
if len > response.len() {
response.reserve(len - response.len());
}
}
}
} else if let Ok(new_response_length_str) =
std::str::from_utf8(&response[last_newline_index..])
{
if expecting_chunk_length {
expecting_chunk_length = false;
if let Ok(n) = usize::from_str_radix(new_response_length_str.trim(), 16) {
// Cut out the chunk length from the reponse
response.truncate(last_newline_index);
byte_count = last_newline_index;
// Update response length according to the new chunk length
if n == 0 {
break;
} else {
response_length = Some(byte_count + n + 2);
}
}
} else if let Some((key, value)) = http::parse_header(new_response_length_str) {
if key.trim() == "Transfer-Encoding" && value.trim() == "chunked" {
chunked = true;
}
}
}
blank_line = true;
last_newline_index = byte_count;
} else if byte != b'\r' {
// Normal character, reset blank_line
blank_line = false;
}
if let Some(len) = response_length {
if byte_count >= len {
if chunked {
// Transfer-Encoding is chunked, next up should be
// the next chunk's length.
expecting_chunk_length = true;
} else {
// We have reached the end of the HTTP response,
// break the reading loop.
break;
}
}
}
}
Ok(response)
}
/// Tries to find out how long the whole response will eventually be,
/// in bytes.
fn get_response_length(response: &str) -> usize {
// The length of the headers
let mut byte_count = 0;
for line in response.lines() {
byte_count += line.len() + 2;
if line.starts_with("Content-Length: ") {
if let Ok(length) = line[16..].parse::<usize>() {
byte_count += length;
}
}
}
byte_count
}
|
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct JobStream {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<JobStreamProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct JobStreamProperties {
#[serde(rename = "jobStreamId", default, skip_serializing_if = "Option::is_none")]
pub job_stream_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub time: Option<String>,
#[serde(rename = "streamType", default, skip_serializing_if = "Option::is_none")]
pub stream_type: Option<job_stream_properties::StreamType>,
#[serde(rename = "streamText", default, skip_serializing_if = "Option::is_none")]
pub stream_text: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub summary: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<serde_json::Value>,
}
pub mod job_stream_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum StreamType {
Progress,
Output,
Warning,
Error,
Debug,
Verbose,
Any,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct JobStreamListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<JobStream>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ContentHash {
pub algorithm: String,
pub value: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ContentLink {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub uri: Option<String>,
#[serde(rename = "contentHash", default, skip_serializing_if = "Option::is_none")]
pub content_hash: Option<ContentHash>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RunbookProperties {
#[serde(rename = "runbookType", default, skip_serializing_if = "Option::is_none")]
pub runbook_type: Option<runbook_properties::RunbookType>,
#[serde(rename = "publishContentLink", default, skip_serializing_if = "Option::is_none")]
pub publish_content_link: Option<ContentLink>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub state: Option<runbook_properties::State>,
#[serde(rename = "logVerbose", default, skip_serializing_if = "Option::is_none")]
pub log_verbose: Option<bool>,
#[serde(rename = "logProgress", default, skip_serializing_if = "Option::is_none")]
pub log_progress: Option<bool>,
#[serde(rename = "logActivityTrace", default, skip_serializing_if = "Option::is_none")]
pub log_activity_trace: Option<i32>,
#[serde(rename = "jobCount", default, skip_serializing_if = "Option::is_none")]
pub job_count: Option<i32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parameters: Option<serde_json::Value>,
#[serde(rename = "outputTypes", default, skip_serializing_if = "Vec::is_empty")]
pub output_types: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub draft: Option<RunbookDraft>,
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<runbook_properties::ProvisioningState>,
#[serde(rename = "lastModifiedBy", default, skip_serializing_if = "Option::is_none")]
pub last_modified_by: Option<String>,
#[serde(rename = "creationTime", default, skip_serializing_if = "Option::is_none")]
pub creation_time: Option<String>,
#[serde(rename = "lastModifiedTime", default, skip_serializing_if = "Option::is_none")]
pub last_modified_time: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
pub mod runbook_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum RunbookType {
Script,
Graph,
PowerShellWorkflow,
PowerShell,
GraphPowerShellWorkflow,
GraphPowerShell,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum State {
New,
Edit,
Published,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ProvisioningState {
Succeeded,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Runbook {
#[serde(flatten)]
pub tracked_resource: TrackedResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<RunbookProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub etag: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RunbookListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Runbook>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RunbookCreateOrUpdateProperties {
#[serde(rename = "logVerbose", default, skip_serializing_if = "Option::is_none")]
pub log_verbose: Option<bool>,
#[serde(rename = "logProgress", default, skip_serializing_if = "Option::is_none")]
pub log_progress: Option<bool>,
#[serde(rename = "runbookType")]
pub runbook_type: runbook_create_or_update_properties::RunbookType,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub draft: Option<RunbookDraft>,
#[serde(rename = "publishContentLink", default, skip_serializing_if = "Option::is_none")]
pub publish_content_link: Option<ContentLink>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(rename = "logActivityTrace", default, skip_serializing_if = "Option::is_none")]
pub log_activity_trace: Option<i32>,
}
pub mod runbook_create_or_update_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum RunbookType {
Script,
Graph,
PowerShellWorkflow,
PowerShell,
GraphPowerShellWorkflow,
GraphPowerShell,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RunbookCreateOrUpdateParameters {
pub properties: RunbookCreateOrUpdateProperties,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub location: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RunbookUpdateProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(rename = "logVerbose", default, skip_serializing_if = "Option::is_none")]
pub log_verbose: Option<bool>,
#[serde(rename = "logProgress", default, skip_serializing_if = "Option::is_none")]
pub log_progress: Option<bool>,
#[serde(rename = "logActivityTrace", default, skip_serializing_if = "Option::is_none")]
pub log_activity_trace: Option<i32>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RunbookUpdateParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<RunbookUpdateProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub location: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RunbookDraftUndoEditResult {
#[serde(rename = "statusCode", default, skip_serializing_if = "Option::is_none")]
pub status_code: Option<runbook_draft_undo_edit_result::StatusCode>,
#[serde(rename = "requestId", default, skip_serializing_if = "Option::is_none")]
pub request_id: Option<String>,
}
pub mod runbook_draft_undo_edit_result {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum StatusCode {
Continue,
SwitchingProtocols,
#[serde(rename = "OK")]
Ok,
Created,
Accepted,
NonAuthoritativeInformation,
NoContent,
ResetContent,
PartialContent,
MultipleChoices,
Ambiguous,
MovedPermanently,
Moved,
Found,
Redirect,
SeeOther,
RedirectMethod,
NotModified,
UseProxy,
Unused,
TemporaryRedirect,
RedirectKeepVerb,
BadRequest,
Unauthorized,
PaymentRequired,
Forbidden,
NotFound,
MethodNotAllowed,
NotAcceptable,
ProxyAuthenticationRequired,
RequestTimeout,
Conflict,
Gone,
LengthRequired,
PreconditionFailed,
RequestEntityTooLarge,
RequestUriTooLong,
UnsupportedMediaType,
RequestedRangeNotSatisfiable,
ExpectationFailed,
UpgradeRequired,
InternalServerError,
NotImplemented,
BadGateway,
ServiceUnavailable,
GatewayTimeout,
HttpVersionNotSupported,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RunbookDraft {
#[serde(rename = "inEdit", default, skip_serializing_if = "Option::is_none")]
pub in_edit: Option<bool>,
#[serde(rename = "draftContentLink", default, skip_serializing_if = "Option::is_none")]
pub draft_content_link: Option<ContentLink>,
#[serde(rename = "creationTime", default, skip_serializing_if = "Option::is_none")]
pub creation_time: Option<String>,
#[serde(rename = "lastModifiedTime", default, skip_serializing_if = "Option::is_none")]
pub last_modified_time: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parameters: Option<serde_json::Value>,
#[serde(rename = "outputTypes", default, skip_serializing_if = "Vec::is_empty")]
pub output_types: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RunbookParameter {
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(rename = "isMandatory", default, skip_serializing_if = "Option::is_none")]
pub is_mandatory: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub position: Option<i32>,
#[serde(rename = "defaultValue", default, skip_serializing_if = "Option::is_none")]
pub default_value: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TestJobCreateParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parameters: Option<serde_json::Value>,
#[serde(rename = "runOn", default, skip_serializing_if = "Option::is_none")]
pub run_on: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TestJob {
#[serde(rename = "creationTime", default, skip_serializing_if = "Option::is_none")]
pub creation_time: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<String>,
#[serde(rename = "statusDetails", default, skip_serializing_if = "Option::is_none")]
pub status_details: Option<String>,
#[serde(rename = "runOn", default, skip_serializing_if = "Option::is_none")]
pub run_on: Option<String>,
#[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")]
pub start_time: Option<String>,
#[serde(rename = "endTime", default, skip_serializing_if = "Option::is_none")]
pub end_time: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub exception: Option<String>,
#[serde(rename = "lastModifiedTime", default, skip_serializing_if = "Option::is_none")]
pub last_modified_time: Option<String>,
#[serde(rename = "lastStatusModifiedTime", default, skip_serializing_if = "Option::is_none")]
pub last_status_modified_time: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parameters: Option<serde_json::Value>,
#[serde(rename = "logActivityTrace", default, skip_serializing_if = "Option::is_none")]
pub log_activity_trace: Option<i32>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RunbookCreateOrUpdateDraftProperties {
#[serde(rename = "logVerbose", default, skip_serializing_if = "Option::is_none")]
pub log_verbose: Option<bool>,
#[serde(rename = "logProgress", default, skip_serializing_if = "Option::is_none")]
pub log_progress: Option<bool>,
#[serde(rename = "runbookType")]
pub runbook_type: runbook_create_or_update_draft_properties::RunbookType,
pub draft: RunbookDraft,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(rename = "logActivityTrace", default, skip_serializing_if = "Option::is_none")]
pub log_activity_trace: Option<i32>,
}
pub mod runbook_create_or_update_draft_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum RunbookType {
Script,
Graph,
PowerShellWorkflow,
PowerShell,
GraphPowerShellWorkflow,
GraphPowerShell,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RunbookCreateOrUpdateDraftParameters {
#[serde(rename = "runbookContent")]
pub runbook_content: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ActivityParameter {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(rename = "isMandatory", default, skip_serializing_if = "Option::is_none")]
pub is_mandatory: Option<bool>,
#[serde(rename = "isDynamic", default, skip_serializing_if = "Option::is_none")]
pub is_dynamic: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub position: Option<i64>,
#[serde(rename = "valueFromPipeline", default, skip_serializing_if = "Option::is_none")]
pub value_from_pipeline: Option<bool>,
#[serde(rename = "valueFromPipelineByPropertyName", default, skip_serializing_if = "Option::is_none")]
pub value_from_pipeline_by_property_name: Option<bool>,
#[serde(rename = "valueFromRemainingArguments", default, skip_serializing_if = "Option::is_none")]
pub value_from_remaining_arguments: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(rename = "validationSet", default, skip_serializing_if = "Vec::is_empty")]
pub validation_set: Vec<ActivityParameterValidationSet>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ActivityParameterSet {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub parameters: Vec<ActivityParameter>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ActivityParameterValidationSet {
#[serde(rename = "memberValue", default, skip_serializing_if = "Option::is_none")]
pub member_value: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ActivityOutputType {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ActivityProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub definition: Option<String>,
#[serde(rename = "parameterSets", default, skip_serializing_if = "Vec::is_empty")]
pub parameter_sets: Vec<ActivityParameterSet>,
#[serde(rename = "outputTypes", default, skip_serializing_if = "Vec::is_empty")]
pub output_types: Vec<ActivityOutputType>,
#[serde(rename = "creationTime", default, skip_serializing_if = "Option::is_none")]
pub creation_time: Option<String>,
#[serde(rename = "lastModifiedTime", default, skip_serializing_if = "Option::is_none")]
pub last_modified_time: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Activity {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<ActivityProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ActivityListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Activity>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ModuleErrorInfo {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ModuleListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Module>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PythonPackageCreateProperties {
#[serde(rename = "contentLink")]
pub content_link: ContentLink,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PythonPackageCreateParameters {
pub properties: PythonPackageCreateProperties,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ModuleProperties {
#[serde(rename = "isGlobal", default, skip_serializing_if = "Option::is_none")]
pub is_global: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
#[serde(rename = "sizeInBytes", default, skip_serializing_if = "Option::is_none")]
pub size_in_bytes: Option<i64>,
#[serde(rename = "activityCount", default, skip_serializing_if = "Option::is_none")]
pub activity_count: Option<i32>,
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<module_properties::ProvisioningState>,
#[serde(rename = "contentLink", default, skip_serializing_if = "Option::is_none")]
pub content_link: Option<ContentLink>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<ModuleErrorInfo>,
#[serde(rename = "creationTime", default, skip_serializing_if = "Option::is_none")]
pub creation_time: Option<String>,
#[serde(rename = "lastModifiedTime", default, skip_serializing_if = "Option::is_none")]
pub last_modified_time: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(rename = "isComposite", default, skip_serializing_if = "Option::is_none")]
pub is_composite: Option<bool>,
}
pub mod module_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ProvisioningState {
Created,
Creating,
StartingImportModuleRunbook,
RunningImportModuleRunbook,
ContentRetrieved,
ContentDownloaded,
ContentValidated,
ConnectionTypeImported,
ContentStored,
ModuleDataStored,
ActivitiesStored,
ModuleImportRunbookComplete,
Succeeded,
Failed,
Cancelled,
Updating,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PythonPackageUpdateParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Module {
#[serde(flatten)]
pub tracked_resource: TrackedResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<ModuleProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub etag: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TypeField {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TypeFieldListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<TypeField>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DscNodeReportListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<DscNodeReport>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DscReportResourceNavigation {
#[serde(rename = "resourceId", default, skip_serializing_if = "Option::is_none")]
pub resource_id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DscMetaConfiguration {
#[serde(rename = "configurationModeFrequencyMins", default, skip_serializing_if = "Option::is_none")]
pub configuration_mode_frequency_mins: Option<i32>,
#[serde(rename = "rebootNodeIfNeeded", default, skip_serializing_if = "Option::is_none")]
pub reboot_node_if_needed: Option<bool>,
#[serde(rename = "configurationMode", default, skip_serializing_if = "Option::is_none")]
pub configuration_mode: Option<String>,
#[serde(rename = "actionAfterReboot", default, skip_serializing_if = "Option::is_none")]
pub action_after_reboot: Option<String>,
#[serde(rename = "certificateId", default, skip_serializing_if = "Option::is_none")]
pub certificate_id: Option<String>,
#[serde(rename = "refreshFrequencyMins", default, skip_serializing_if = "Option::is_none")]
pub refresh_frequency_mins: Option<i32>,
#[serde(rename = "allowModuleOverwrite", default, skip_serializing_if = "Option::is_none")]
pub allow_module_overwrite: Option<bool>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DscNodeReport {
#[serde(rename = "endTime", default, skip_serializing_if = "Option::is_none")]
pub end_time: Option<String>,
#[serde(rename = "lastModifiedTime", default, skip_serializing_if = "Option::is_none")]
pub last_modified_time: Option<String>,
#[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")]
pub start_time: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(rename = "reportId", default, skip_serializing_if = "Option::is_none")]
pub report_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<String>,
#[serde(rename = "refreshMode", default, skip_serializing_if = "Option::is_none")]
pub refresh_mode: Option<String>,
#[serde(rename = "rebootRequested", default, skip_serializing_if = "Option::is_none")]
pub reboot_requested: Option<String>,
#[serde(rename = "reportFormatVersion", default, skip_serializing_if = "Option::is_none")]
pub report_format_version: Option<String>,
#[serde(rename = "configurationVersion", default, skip_serializing_if = "Option::is_none")]
pub configuration_version: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub errors: Vec<DscReportError>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub resources: Vec<DscReportResource>,
#[serde(rename = "metaConfiguration", default, skip_serializing_if = "Option::is_none")]
pub meta_configuration: Option<DscMetaConfiguration>,
#[serde(rename = "hostName", default, skip_serializing_if = "Option::is_none")]
pub host_name: Option<String>,
#[serde(rename = "iPV4Addresses", default, skip_serializing_if = "Vec::is_empty")]
pub i_pv4_addresses: Vec<String>,
#[serde(rename = "iPV6Addresses", default, skip_serializing_if = "Vec::is_empty")]
pub i_pv6_addresses: Vec<String>,
#[serde(rename = "numberOfResources", default, skip_serializing_if = "Option::is_none")]
pub number_of_resources: Option<i32>,
#[serde(rename = "rawErrors", default, skip_serializing_if = "Option::is_none")]
pub raw_errors: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DscReportResource {
#[serde(rename = "resourceId", default, skip_serializing_if = "Option::is_none")]
pub resource_id: Option<String>,
#[serde(rename = "sourceInfo", default, skip_serializing_if = "Option::is_none")]
pub source_info: Option<String>,
#[serde(rename = "dependsOn", default, skip_serializing_if = "Vec::is_empty")]
pub depends_on: Vec<DscReportResourceNavigation>,
#[serde(rename = "moduleName", default, skip_serializing_if = "Option::is_none")]
pub module_name: Option<String>,
#[serde(rename = "moduleVersion", default, skip_serializing_if = "Option::is_none")]
pub module_version: Option<String>,
#[serde(rename = "resourceName", default, skip_serializing_if = "Option::is_none")]
pub resource_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<String>,
#[serde(rename = "durationInSeconds", default, skip_serializing_if = "Option::is_none")]
pub duration_in_seconds: Option<f64>,
#[serde(rename = "startDate", default, skip_serializing_if = "Option::is_none")]
pub start_date: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DscReportError {
#[serde(rename = "errorSource", default, skip_serializing_if = "Option::is_none")]
pub error_source: Option<String>,
#[serde(rename = "resourceId", default, skip_serializing_if = "Option::is_none")]
pub resource_id: Option<String>,
#[serde(rename = "errorCode", default, skip_serializing_if = "Option::is_none")]
pub error_code: Option<String>,
#[serde(rename = "errorMessage", default, skip_serializing_if = "Option::is_none")]
pub error_message: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub locale: Option<String>,
#[serde(rename = "errorDetails", default, skip_serializing_if = "Option::is_none")]
pub error_details: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AgentRegistration {
#[serde(rename = "dscMetaConfiguration", default, skip_serializing_if = "Option::is_none")]
pub dsc_meta_configuration: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub endpoint: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub keys: Option<AgentRegistrationKeys>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AgentRegistrationKeys {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub primary: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub secondary: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DscNode {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<DscNodeProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DscNodeProperties {
#[serde(rename = "lastSeen", default, skip_serializing_if = "Option::is_none")]
pub last_seen: Option<String>,
#[serde(rename = "registrationTime", default, skip_serializing_if = "Option::is_none")]
pub registration_time: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ip: Option<String>,
#[serde(rename = "accountId", default, skip_serializing_if = "Option::is_none")]
pub account_id: Option<String>,
#[serde(rename = "nodeConfiguration", default, skip_serializing_if = "Option::is_none")]
pub node_configuration: Option<DscNodeConfigurationAssociationProperty>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<String>,
#[serde(rename = "nodeId", default, skip_serializing_if = "Option::is_none")]
pub node_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub etag: Option<String>,
#[serde(rename = "totalCount", default, skip_serializing_if = "Option::is_none")]
pub total_count: Option<i64>,
#[serde(rename = "extensionHandler", default, skip_serializing_if = "Vec::is_empty")]
pub extension_handler: Vec<DscNodeExtensionHandlerAssociationProperty>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DscNodeExtensionHandlerAssociationProperty {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DscNodeConfigurationAssociationProperty {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AgentRegistrationRegenerateKeyParameter {
#[serde(rename = "keyName")]
pub key_name: agent_registration_regenerate_key_parameter::KeyName,
}
pub mod agent_registration_regenerate_key_parameter {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum KeyName {
#[serde(rename = "primary")]
Primary,
#[serde(rename = "secondary")]
Secondary,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DscNodeUpdateParameters {
#[serde(rename = "nodeId", default, skip_serializing_if = "Option::is_none")]
pub node_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<dsc_node_update_parameters::Properties>,
}
pub mod dsc_node_update_parameters {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(rename = "nodeConfiguration", default, skip_serializing_if = "Option::is_none")]
pub node_configuration: Option<DscNodeConfigurationAssociationProperty>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DscNodeListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<DscNode>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
#[serde(rename = "totalCount", default, skip_serializing_if = "Option::is_none")]
pub total_count: Option<i64>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DscCompilationJob {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<DscCompilationJobProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DscCompilationJobCreateProperties {
pub configuration: DscConfigurationAssociationProperty,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parameters: Option<serde_json::Value>,
#[serde(rename = "incrementNodeConfigurationBuild", default, skip_serializing_if = "Option::is_none")]
pub increment_node_configuration_build: Option<bool>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DscCompilationJobProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub configuration: Option<DscConfigurationAssociationProperty>,
#[serde(rename = "startedBy", default, skip_serializing_if = "Option::is_none")]
pub started_by: Option<String>,
#[serde(rename = "jobId", default, skip_serializing_if = "Option::is_none")]
pub job_id: Option<String>,
#[serde(rename = "creationTime", default, skip_serializing_if = "Option::is_none")]
pub creation_time: Option<String>,
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<JobProvisioningStateProperty>,
#[serde(rename = "runOn", default, skip_serializing_if = "Option::is_none")]
pub run_on: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<dsc_compilation_job_properties::Status>,
#[serde(rename = "statusDetails", default, skip_serializing_if = "Option::is_none")]
pub status_details: Option<String>,
#[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")]
pub start_time: Option<String>,
#[serde(rename = "endTime", default, skip_serializing_if = "Option::is_none")]
pub end_time: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub exception: Option<String>,
#[serde(rename = "lastModifiedTime", default, skip_serializing_if = "Option::is_none")]
pub last_modified_time: Option<String>,
#[serde(rename = "lastStatusModifiedTime", default, skip_serializing_if = "Option::is_none")]
pub last_status_modified_time: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parameters: Option<serde_json::Value>,
}
pub mod dsc_compilation_job_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Status {
New,
Activating,
Running,
Completed,
Failed,
Stopped,
Blocked,
Suspended,
Disconnected,
Suspending,
Stopping,
Resuming,
Removing,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DscCompilationJobListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<DscCompilationJob>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DscCompilationJobCreateParameters {
pub properties: DscCompilationJobCreateProperties,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub location: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DscConfigurationAssociationProperty {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum JobProvisioningStateProperty {
Failed,
Succeeded,
Suspended,
Processing,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ContentSource {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub hash: Option<ContentHash>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<content_source::Type>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
}
pub mod content_source {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Type {
#[serde(rename = "embeddedContent")]
EmbeddedContent,
#[serde(rename = "uri")]
Uri,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DscNodeConfiguration {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<DscNodeConfigurationProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DscNodeConfigurationProperties {
#[serde(rename = "lastModifiedTime", default, skip_serializing_if = "Option::is_none")]
pub last_modified_time: Option<String>,
#[serde(rename = "creationTime", default, skip_serializing_if = "Option::is_none")]
pub creation_time: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub configuration: Option<DscConfigurationAssociationProperty>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub source: Option<String>,
#[serde(rename = "nodeCount", default, skip_serializing_if = "Option::is_none")]
pub node_count: Option<i64>,
#[serde(rename = "incrementNodeConfigurationBuild", default, skip_serializing_if = "Option::is_none")]
pub increment_node_configuration_build: Option<bool>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DscNodeConfigurationListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<DscNodeConfiguration>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
#[serde(rename = "totalCount", default, skip_serializing_if = "Option::is_none")]
pub total_count: Option<i64>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DscNodeConfigurationCreateOrUpdateParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<DscNodeConfigurationCreateOrUpdateParametersProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DscNodeConfigurationCreateOrUpdateParametersProperties {
pub source: ContentSource,
pub configuration: DscConfigurationAssociationProperty,
#[serde(rename = "incrementNodeConfigurationBuild", default, skip_serializing_if = "Option::is_none")]
pub increment_node_configuration_build: Option<bool>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct NodeCounts {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<NodeCount>,
#[serde(rename = "totalCount", default, skip_serializing_if = "Option::is_none")]
pub total_count: Option<i64>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct NodeCount {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<NodeCountProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct NodeCountProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub count: Option<i64>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SoftwareUpdateConfigurationRun {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<SoftwareUpdateConfigurationRunProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SoftwareUpdateConfigurationRunProperties {
#[serde(rename = "softwareUpdateConfiguration", default, skip_serializing_if = "Option::is_none")]
pub software_update_configuration: Option<UpdateConfigurationNavigation>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<String>,
#[serde(rename = "configuredDuration", default, skip_serializing_if = "Option::is_none")]
pub configured_duration: Option<String>,
#[serde(rename = "osType", default, skip_serializing_if = "Option::is_none")]
pub os_type: Option<String>,
#[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")]
pub start_time: Option<String>,
#[serde(rename = "endTime", default, skip_serializing_if = "Option::is_none")]
pub end_time: Option<String>,
#[serde(rename = "computerCount", default, skip_serializing_if = "Option::is_none")]
pub computer_count: Option<i64>,
#[serde(rename = "failedCount", default, skip_serializing_if = "Option::is_none")]
pub failed_count: Option<i64>,
#[serde(rename = "creationTime", default, skip_serializing_if = "Option::is_none")]
pub creation_time: Option<String>,
#[serde(rename = "createdBy", default, skip_serializing_if = "Option::is_none")]
pub created_by: Option<String>,
#[serde(rename = "lastModifiedTime", default, skip_serializing_if = "Option::is_none")]
pub last_modified_time: Option<String>,
#[serde(rename = "lastModifiedBy", default, skip_serializing_if = "Option::is_none")]
pub last_modified_by: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tasks: Option<SoftwareUpdateConfigurationRunTasks>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SoftwareUpdateConfigurationRunTasks {
#[serde(rename = "preTask", default, skip_serializing_if = "Option::is_none")]
pub pre_task: Option<SoftwareUpdateConfigurationRunTaskProperties>,
#[serde(rename = "postTask", default, skip_serializing_if = "Option::is_none")]
pub post_task: Option<SoftwareUpdateConfigurationRunTaskProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SoftwareUpdateConfigurationRunTaskProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub source: Option<String>,
#[serde(rename = "jobId", default, skip_serializing_if = "Option::is_none")]
pub job_id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UpdateConfigurationNavigation {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SoftwareUpdateConfigurationRunListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<SoftwareUpdateConfigurationRun>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SoftwareUpdateConfigurationMachineRun {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<UpdateConfigurationMachineRunProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SoftwareUpdateConfigurationMachineRunListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<SoftwareUpdateConfigurationMachineRun>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UpdateConfigurationMachineRunProperties {
#[serde(rename = "targetComputer", default, skip_serializing_if = "Option::is_none")]
pub target_computer: Option<String>,
#[serde(rename = "targetComputerType", default, skip_serializing_if = "Option::is_none")]
pub target_computer_type: Option<String>,
#[serde(rename = "softwareUpdateConfiguration", default, skip_serializing_if = "Option::is_none")]
pub software_update_configuration: Option<UpdateConfigurationNavigation>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<String>,
#[serde(rename = "osType", default, skip_serializing_if = "Option::is_none")]
pub os_type: Option<String>,
#[serde(rename = "correlationId", default, skip_serializing_if = "Option::is_none")]
pub correlation_id: Option<String>,
#[serde(rename = "sourceComputerId", default, skip_serializing_if = "Option::is_none")]
pub source_computer_id: Option<String>,
#[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")]
pub start_time: Option<String>,
#[serde(rename = "endTime", default, skip_serializing_if = "Option::is_none")]
pub end_time: Option<String>,
#[serde(rename = "configuredDuration", default, skip_serializing_if = "Option::is_none")]
pub configured_duration: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub job: Option<JobNavigation>,
#[serde(rename = "creationTime", default, skip_serializing_if = "Option::is_none")]
pub creation_time: Option<String>,
#[serde(rename = "createdBy", default, skip_serializing_if = "Option::is_none")]
pub created_by: Option<String>,
#[serde(rename = "lastModifiedTime", default, skip_serializing_if = "Option::is_none")]
pub last_modified_time: Option<String>,
#[serde(rename = "lastModifiedBy", default, skip_serializing_if = "Option::is_none")]
pub last_modified_by: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<ErrorResponse>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct JobNavigation {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SourceControlListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<SourceControl>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SourceControlUpdateProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub branch: Option<String>,
#[serde(rename = "folderPath", default, skip_serializing_if = "Option::is_none")]
pub folder_path: Option<String>,
#[serde(rename = "autoSync", default, skip_serializing_if = "Option::is_none")]
pub auto_sync: Option<bool>,
#[serde(rename = "publishRunbook", default, skip_serializing_if = "Option::is_none")]
pub publish_runbook: Option<bool>,
#[serde(rename = "securityToken", default, skip_serializing_if = "Option::is_none")]
pub security_token: Option<SourceControlSecurityTokenProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SourceControlUpdateParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<SourceControlUpdateProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SourceControl {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<SourceControlProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SourceControlProperties {
#[serde(rename = "repoUrl", default, skip_serializing_if = "Option::is_none")]
pub repo_url: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub branch: Option<String>,
#[serde(rename = "folderPath", default, skip_serializing_if = "Option::is_none")]
pub folder_path: Option<String>,
#[serde(rename = "autoSync", default, skip_serializing_if = "Option::is_none")]
pub auto_sync: Option<bool>,
#[serde(rename = "publishRunbook", default, skip_serializing_if = "Option::is_none")]
pub publish_runbook: Option<bool>,
#[serde(rename = "sourceType", default, skip_serializing_if = "Option::is_none")]
pub source_type: Option<source_control_properties::SourceType>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(rename = "creationTime", default, skip_serializing_if = "Option::is_none")]
pub creation_time: Option<String>,
#[serde(rename = "lastModifiedTime", default, skip_serializing_if = "Option::is_none")]
pub last_modified_time: Option<String>,
}
pub mod source_control_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum SourceType {
VsoGit,
VsoTfvc,
GitHub,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SourceControlCreateOrUpdateParameters {
pub properties: SourceControlCreateOrUpdateProperties,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SourceControlCreateOrUpdateProperties {
#[serde(rename = "repoUrl", default, skip_serializing_if = "Option::is_none")]
pub repo_url: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub branch: Option<String>,
#[serde(rename = "folderPath", default, skip_serializing_if = "Option::is_none")]
pub folder_path: Option<String>,
#[serde(rename = "autoSync", default, skip_serializing_if = "Option::is_none")]
pub auto_sync: Option<bool>,
#[serde(rename = "publishRunbook", default, skip_serializing_if = "Option::is_none")]
pub publish_runbook: Option<bool>,
#[serde(rename = "sourceType", default, skip_serializing_if = "Option::is_none")]
pub source_type: Option<source_control_create_or_update_properties::SourceType>,
#[serde(rename = "securityToken", default, skip_serializing_if = "Option::is_none")]
pub security_token: Option<SourceControlSecurityTokenProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
pub mod source_control_create_or_update_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum SourceType {
VsoGit,
VsoTfvc,
GitHub,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SourceControlSecurityTokenProperties {
#[serde(rename = "accessToken", default, skip_serializing_if = "Option::is_none")]
pub access_token: Option<String>,
#[serde(rename = "refreshToken", default, skip_serializing_if = "Option::is_none")]
pub refresh_token: Option<String>,
#[serde(rename = "tokenType", default, skip_serializing_if = "Option::is_none")]
pub token_type: Option<source_control_security_token_properties::TokenType>,
}
pub mod source_control_security_token_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum TokenType {
PersonalAccessToken,
Oauth,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SourceControlSyncJobListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<SourceControlSyncJob>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SourceControlSyncJobCreateParameters {
pub properties: SourceControlSyncJobCreateProperties,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SourceControlSyncJobCreateProperties {
#[serde(rename = "commitId")]
pub commit_id: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SourceControlSyncJobById {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<SourceControlSyncJobByIdProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SourceControlSyncJobByIdProperties {
#[serde(rename = "sourceControlSyncJobId", default, skip_serializing_if = "Option::is_none")]
pub source_control_sync_job_id: Option<String>,
#[serde(rename = "creationTime", default, skip_serializing_if = "Option::is_none")]
pub creation_time: Option<String>,
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<source_control_sync_job_by_id_properties::ProvisioningState>,
#[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")]
pub start_time: Option<String>,
#[serde(rename = "endTime", default, skip_serializing_if = "Option::is_none")]
pub end_time: Option<String>,
#[serde(rename = "syncType", default, skip_serializing_if = "Option::is_none")]
pub sync_type: Option<source_control_sync_job_by_id_properties::SyncType>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub exception: Option<String>,
}
pub mod source_control_sync_job_by_id_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ProvisioningState {
Completed,
Failed,
Running,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum SyncType {
PartialSync,
FullSync,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SourceControlSyncJob {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<SourceControlSyncJobProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SourceControlSyncJobProperties {
#[serde(rename = "sourceControlSyncJobId", default, skip_serializing_if = "Option::is_none")]
pub source_control_sync_job_id: Option<String>,
#[serde(rename = "creationTime", default, skip_serializing_if = "Option::is_none")]
pub creation_time: Option<String>,
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<source_control_sync_job_properties::ProvisioningState>,
#[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")]
pub start_time: Option<String>,
#[serde(rename = "endTime", default, skip_serializing_if = "Option::is_none")]
pub end_time: Option<String>,
#[serde(rename = "syncType", default, skip_serializing_if = "Option::is_none")]
pub sync_type: Option<source_control_sync_job_properties::SyncType>,
}
pub mod source_control_sync_job_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ProvisioningState {
Completed,
Failed,
Running,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum SyncType {
PartialSync,
FullSync,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SourceControlSyncJobStreamsListBySyncJob {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<SourceControlSyncJobStream>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SourceControlSyncJobStream {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<SourceControlSyncJobStreamProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SourceControlSyncJobStreamProperties {
#[serde(rename = "sourceControlSyncJobStreamId", default, skip_serializing_if = "Option::is_none")]
pub source_control_sync_job_stream_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub summary: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub time: Option<String>,
#[serde(rename = "streamType", default, skip_serializing_if = "Option::is_none")]
pub stream_type: Option<source_control_sync_job_stream_properties::StreamType>,
}
pub mod source_control_sync_job_stream_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum StreamType {
Error,
Output,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SourceControlSyncJobStreamById {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<SourceControlSyncJobStreamByIdProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SourceControlSyncJobStreamByIdProperties {
#[serde(rename = "sourceControlSyncJobStreamId", default, skip_serializing_if = "Option::is_none")]
pub source_control_sync_job_stream_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub summary: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub time: Option<String>,
#[serde(rename = "streamType", default, skip_serializing_if = "Option::is_none")]
pub stream_type: Option<source_control_sync_job_stream_by_id_properties::StreamType>,
#[serde(rename = "streamText", default, skip_serializing_if = "Option::is_none")]
pub stream_text: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<serde_json::Value>,
}
pub mod source_control_sync_job_stream_by_id_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum StreamType {
Error,
Output,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Job {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<JobProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct JobListResultV2 {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<JobCollectionItem>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct JobCollectionItem {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
pub properties: JobCollectionItemProperties,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct JobProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub runbook: Option<RunbookAssociationProperty>,
#[serde(rename = "startedBy", default, skip_serializing_if = "Option::is_none")]
pub started_by: Option<String>,
#[serde(rename = "runOn", default, skip_serializing_if = "Option::is_none")]
pub run_on: Option<String>,
#[serde(rename = "jobId", default, skip_serializing_if = "Option::is_none")]
pub job_id: Option<String>,
#[serde(rename = "creationTime", default, skip_serializing_if = "Option::is_none")]
pub creation_time: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<job_properties::Status>,
#[serde(rename = "statusDetails", default, skip_serializing_if = "Option::is_none")]
pub status_details: Option<String>,
#[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")]
pub start_time: Option<String>,
#[serde(rename = "endTime", default, skip_serializing_if = "Option::is_none")]
pub end_time: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub exception: Option<String>,
#[serde(rename = "lastModifiedTime", default, skip_serializing_if = "Option::is_none")]
pub last_modified_time: Option<String>,
#[serde(rename = "lastStatusModifiedTime", default, skip_serializing_if = "Option::is_none")]
pub last_status_modified_time: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parameters: Option<serde_json::Value>,
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<JobProvisioningStateProperty>,
}
pub mod job_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Status {
New,
Activating,
Running,
Completed,
Failed,
Stopped,
Blocked,
Suspended,
Disconnected,
Suspending,
Stopping,
Resuming,
Removing,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RunbookAssociationProperty {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct JobCreateParameters {
pub properties: JobCreateProperties,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct JobCollectionItemProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub runbook: Option<RunbookAssociationProperty>,
#[serde(rename = "jobId", default, skip_serializing_if = "Option::is_none")]
pub job_id: Option<String>,
#[serde(rename = "creationTime", default, skip_serializing_if = "Option::is_none")]
pub creation_time: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<job_collection_item_properties::Status>,
#[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")]
pub start_time: Option<String>,
#[serde(rename = "endTime", default, skip_serializing_if = "Option::is_none")]
pub end_time: Option<String>,
#[serde(rename = "lastModifiedTime", default, skip_serializing_if = "Option::is_none")]
pub last_modified_time: Option<String>,
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<String>,
#[serde(rename = "runOn", default, skip_serializing_if = "Option::is_none")]
pub run_on: Option<String>,
}
pub mod job_collection_item_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Status {
New,
Activating,
Running,
Completed,
Failed,
Stopped,
Blocked,
Suspended,
Disconnected,
Suspending,
Stopping,
Resuming,
Removing,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct JobCreateProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub runbook: Option<RunbookAssociationProperty>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parameters: Option<serde_json::Value>,
#[serde(rename = "runOn", default, skip_serializing_if = "Option::is_none")]
pub run_on: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AutomationAccount {
#[serde(flatten)]
pub tracked_resource: TrackedResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<AutomationAccountProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub etag: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AutomationAccountProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sku: Option<Sku>,
#[serde(rename = "lastModifiedBy", default, skip_serializing_if = "Option::is_none")]
pub last_modified_by: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub state: Option<automation_account_properties::State>,
#[serde(rename = "creationTime", default, skip_serializing_if = "Option::is_none")]
pub creation_time: Option<String>,
#[serde(rename = "lastModifiedTime", default, skip_serializing_if = "Option::is_none")]
pub last_modified_time: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
pub mod automation_account_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum State {
Ok,
Unavailable,
Suspended,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Sku {
pub name: sku::Name,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub family: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub capacity: Option<i32>,
}
pub mod sku {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Name {
Free,
Basic,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AutomationAccountCreateOrUpdateParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<AutomationAccountCreateOrUpdateProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub location: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AutomationAccountCreateOrUpdateProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sku: Option<Sku>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AutomationAccountListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<AutomationAccount>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Statistics {
#[serde(rename = "counterProperty", default, skip_serializing_if = "Option::is_none")]
pub counter_property: Option<String>,
#[serde(rename = "counterValue", default, skip_serializing_if = "Option::is_none")]
pub counter_value: Option<i64>,
#[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")]
pub start_time: Option<String>,
#[serde(rename = "endTime", default, skip_serializing_if = "Option::is_none")]
pub end_time: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StatisticsListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Statistics>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Usage {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<UsageCounterName>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub unit: Option<String>,
#[serde(rename = "currentValue", default, skip_serializing_if = "Option::is_none")]
pub current_value: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub limit: Option<i64>,
#[serde(rename = "throttleStatus", default, skip_serializing_if = "Option::is_none")]
pub throttle_status: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UsageCounterName {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
#[serde(rename = "localizedValue", default, skip_serializing_if = "Option::is_none")]
pub localized_value: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UsageListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Usage>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Key {
#[serde(rename = "KeyName", default, skip_serializing_if = "Option::is_none")]
pub key_name: Option<key::KeyName>,
#[serde(rename = "Permissions", default, skip_serializing_if = "Option::is_none")]
pub permissions: Option<key::Permissions>,
#[serde(rename = "Value", default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
}
pub mod key {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum KeyName {
Primary,
Secondary,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Permissions {
Read,
Full,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct KeyListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub keys: Vec<Key>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AutomationAccountUpdateProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sku: Option<Sku>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AutomationAccountUpdateParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<AutomationAccountUpdateProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub location: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CertificateCreateOrUpdateProperties {
#[serde(rename = "base64Value")]
pub base64_value: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub thumbprint: Option<String>,
#[serde(rename = "isExportable", default, skip_serializing_if = "Option::is_none")]
pub is_exportable: Option<bool>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CertificateCreateOrUpdateParameters {
pub name: String,
pub properties: CertificateCreateOrUpdateProperties,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CertificateProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub thumbprint: Option<String>,
#[serde(rename = "expiryTime", default, skip_serializing_if = "Option::is_none")]
pub expiry_time: Option<String>,
#[serde(rename = "isExportable", default, skip_serializing_if = "Option::is_none")]
pub is_exportable: Option<bool>,
#[serde(rename = "creationTime", default, skip_serializing_if = "Option::is_none")]
pub creation_time: Option<String>,
#[serde(rename = "lastModifiedTime", default, skip_serializing_if = "Option::is_none")]
pub last_modified_time: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Certificate {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<CertificateProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CertificateListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Certificate>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CertificateUpdateProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CertificateUpdateParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<CertificateUpdateProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ConnectionCreateOrUpdateProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(rename = "connectionType")]
pub connection_type: ConnectionTypeAssociationProperty,
#[serde(rename = "fieldDefinitionValues", default, skip_serializing_if = "Option::is_none")]
pub field_definition_values: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ConnectionCreateOrUpdateParameters {
pub name: String,
pub properties: ConnectionCreateOrUpdateProperties,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ConnectionProperties {
#[serde(rename = "connectionType", default, skip_serializing_if = "Option::is_none")]
pub connection_type: Option<ConnectionTypeAssociationProperty>,
#[serde(rename = "fieldDefinitionValues", default, skip_serializing_if = "Option::is_none")]
pub field_definition_values: Option<serde_json::Value>,
#[serde(rename = "creationTime", default, skip_serializing_if = "Option::is_none")]
pub creation_time: Option<String>,
#[serde(rename = "lastModifiedTime", default, skip_serializing_if = "Option::is_none")]
pub last_modified_time: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Connection {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<ConnectionProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ConnectionListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Connection>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ConnectionUpdateProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(rename = "fieldDefinitionValues", default, skip_serializing_if = "Option::is_none")]
pub field_definition_values: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ConnectionUpdateParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<ConnectionUpdateProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ConnectionTypeAssociationProperty {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FieldDefinition {
#[serde(rename = "isEncrypted", default, skip_serializing_if = "Option::is_none")]
pub is_encrypted: Option<bool>,
#[serde(rename = "isOptional", default, skip_serializing_if = "Option::is_none")]
pub is_optional: Option<bool>,
#[serde(rename = "type")]
pub type_: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ConnectionTypeProperties {
#[serde(rename = "isGlobal", default, skip_serializing_if = "Option::is_none")]
pub is_global: Option<bool>,
#[serde(rename = "fieldDefinitions", default, skip_serializing_if = "Option::is_none")]
pub field_definitions: Option<serde_json::Value>,
#[serde(rename = "creationTime", default, skip_serializing_if = "Option::is_none")]
pub creation_time: Option<String>,
#[serde(rename = "lastModifiedTime", default, skip_serializing_if = "Option::is_none")]
pub last_modified_time: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ConnectionType {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<ConnectionTypeProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ConnectionTypeListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<ConnectionType>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ConnectionTypeCreateOrUpdateParameters {
pub name: String,
pub properties: ConnectionTypeCreateOrUpdateProperties,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ConnectionTypeCreateOrUpdateProperties {
#[serde(rename = "isGlobal", default, skip_serializing_if = "Option::is_none")]
pub is_global: Option<bool>,
#[serde(rename = "fieldDefinitions")]
pub field_definitions: serde_json::Value,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CredentialCreateOrUpdateProperties {
#[serde(rename = "userName")]
pub user_name: String,
pub password: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CredentialCreateOrUpdateParameters {
pub name: String,
pub properties: CredentialCreateOrUpdateProperties,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CredentialProperties {
#[serde(rename = "userName", default, skip_serializing_if = "Option::is_none")]
pub user_name: Option<String>,
#[serde(rename = "creationTime", default, skip_serializing_if = "Option::is_none")]
pub creation_time: Option<String>,
#[serde(rename = "lastModifiedTime", default, skip_serializing_if = "Option::is_none")]
pub last_modified_time: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Credential {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<CredentialProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CredentialListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Credential>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CredentialUpdateProperties {
#[serde(rename = "userName", default, skip_serializing_if = "Option::is_none")]
pub user_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub password: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CredentialUpdateParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<CredentialUpdateProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DscConfigurationCreateOrUpdateParameters {
pub properties: DscConfigurationCreateOrUpdateProperties,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub location: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DscConfigurationListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<DscConfiguration>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
#[serde(rename = "totalCount", default, skip_serializing_if = "Option::is_none")]
pub total_count: Option<i64>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DscConfigurationCreateOrUpdateProperties {
#[serde(rename = "logVerbose", default, skip_serializing_if = "Option::is_none")]
pub log_verbose: Option<bool>,
#[serde(rename = "logProgress", default, skip_serializing_if = "Option::is_none")]
pub log_progress: Option<bool>,
pub source: ContentSource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parameters: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DscConfigurationParameter {
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(rename = "isMandatory", default, skip_serializing_if = "Option::is_none")]
pub is_mandatory: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub position: Option<i32>,
#[serde(rename = "defaultValue", default, skip_serializing_if = "Option::is_none")]
pub default_value: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DscConfigurationUpdateParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<DscConfigurationCreateOrUpdateProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DscConfigurationProperties {
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<dsc_configuration_properties::ProvisioningState>,
#[serde(rename = "jobCount", default, skip_serializing_if = "Option::is_none")]
pub job_count: Option<i32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parameters: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub source: Option<ContentSource>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub state: Option<dsc_configuration_properties::State>,
#[serde(rename = "logVerbose", default, skip_serializing_if = "Option::is_none")]
pub log_verbose: Option<bool>,
#[serde(rename = "creationTime", default, skip_serializing_if = "Option::is_none")]
pub creation_time: Option<String>,
#[serde(rename = "lastModifiedTime", default, skip_serializing_if = "Option::is_none")]
pub last_modified_time: Option<String>,
#[serde(rename = "nodeConfigurationCount", default, skip_serializing_if = "Option::is_none")]
pub node_configuration_count: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
pub mod dsc_configuration_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ProvisioningState {
Succeeded,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum State {
New,
Edit,
Published,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DscConfiguration {
#[serde(flatten)]
pub tracked_resource: TrackedResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<DscConfigurationProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub etag: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SoftwareUpdateConfiguration {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
pub properties: SoftwareUpdateConfigurationProperties,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SoftwareUpdateConfigurationProperties {
#[serde(rename = "updateConfiguration")]
pub update_configuration: UpdateConfiguration,
#[serde(rename = "scheduleInfo")]
pub schedule_info: SucScheduleProperties,
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<ErrorResponse>,
#[serde(rename = "creationTime", default, skip_serializing_if = "Option::is_none")]
pub creation_time: Option<String>,
#[serde(rename = "createdBy", default, skip_serializing_if = "Option::is_none")]
pub created_by: Option<String>,
#[serde(rename = "lastModifiedTime", default, skip_serializing_if = "Option::is_none")]
pub last_modified_time: Option<String>,
#[serde(rename = "lastModifiedBy", default, skip_serializing_if = "Option::is_none")]
pub last_modified_by: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tasks: Option<SoftwareUpdateConfigurationTasks>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SoftwareUpdateConfigurationTasks {
#[serde(rename = "preTask", default, skip_serializing_if = "Option::is_none")]
pub pre_task: Option<TaskProperties>,
#[serde(rename = "postTask", default, skip_serializing_if = "Option::is_none")]
pub post_task: Option<TaskProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TaskProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parameters: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub source: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WindowsProperties {
#[serde(rename = "includedUpdateClassifications", default, skip_serializing_if = "Option::is_none")]
pub included_update_classifications: Option<windows_properties::IncludedUpdateClassifications>,
#[serde(rename = "excludedKbNumbers", default, skip_serializing_if = "Vec::is_empty")]
pub excluded_kb_numbers: Vec<String>,
#[serde(rename = "includedKbNumbers", default, skip_serializing_if = "Vec::is_empty")]
pub included_kb_numbers: Vec<String>,
#[serde(rename = "rebootSetting", default, skip_serializing_if = "Option::is_none")]
pub reboot_setting: Option<String>,
}
pub mod windows_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum IncludedUpdateClassifications {
Unclassified,
Critical,
Security,
UpdateRollup,
FeaturePack,
ServicePack,
Definition,
Tools,
Updates,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum OperatingSystemType {
Windows,
Linux,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UpdateConfiguration {
#[serde(rename = "operatingSystem")]
pub operating_system: OperatingSystemType,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub windows: Option<WindowsProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub linux: Option<LinuxProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub duration: Option<String>,
#[serde(rename = "azureVirtualMachines", default, skip_serializing_if = "Vec::is_empty")]
pub azure_virtual_machines: Vec<String>,
#[serde(rename = "nonAzureComputerNames", default, skip_serializing_if = "Vec::is_empty")]
pub non_azure_computer_names: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub targets: Option<TargetProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LinuxProperties {
#[serde(rename = "includedPackageClassifications", default, skip_serializing_if = "Option::is_none")]
pub included_package_classifications: Option<linux_properties::IncludedPackageClassifications>,
#[serde(rename = "excludedPackageNameMasks", default, skip_serializing_if = "Vec::is_empty")]
pub excluded_package_name_masks: Vec<String>,
#[serde(rename = "includedPackageNameMasks", default, skip_serializing_if = "Vec::is_empty")]
pub included_package_name_masks: Vec<String>,
#[serde(rename = "rebootSetting", default, skip_serializing_if = "Option::is_none")]
pub reboot_setting: Option<String>,
}
pub mod linux_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum IncludedPackageClassifications {
Unclassified,
Critical,
Security,
Other,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SucScheduleProperties {
#[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")]
pub start_time: Option<String>,
#[serde(rename = "startTimeOffsetMinutes", default, skip_serializing_if = "Option::is_none")]
pub start_time_offset_minutes: Option<f64>,
#[serde(rename = "expiryTime", default, skip_serializing_if = "Option::is_none")]
pub expiry_time: Option<String>,
#[serde(rename = "expiryTimeOffsetMinutes", default, skip_serializing_if = "Option::is_none")]
pub expiry_time_offset_minutes: Option<f64>,
#[serde(rename = "isEnabled", default, skip_serializing_if = "Option::is_none")]
pub is_enabled: Option<bool>,
#[serde(rename = "nextRun", default, skip_serializing_if = "Option::is_none")]
pub next_run: Option<String>,
#[serde(rename = "nextRunOffsetMinutes", default, skip_serializing_if = "Option::is_none")]
pub next_run_offset_minutes: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub interval: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub frequency: Option<ScheduleFrequency>,
#[serde(rename = "timeZone", default, skip_serializing_if = "Option::is_none")]
pub time_zone: Option<String>,
#[serde(rename = "advancedSchedule", default, skip_serializing_if = "Option::is_none")]
pub advanced_schedule: Option<AdvancedSchedule>,
#[serde(rename = "creationTime", default, skip_serializing_if = "Option::is_none")]
pub creation_time: Option<String>,
#[serde(rename = "lastModifiedTime", default, skip_serializing_if = "Option::is_none")]
pub last_modified_time: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AdvancedSchedule {
#[serde(rename = "weekDays", default, skip_serializing_if = "Vec::is_empty")]
pub week_days: Vec<String>,
#[serde(rename = "monthDays", default, skip_serializing_if = "Vec::is_empty")]
pub month_days: Vec<i32>,
#[serde(rename = "monthlyOccurrences", default, skip_serializing_if = "Vec::is_empty")]
pub monthly_occurrences: Vec<AdvancedScheduleMonthlyOccurrence>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AdvancedScheduleMonthlyOccurrence {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub occurrence: Option<i32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub day: Option<advanced_schedule_monthly_occurrence::Day>,
}
pub mod advanced_schedule_monthly_occurrence {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Day {
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SoftwareUpdateConfigurationListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<SoftwareUpdateConfigurationCollectionItem>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SoftwareUpdateConfigurationCollectionItem {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
pub properties: SoftwareUpdateConfigurationCollectionItemProperties,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SoftwareUpdateConfigurationCollectionItemProperties {
#[serde(rename = "updateConfiguration", default, skip_serializing_if = "Option::is_none")]
pub update_configuration: Option<UpdateConfiguration>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tasks: Option<SoftwareUpdateConfigurationTasks>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub frequency: Option<ScheduleFrequency>,
#[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")]
pub start_time: Option<String>,
#[serde(rename = "creationTime", default, skip_serializing_if = "Option::is_none")]
pub creation_time: Option<String>,
#[serde(rename = "lastModifiedTime", default, skip_serializing_if = "Option::is_none")]
pub last_modified_time: Option<String>,
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<String>,
#[serde(rename = "nextRun", default, skip_serializing_if = "Option::is_none")]
pub next_run: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TargetProperties {
#[serde(rename = "azureQueries", default, skip_serializing_if = "Vec::is_empty")]
pub azure_queries: Vec<AzureQueryProperties>,
#[serde(rename = "nonAzureQueries", default, skip_serializing_if = "Vec::is_empty")]
pub non_azure_queries: Vec<NonAzureQueryProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct NonAzureQueryProperties {
#[serde(rename = "functionAlias", default, skip_serializing_if = "Option::is_none")]
pub function_alias: Option<String>,
#[serde(rename = "workspaceId", default, skip_serializing_if = "Option::is_none")]
pub workspace_id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AzureQueryProperties {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub scope: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub locations: Vec<String>,
#[serde(rename = "tagSettings", default, skip_serializing_if = "Option::is_none")]
pub tag_settings: Option<TagSettingsProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TagSettingsProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
#[serde(rename = "filterOperator", default, skip_serializing_if = "Option::is_none")]
pub filter_operator: Option<tag_settings_properties::FilterOperator>,
}
pub mod tag_settings_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum FilterOperator {
All,
Any,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RunAsCredentialAssociationProperty {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct HybridRunbookWorker {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ip: Option<String>,
#[serde(rename = "registrationTime", default, skip_serializing_if = "Option::is_none")]
pub registration_time: Option<String>,
#[serde(rename = "lastSeenDateTime", default, skip_serializing_if = "Option::is_none")]
pub last_seen_date_time: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct HybridRunbookWorkerGroup {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "hybridRunbookWorkers", default, skip_serializing_if = "Vec::is_empty")]
pub hybrid_runbook_workers: Vec<HybridRunbookWorker>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub credential: Option<RunAsCredentialAssociationProperty>,
#[serde(rename = "groupType", default, skip_serializing_if = "Option::is_none")]
pub group_type: Option<hybrid_runbook_worker_group::GroupType>,
}
pub mod hybrid_runbook_worker_group {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum GroupType {
User,
System,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct HybridRunbookWorkerGroupsListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<HybridRunbookWorkerGroup>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct HybridRunbookWorkerGroupUpdateParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub credential: Option<RunAsCredentialAssociationProperty>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct JobScheduleListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<JobSchedule>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct JobSchedule {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<JobScheduleProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ScheduleAssociationProperty {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct JobScheduleProperties {
#[serde(rename = "jobScheduleId", default, skip_serializing_if = "Option::is_none")]
pub job_schedule_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub schedule: Option<ScheduleAssociationProperty>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub runbook: Option<RunbookAssociationProperty>,
#[serde(rename = "runOn", default, skip_serializing_if = "Option::is_none")]
pub run_on: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parameters: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct JobScheduleCreateProperties {
pub schedule: ScheduleAssociationProperty,
pub runbook: RunbookAssociationProperty,
#[serde(rename = "runOn", default, skip_serializing_if = "Option::is_none")]
pub run_on: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parameters: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct JobScheduleCreateParameters {
pub properties: JobScheduleCreateProperties,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LinkedWorkspace {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ModuleCreateOrUpdateProperties {
#[serde(rename = "contentLink")]
pub content_link: ContentLink,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ModuleCreateOrUpdateParameters {
pub properties: ModuleCreateOrUpdateProperties,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub location: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ModuleUpdateProperties {
#[serde(rename = "contentLink", default, skip_serializing_if = "Option::is_none")]
pub content_link: Option<ContentLink>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ModuleUpdateParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<ModuleUpdateProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub location: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OperationListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Operation>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Operation {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display: Option<operation::Display>,
}
pub mod operation {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Display {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub provider: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resource: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub operation: Option<String>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ScheduleCreateOrUpdateProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(rename = "startTime")]
pub start_time: String,
#[serde(rename = "expiryTime", default, skip_serializing_if = "Option::is_none")]
pub expiry_time: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub interval: Option<serde_json::Value>,
pub frequency: ScheduleFrequency,
#[serde(rename = "timeZone", default, skip_serializing_if = "Option::is_none")]
pub time_zone: Option<String>,
#[serde(rename = "advancedSchedule", default, skip_serializing_if = "Option::is_none")]
pub advanced_schedule: Option<AdvancedSchedule>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ScheduleFrequency {
OneTime,
Day,
Hour,
Week,
Month,
Minute,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ScheduleCreateOrUpdateParameters {
pub name: String,
pub properties: ScheduleCreateOrUpdateProperties,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Schedule {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<ScheduleProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ScheduleProperties {
#[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")]
pub start_time: Option<String>,
#[serde(rename = "startTimeOffsetMinutes", default, skip_serializing_if = "Option::is_none")]
pub start_time_offset_minutes: Option<f64>,
#[serde(rename = "expiryTime", default, skip_serializing_if = "Option::is_none")]
pub expiry_time: Option<String>,
#[serde(rename = "expiryTimeOffsetMinutes", default, skip_serializing_if = "Option::is_none")]
pub expiry_time_offset_minutes: Option<f64>,
#[serde(rename = "isEnabled", default, skip_serializing_if = "Option::is_none")]
pub is_enabled: Option<bool>,
#[serde(rename = "nextRun", default, skip_serializing_if = "Option::is_none")]
pub next_run: Option<String>,
#[serde(rename = "nextRunOffsetMinutes", default, skip_serializing_if = "Option::is_none")]
pub next_run_offset_minutes: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub interval: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub frequency: Option<ScheduleFrequency>,
#[serde(rename = "timeZone", default, skip_serializing_if = "Option::is_none")]
pub time_zone: Option<String>,
#[serde(rename = "advancedSchedule", default, skip_serializing_if = "Option::is_none")]
pub advanced_schedule: Option<AdvancedSchedule>,
#[serde(rename = "creationTime", default, skip_serializing_if = "Option::is_none")]
pub creation_time: Option<String>,
#[serde(rename = "lastModifiedTime", default, skip_serializing_if = "Option::is_none")]
pub last_modified_time: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ScheduleUpdateProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(rename = "isEnabled", default, skip_serializing_if = "Option::is_none")]
pub is_enabled: Option<bool>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ScheduleUpdateParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<ScheduleUpdateProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ScheduleListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Schedule>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VariableCreateOrUpdateParameters {
pub name: String,
pub properties: VariableCreateOrUpdateProperties,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VariableCreateOrUpdateProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(rename = "isEncrypted", default, skip_serializing_if = "Option::is_none")]
pub is_encrypted: Option<bool>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Variable {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<VariableProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VariableListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Variable>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VariableUpdateParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<VariableUpdateProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VariableUpdateProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VariableProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
#[serde(rename = "isEncrypted", default, skip_serializing_if = "Option::is_none")]
pub is_encrypted: Option<bool>,
#[serde(rename = "creationTime", default, skip_serializing_if = "Option::is_none")]
pub creation_time: Option<String>,
#[serde(rename = "lastModifiedTime", default, skip_serializing_if = "Option::is_none")]
pub last_modified_time: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Watcher {
#[serde(flatten)]
pub resource: Resource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<WatcherProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub etag: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub location: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WatcherProperties {
#[serde(rename = "executionFrequencyInSeconds", default, skip_serializing_if = "Option::is_none")]
pub execution_frequency_in_seconds: Option<i64>,
#[serde(rename = "scriptName", default, skip_serializing_if = "Option::is_none")]
pub script_name: Option<String>,
#[serde(rename = "scriptParameters", default, skip_serializing_if = "Option::is_none")]
pub script_parameters: Option<serde_json::Value>,
#[serde(rename = "scriptRunOn", default, skip_serializing_if = "Option::is_none")]
pub script_run_on: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<String>,
#[serde(rename = "creationTime", default, skip_serializing_if = "Option::is_none")]
pub creation_time: Option<String>,
#[serde(rename = "lastModifiedTime", default, skip_serializing_if = "Option::is_none")]
pub last_modified_time: Option<String>,
#[serde(rename = "lastModifiedBy", default, skip_serializing_if = "Option::is_none")]
pub last_modified_by: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WatcherUpdateParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<WatcherUpdateProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WatcherUpdateProperties {
#[serde(rename = "executionFrequencyInSeconds", default, skip_serializing_if = "Option::is_none")]
pub execution_frequency_in_seconds: Option<i64>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WatcherListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Watcher>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WebhookProperties {
#[serde(rename = "isEnabled", default, skip_serializing_if = "Option::is_none")]
pub is_enabled: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub uri: Option<String>,
#[serde(rename = "expiryTime", default, skip_serializing_if = "Option::is_none")]
pub expiry_time: Option<String>,
#[serde(rename = "lastInvokedTime", default, skip_serializing_if = "Option::is_none")]
pub last_invoked_time: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parameters: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub runbook: Option<RunbookAssociationProperty>,
#[serde(rename = "runOn", default, skip_serializing_if = "Option::is_none")]
pub run_on: Option<String>,
#[serde(rename = "creationTime", default, skip_serializing_if = "Option::is_none")]
pub creation_time: Option<String>,
#[serde(rename = "lastModifiedTime", default, skip_serializing_if = "Option::is_none")]
pub last_modified_time: Option<String>,
#[serde(rename = "lastModifiedBy", default, skip_serializing_if = "Option::is_none")]
pub last_modified_by: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Webhook {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<WebhookProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WebhookListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Webhook>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WebhookUpdateProperties {
#[serde(rename = "isEnabled", default, skip_serializing_if = "Option::is_none")]
pub is_enabled: Option<bool>,
#[serde(rename = "runOn", default, skip_serializing_if = "Option::is_none")]
pub run_on: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parameters: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WebhookUpdateParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<WebhookUpdateProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WebhookCreateOrUpdateParameters {
pub name: String,
pub properties: WebhookCreateOrUpdateProperties,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WebhookCreateOrUpdateProperties {
#[serde(rename = "isEnabled", default, skip_serializing_if = "Option::is_none")]
pub is_enabled: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub uri: Option<String>,
#[serde(rename = "expiryTime", default, skip_serializing_if = "Option::is_none")]
pub expiry_time: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parameters: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub runbook: Option<RunbookAssociationProperty>,
#[serde(rename = "runOn", default, skip_serializing_if = "Option::is_none")]
pub run_on: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorResponse {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TrackedResource {
#[serde(flatten)]
pub resource: Resource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub location: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Resource {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ProxyResource {
#[serde(flatten)]
pub resource: Resource,
}
|
use crate::errors::MetaphraseError;
use crate::models::*;
use actix_web::HttpRequest;
use time::OffsetDateTime;
pub fn current_user(req: &HttpRequest) -> Result<User, MetaphraseError> {
let extensions = req.extensions();
let current_session = extensions.get::<Session>().unwrap();
current_session.user()
}
pub fn now_str() -> String {
OffsetDateTime::now_utc().format("%F %T")
}
|
use std::fmt::Debug;
#[derive(Debug)]
struct Ref<'a, T: 'a>(&'a T);
// Ref contains a reference to a generic type T
// that has an unknown lifetime 'a.
// T is bounded such that any reference in T
// must outlibe 'a.
// Additionally the lifetime of Ref may not exceed 'a.
fn print<T>(t: T) where
T: Debug {
println!("`print`: t is {:?}", t);
}
// a reference to T is taken
// where T implements Debug and all references in T outlibe 'a.
// In addition 'a must outlive the function
fn print_ref<'a, T>(t: &'a T) where
T: Debug + 'a {
println!("`print_ref`: t is {:?}", t);
}
fn main() {
let x = 7;
let ref_x = Ref(&x);
print_ref(&ref_x);
print(ref_x);
}
|
#[doc = "Register `SYSCFG_ITLINE3` reader"]
pub type R = crate::R<SYSCFG_ITLINE3_SPEC>;
#[doc = "Field `FLASH_ITF` reader - Flash interface interrupt request pending"]
pub type FLASH_ITF_R = crate::BitReader;
impl R {
#[doc = "Bit 1 - Flash interface interrupt request pending"]
#[inline(always)]
pub fn flash_itf(&self) -> FLASH_ITF_R {
FLASH_ITF_R::new(((self.bits >> 1) & 1) != 0)
}
}
#[doc = "SYSCFG interrupt line 3 status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`syscfg_itline3::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct SYSCFG_ITLINE3_SPEC;
impl crate::RegisterSpec for SYSCFG_ITLINE3_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`syscfg_itline3::R`](R) reader structure"]
impl crate::Readable for SYSCFG_ITLINE3_SPEC {}
#[doc = "`reset()` method sets SYSCFG_ITLINE3 to value 0"]
impl crate::Resettable for SYSCFG_ITLINE3_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use std::collections::HashMap;
use std::collections::HashSet;
use crate::util;
pub fn solve() {
let input_file = "input-day-3.txt";
println!("Day 3 answers");
print!(" first puzzle: ");
let answer = solve_first_file(input_file);
println!("{}", answer);
print!(" second puzzle: ");
let answer = solve_second_file(input_file);
println!("{}", answer);
}
fn solve_first_file(input: &str) -> i32 {
let v = util::aoc2018_row_file_to_vector(input);
solve_first(v)
}
fn solve_first(str_vector: Vec<String>) -> i32 {
let claims: Vec<Claim> = get_claims(str_vector);
let mut overclaimed_rects: Vec<Rect> = Vec::new();
let no_of_claims = claims.len();
for (current_pos, claim) in claims.iter().enumerate() {
// Skip last as we only compare to those after.
if current_pos == no_of_claims - 1 {
break;
}
let sub_vector = &claims[(current_pos + 1)..];
// println!("XXX: sub_vector_size: {} ", sub_vector.len());
let claim_rec = claim.get_rect();
// println!(
// "XXXXXXXXXX: claim_rec rect: {},{} {},{}",
// claim_rec.x, claim_rec.y, claim_rec.x2, claim_rec.y2
// );
for (_cmp_pos, cmp_claim) in sub_vector.iter().enumerate() {
// println!("XXX: cmp pos_ : {} ", _cmp_pos);
let cmp_claim_rec = cmp_claim.get_rect();
// println!(
// "XXXXXXXXXXX: cmp_claim_rec: {},{} {},{}",
// cmp_claim_rec.x, cmp_claim_rec.y, cmp_claim_rec.x2, cmp_claim_rec.y2
// );
if let Some(rect) = claim_rec.get_intersect_rect(&cmp_claim_rec) {
// println!(
// "XXXXXXXXXXXX: cmp_claim_rec: {},{} {},{}",
// rect.x, rect.y, rect.x2, rect.y2
// );
overclaimed_rects.push(rect);
}
}
}
type YSet = HashSet<i32>;
// Ok, don't care for a full sweep implementation, see just add to a matrix and count...
// Might be slooow for larger inputs. Might give time for reflection and contemplation
let mut overclaimed_square_inches: HashMap<i32, YSet> = HashMap::new();
let mut new_insert: i32 = 0;
for rect in overclaimed_rects {
// println!(
// "XXXXXXXXXX: oc rect: {},{} {},{}",
// rect.x, rect.y, rect.x2, rect.y2
// );
for x in rect.x..=rect.x2 {
overclaimed_square_inches.entry(x).or_insert_with(YSet::new);
let y_map_res: Option<&mut YSet> = overclaimed_square_inches.get_mut(&x);
let y_map = y_map_res.unwrap();
// println!("XXXXXXXXXX: check y {} rect.y..rect.y2 {}", rect.y, rect.y2 );
for y in rect.y..=rect.y2 {
// println!("XXXXXXXXXX: fo loop y {} ", y );
if y_map.insert(y) {
new_insert += 1;
}
}
}
}
new_insert
}
fn solve_second_file(input: &str) -> String {
let v = util::aoc2018_row_file_to_vector(input);
solve_second(v)
}
// Ok, only one was expected, coded to find first. Brute fore and use the cpu. Love the heat.
fn solve_second(str_vector: Vec<String>) -> String {
let claims: Vec<Claim> = get_claims(str_vector);
for (current_pos, claim) in claims.iter().enumerate() {
// Skip last as we only compare to those after.
let claim_rec = claim.get_rect();
let mut found_overlap: bool = false;
for (_cmp_pos, cmp_claim) in claims.iter().enumerate() {
let cmp_claim_rec = cmp_claim.get_rect();
if current_pos != _cmp_pos && claim_rec.get_intersect_rect(&cmp_claim_rec).is_some() {
found_overlap = true;
break;
}
}
if !found_overlap {
return claim.id.to_string();
}
}
"Fail".to_string()
}
fn get_claims(str_vector: Vec<String>) -> Vec<Claim> {
let mut claims: Vec<Claim> = Vec::new();
for line in str_vector {
let v: Vec<&str> = line
.split(|c| c == '#' || c == '@' || c == ',' || c == ':' || c == 'x')
.filter(|k| !k.is_empty())
.collect();
// &['#', '@', ',', ':', 'x'] let tokens: Vec<_> = line.split(&['#', '@', ',', ':', 'x']).).collect();
let claim = Claim {
id: String::from(v[0].trim()),
offset_x: v[1].trim().parse().unwrap(),
offset_y: v[2].trim().parse().unwrap(),
width: v[3].trim().parse().unwrap(),
height: v[4].trim().parse().unwrap(),
};
claims.push(claim);
}
claims
}
struct Claim {
#[allow(dead_code)]
id: String,
offset_x: i32,
offset_y: i32,
width: i32,
height: i32,
}
struct Rect {
x: i32,
y: i32,
x2: i32,
y2: i32,
}
impl Claim {
pub fn get_rect(self: &Self) -> Rect {
Rect {
x: self.offset_x,
y: self.offset_y,
x2: self.offset_x + self.width - 1,
y2: self.offset_y + self.height - 1,
}
}
}
impl Rect {
// note, requires normalized rects
pub fn get_intersect_rect(self: &Self, r2: &Rect) -> Option<Rect> {
let irect = Rect {
x: self.x.max(r2.x),
y: self.y.max(r2.y),
x2: self.x2.min(r2.x2),
y2: self.y2.min(r2.y2),
};
// println!(
// "XXXXXXXXXXX: test int: {},{} {},{}",
// irect.x, irect.y, irect.x2, irect.y2
// );
if irect.x > irect.x2 || irect.y > irect.y2 {
// println!(
// "XXXXXXXXXXX: NONE test irect.x > irect.x2 || irect.y > irect.y2 {} {}",
// irect.x > irect.x2,
// irect.y > irect.y2
// );
None
} else {
Some(irect)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_cases_first() {
// provided examples
let answer = solve_first_file("test-day-3.txt");
assert_eq!(answer, 4);
// my test
let answer = solve_first_file("test-day-3-2.txt");
assert_eq!(answer, 1);
}
#[test]
fn test_day_3_second() {
// provided examples
let answer = solve_second_file("test-day-3.txt");
assert_eq!(answer, "3");
// my test
let answer = solve_second_file("test-day-3-2.txt");
assert_eq!(answer, "Fail");
}
}
|
use crate::problem_datatypes::Solution;
use crate::problem_datatypes::DataPoints;
use crate::problem_datatypes::Constraints;
use crate::fitness_evolution::FitnessEvolution;
use crate::arg_parser::ProgramParameters;
use crate::utils;
use crate::arg_parser::SearchType;
use crate::algorithms::local_search;
use crate::algorithms::simulated_annealing;
use rand::rngs::StdRng;
use std::time::Instant;
/// Ejecuta y muestra los resultados de la busqueda
/// Esto para no incluir todo este codigo en el cuerpo de la funcion main
/// basic indica si usamos busqueda local (true) o enfriamiento simulado (false) entre repeticiones
pub fn run_and_show_results(data_points: &DataPoints, constraints: &Constraints, program_arguments: ProgramParameters, basic: bool, rng: &mut StdRng){
// Numero maximo de iteraciones para la busqueda local y numero de repeticiones
// Es menos que en otros algoritmos, porque estamos usando repeticiones
let max_fitness_evaluations = 10000;
let number_of_repetitions = 10;
// Tamaรฑo del segmento de mutacion fuerte que consideramos
let mutation_segment_size: usize = (0.1 * data_points.len() as f32) as usize;
// Comprobacion de seguridad
debug_assert!(
max_fitness_evaluations * number_of_repetitions == 100000,
"No estamos usando el numero adecuado de evaluaciones del fitness o lanzamientos de local search"
);
let before = Instant::now();
let (solucion_local, fitness_evolution) = run(&data_points, &constraints, program_arguments.get_number_of_clusters(), max_fitness_evaluations, number_of_repetitions, basic, mutation_segment_size, rng);
let after = Instant::now();
let duration = after.duration_since(before);
let duration_numeric = duration.as_secs() as f64 + duration.subsec_nanos() as f64 * 1e-9;
// Mostramos los resultados
println!("==> Busqueda local iterativa, basic: {}", basic);
println!("La distancia global instracluster de la solucion es: {}", solucion_local.global_cluster_mean_distance());
println!("El numero de restricciones violadas es: {}", solucion_local.infeasibility());
println!("El valor de fitness es: {}", solucion_local.fitness());
println!("El valor de lambda es: {}", solucion_local.get_lambda());
println!("Tiempo transcurrido (segundos): {}", duration_numeric);
println!("Salvado del fitness: {:?}", fitness_evolution.save_as_numpy_file(&utils::generate_file_name(SearchType::LocalSearch)));
println!("");
}
/// Lanzamos la busqueda iterativa
fn run<'a, 'b>(data_points: &'a DataPoints, constraints: &'b Constraints, number_of_clusters: i32, max_fitness_evaluations: i32, number_of_repetitions: i32, basic: bool, mutation_segment_size: usize, rng: &mut StdRng) -> (Solution<'a, 'b>, FitnessEvolution){
// Llevamos la cuenta de la evolucion del fintess
let mut fitness_evolution = FitnessEvolution::new();
// Generamos una solucion inicial aleatoria
// Current solution sera la mejor solucion hasta el momento
let mut current_solution = Solution::generate_random_solution(data_points, constraints, number_of_clusters, rng);
fitness_evolution.add_iteration(current_solution.fitness()); // Por ser solo una evaluacion no tenemos en
// cuenta esto en el maximo de evaluaciones
// Realizamos las repeticiones dadas
for _ in 0..number_of_repetitions{
// Mutamos fuertemente la mejor solucion encontrada hasta el momento
// Notar que esta mejor solucion no se modifica en el .hard_mutated
let mut new_solution = current_solution.hard_mutated(mutation_segment_size, rng);
// Aplicamos busqueda local o enfriamiento simulado a esta solucion mutada fuertemente
if basic == true{
let (local_solution, _) = local_search::run_from_init_sol(max_fitness_evaluations, &new_solution, rng);
new_solution = local_solution;
}else{
// Establecemos los parametros para aplicar enfriamiento simulado
let mu = 0.3;
let final_tmp = 0.001;
let max_neighbours: i32 = (10.0 * data_points.len() as f64) as i32;
let max_successes: i32 = (0.1 * max_neighbours as f64) as i32;
let M: f64 = max_fitness_evaluations as f64 / max_neighbours as f64;
let initial_tmp: f64 = (mu * current_solution.fitness()) / (-mu.ln());
// Aplicamos enfriamiento simulado
let (annealing_solution, _) = simulated_annealing::run(
max_fitness_evaluations,
¤t_solution,
initial_tmp,
final_tmp,
M,
max_neighbours,
max_successes,
rng
);
new_solution = annealing_solution;
}
// Comprobamos si esta solucion es mejor que la que ya teniamos
if new_solution.fitness() < current_solution.fitness(){
current_solution = new_solution;
}
}
return (current_solution, fitness_evolution);
}
|
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CertificateAttributes {
#[serde(flatten)]
pub attributes: Attributes,
#[serde(rename = "recoverableDays", default, skip_serializing_if = "Option::is_none")]
pub recoverable_days: Option<i32>,
#[serde(rename = "recoveryLevel", default, skip_serializing_if = "Option::is_none")]
pub recovery_level: Option<certificate_attributes::RecoveryLevel>,
}
pub mod certificate_attributes {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum RecoveryLevel {
Purgeable,
#[serde(rename = "Recoverable+Purgeable")]
RecoverablePurgeable,
Recoverable,
#[serde(rename = "Recoverable+ProtectedSubscription")]
RecoverableProtectedSubscription,
#[serde(rename = "CustomizedRecoverable+Purgeable")]
CustomizedRecoverablePurgeable,
CustomizedRecoverable,
#[serde(rename = "CustomizedRecoverable+ProtectedSubscription")]
CustomizedRecoverableProtectedSubscription,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CertificateItem {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attributes: Option<CertificateAttributes>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub x5t: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CertificateIssuerItem {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub provider: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CertificateBundle {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kid: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sid: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub x5t: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub policy: Option<CertificatePolicy>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cer: Option<String>,
#[serde(rename = "contentType", default, skip_serializing_if = "Option::is_none")]
pub content_type: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attributes: Option<CertificateAttributes>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DeletedCertificateBundle {
#[serde(flatten)]
pub certificate_bundle: CertificateBundle,
#[serde(rename = "recoveryId", default, skip_serializing_if = "Option::is_none")]
pub recovery_id: Option<String>,
#[serde(rename = "scheduledPurgeDate", default, skip_serializing_if = "Option::is_none")]
pub scheduled_purge_date: Option<i64>,
#[serde(rename = "deletedDate", default, skip_serializing_if = "Option::is_none")]
pub deleted_date: Option<i64>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DeletedCertificateItem {
#[serde(flatten)]
pub certificate_item: CertificateItem,
#[serde(rename = "recoveryId", default, skip_serializing_if = "Option::is_none")]
pub recovery_id: Option<String>,
#[serde(rename = "scheduledPurgeDate", default, skip_serializing_if = "Option::is_none")]
pub scheduled_purge_date: Option<i64>,
#[serde(rename = "deletedDate", default, skip_serializing_if = "Option::is_none")]
pub deleted_date: Option<i64>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CertificateOperation {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub issuer: Option<IssuerParameters>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub csr: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cancellation_requested: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status_details: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<Error>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub request_id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CertificatePolicy {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub key_props: Option<KeyProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub secret_props: Option<SecretProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub x509_props: Option<X509CertificateProperties>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub lifetime_actions: Vec<LifetimeAction>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub issuer: Option<IssuerParameters>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attributes: Option<CertificateAttributes>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct X509CertificateProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub subject: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub ekus: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sans: Option<SubjectAlternativeNames>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub key_usage: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub validity_months: Option<i32>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct IssuerParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cty: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cert_transparency: Option<bool>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LifetimeAction {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub trigger: Option<Trigger>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub action: Option<Action>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Action {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub action_type: Option<action::ActionType>,
}
pub mod action {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ActionType {
EmailContacts,
AutoRenew,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Trigger {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub lifetime_percentage: Option<i32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub days_before_expiry: Option<i32>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SubjectAlternativeNames {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub emails: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub dns_names: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub upns: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct IssuerBundle {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub provider: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub credentials: Option<IssuerCredentials>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub org_details: Option<OrganizationDetails>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attributes: Option<IssuerAttributes>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct IssuerAttributes {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub enabled: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub created: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub updated: Option<i64>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct IssuerCredentials {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub account_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pwd: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OrganizationDetails {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub admin_details: Vec<AdministratorDetails>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AdministratorDetails {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub first_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub email: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub phone: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Contacts {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub contacts: Vec<Contact>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Contact {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub email: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub phone: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CertificateCreateParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub policy: Option<CertificatePolicy>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attributes: Option<CertificateAttributes>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CertificateImportParameters {
pub value: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pwd: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub policy: Option<CertificatePolicy>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attributes: Option<CertificateAttributes>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CertificateUpdateParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub policy: Option<CertificatePolicy>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attributes: Option<CertificateAttributes>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CertificateMergeParameters {
pub x5c: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attributes: Option<CertificateAttributes>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CertificateIssuerSetParameters {
pub provider: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub credentials: Option<IssuerCredentials>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub org_details: Option<OrganizationDetails>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attributes: Option<IssuerAttributes>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CertificateIssuerUpdateParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub provider: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub credentials: Option<IssuerCredentials>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub org_details: Option<OrganizationDetails>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attributes: Option<IssuerAttributes>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CertificateOperationUpdateParameter {
pub cancellation_requested: bool,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CertificateListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<CertificateItem>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DeletedCertificateListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<DeletedCertificateItem>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CertificateIssuerListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<CertificateIssuerItem>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PendingCertificateSigningRequestResult {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CertificateRestoreParameters {
pub value: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BackupCertificateResult {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Attributes {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub enabled: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub nbf: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub exp: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub created: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub updated: Option<i64>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct KeyVaultError {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<Error>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Error {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub innererror: Box<Option<Error>>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct JsonWebKey {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kid: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kty: Option<json_web_key::Kty>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub key_ops: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub n: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub e: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub d: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub dp: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub dq: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub qi: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub p: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub q: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub k: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub key_hsm: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub crv: Option<json_web_key::Crv>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub x: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub y: Option<String>,
}
pub mod json_web_key {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Kty {
#[serde(rename = "EC")]
Ec,
#[serde(rename = "EC-HSM")]
EcHsm,
#[serde(rename = "RSA")]
Rsa,
#[serde(rename = "RSA-HSM")]
RsaHsm,
#[serde(rename = "oct")]
Oct,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Crv {
#[serde(rename = "P-256")]
P256,
#[serde(rename = "P-384")]
P384,
#[serde(rename = "P-521")]
P521,
#[serde(rename = "P-256K")]
P256k,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct KeyAttributes {
#[serde(flatten)]
pub attributes: Attributes,
#[serde(rename = "recoverableDays", default, skip_serializing_if = "Option::is_none")]
pub recoverable_days: Option<i32>,
#[serde(rename = "recoveryLevel", default, skip_serializing_if = "Option::is_none")]
pub recovery_level: Option<key_attributes::RecoveryLevel>,
}
pub mod key_attributes {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum RecoveryLevel {
Purgeable,
#[serde(rename = "Recoverable+Purgeable")]
RecoverablePurgeable,
Recoverable,
#[serde(rename = "Recoverable+ProtectedSubscription")]
RecoverableProtectedSubscription,
#[serde(rename = "CustomizedRecoverable+Purgeable")]
CustomizedRecoverablePurgeable,
CustomizedRecoverable,
#[serde(rename = "CustomizedRecoverable+ProtectedSubscription")]
CustomizedRecoverableProtectedSubscription,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct KeyBundle {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub key: Option<JsonWebKey>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attributes: Option<KeyAttributes>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub managed: Option<bool>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct KeyItem {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kid: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attributes: Option<KeyAttributes>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub managed: Option<bool>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DeletedKeyBundle {
#[serde(flatten)]
pub key_bundle: KeyBundle,
#[serde(rename = "recoveryId", default, skip_serializing_if = "Option::is_none")]
pub recovery_id: Option<String>,
#[serde(rename = "scheduledPurgeDate", default, skip_serializing_if = "Option::is_none")]
pub scheduled_purge_date: Option<i64>,
#[serde(rename = "deletedDate", default, skip_serializing_if = "Option::is_none")]
pub deleted_date: Option<i64>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DeletedKeyItem {
#[serde(flatten)]
pub key_item: KeyItem,
#[serde(rename = "recoveryId", default, skip_serializing_if = "Option::is_none")]
pub recovery_id: Option<String>,
#[serde(rename = "scheduledPurgeDate", default, skip_serializing_if = "Option::is_none")]
pub scheduled_purge_date: Option<i64>,
#[serde(rename = "deletedDate", default, skip_serializing_if = "Option::is_none")]
pub deleted_date: Option<i64>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct KeyProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub exportable: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kty: Option<key_properties::Kty>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub key_size: Option<i32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reuse_key: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub crv: Option<key_properties::Crv>,
}
pub mod key_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Kty {
#[serde(rename = "EC")]
Ec,
#[serde(rename = "EC-HSM")]
EcHsm,
#[serde(rename = "RSA")]
Rsa,
#[serde(rename = "RSA-HSM")]
RsaHsm,
#[serde(rename = "oct")]
Oct,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Crv {
#[serde(rename = "P-256")]
P256,
#[serde(rename = "P-384")]
P384,
#[serde(rename = "P-521")]
P521,
#[serde(rename = "P-256K")]
P256k,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct KeyCreateParameters {
pub kty: key_create_parameters::Kty,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub key_size: Option<i32>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub key_ops: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attributes: Option<KeyAttributes>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub crv: Option<key_create_parameters::Crv>,
}
pub mod key_create_parameters {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Kty {
#[serde(rename = "EC")]
Ec,
#[serde(rename = "EC-HSM")]
EcHsm,
#[serde(rename = "RSA")]
Rsa,
#[serde(rename = "RSA-HSM")]
RsaHsm,
#[serde(rename = "oct")]
Oct,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Crv {
#[serde(rename = "P-256")]
P256,
#[serde(rename = "P-384")]
P384,
#[serde(rename = "P-521")]
P521,
#[serde(rename = "P-256K")]
P256k,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct KeyImportParameters {
#[serde(rename = "Hsm", default, skip_serializing_if = "Option::is_none")]
pub hsm: Option<bool>,
pub key: JsonWebKey,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attributes: Option<KeyAttributes>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct KeyOperationsParameters {
pub alg: key_operations_parameters::Alg,
pub value: String,
}
pub mod key_operations_parameters {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Alg {
#[serde(rename = "RSA-OAEP")]
RsaOaep,
#[serde(rename = "RSA-OAEP-256")]
RsaOaep256,
#[serde(rename = "RSA1_5")]
Rsa15,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct KeySignParameters {
pub alg: key_sign_parameters::Alg,
pub value: String,
}
pub mod key_sign_parameters {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Alg {
#[serde(rename = "PS256")]
Ps256,
#[serde(rename = "PS384")]
Ps384,
#[serde(rename = "PS512")]
Ps512,
#[serde(rename = "RS256")]
Rs256,
#[serde(rename = "RS384")]
Rs384,
#[serde(rename = "RS512")]
Rs512,
#[serde(rename = "RSNULL")]
Rsnull,
#[serde(rename = "ES256")]
Es256,
#[serde(rename = "ES384")]
Es384,
#[serde(rename = "ES512")]
Es512,
#[serde(rename = "ES256K")]
Es256k,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct KeyVerifyParameters {
pub alg: key_verify_parameters::Alg,
pub digest: String,
pub value: String,
}
pub mod key_verify_parameters {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Alg {
#[serde(rename = "PS256")]
Ps256,
#[serde(rename = "PS384")]
Ps384,
#[serde(rename = "PS512")]
Ps512,
#[serde(rename = "RS256")]
Rs256,
#[serde(rename = "RS384")]
Rs384,
#[serde(rename = "RS512")]
Rs512,
#[serde(rename = "RSNULL")]
Rsnull,
#[serde(rename = "ES256")]
Es256,
#[serde(rename = "ES384")]
Es384,
#[serde(rename = "ES512")]
Es512,
#[serde(rename = "ES256K")]
Es256k,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct KeyUpdateParameters {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub key_ops: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attributes: Option<KeyAttributes>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct KeyRestoreParameters {
pub value: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct KeyOperationResult {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kid: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct KeyVerifyResult {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<bool>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct KeyListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<KeyItem>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DeletedKeyListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<DeletedKeyItem>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BackupKeyResult {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SecretBundle {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(rename = "contentType", default, skip_serializing_if = "Option::is_none")]
pub content_type: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attributes: Option<SecretAttributes>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kid: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub managed: Option<bool>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SecretItem {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attributes: Option<SecretAttributes>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
#[serde(rename = "contentType", default, skip_serializing_if = "Option::is_none")]
pub content_type: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub managed: Option<bool>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DeletedSecretBundle {
#[serde(flatten)]
pub secret_bundle: SecretBundle,
#[serde(rename = "recoveryId", default, skip_serializing_if = "Option::is_none")]
pub recovery_id: Option<String>,
#[serde(rename = "scheduledPurgeDate", default, skip_serializing_if = "Option::is_none")]
pub scheduled_purge_date: Option<i64>,
#[serde(rename = "deletedDate", default, skip_serializing_if = "Option::is_none")]
pub deleted_date: Option<i64>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DeletedSecretItem {
#[serde(flatten)]
pub secret_item: SecretItem,
#[serde(rename = "recoveryId", default, skip_serializing_if = "Option::is_none")]
pub recovery_id: Option<String>,
#[serde(rename = "scheduledPurgeDate", default, skip_serializing_if = "Option::is_none")]
pub scheduled_purge_date: Option<i64>,
#[serde(rename = "deletedDate", default, skip_serializing_if = "Option::is_none")]
pub deleted_date: Option<i64>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SecretAttributes {
#[serde(flatten)]
pub attributes: Attributes,
#[serde(rename = "recoverableDays", default, skip_serializing_if = "Option::is_none")]
pub recoverable_days: Option<i32>,
#[serde(rename = "recoveryLevel", default, skip_serializing_if = "Option::is_none")]
pub recovery_level: Option<secret_attributes::RecoveryLevel>,
}
pub mod secret_attributes {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum RecoveryLevel {
Purgeable,
#[serde(rename = "Recoverable+Purgeable")]
RecoverablePurgeable,
Recoverable,
#[serde(rename = "Recoverable+ProtectedSubscription")]
RecoverableProtectedSubscription,
#[serde(rename = "CustomizedRecoverable+Purgeable")]
CustomizedRecoverablePurgeable,
CustomizedRecoverable,
#[serde(rename = "CustomizedRecoverable+ProtectedSubscription")]
CustomizedRecoverableProtectedSubscription,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SecretRestoreParameters {
pub value: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SecretProperties {
#[serde(rename = "contentType", default, skip_serializing_if = "Option::is_none")]
pub content_type: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SecretSetParameters {
pub value: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
#[serde(rename = "contentType", default, skip_serializing_if = "Option::is_none")]
pub content_type: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attributes: Option<SecretAttributes>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SecretUpdateParameters {
#[serde(rename = "contentType", default, skip_serializing_if = "Option::is_none")]
pub content_type: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attributes: Option<SecretAttributes>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SecretListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<SecretItem>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DeletedSecretListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<DeletedSecretItem>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BackupSecretResult {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StorageRestoreParameters {
pub value: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StorageAccountAttributes {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub enabled: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub created: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub updated: Option<i64>,
#[serde(rename = "recoverableDays", default, skip_serializing_if = "Option::is_none")]
pub recoverable_days: Option<i32>,
#[serde(rename = "recoveryLevel", default, skip_serializing_if = "Option::is_none")]
pub recovery_level: Option<storage_account_attributes::RecoveryLevel>,
}
pub mod storage_account_attributes {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum RecoveryLevel {
Purgeable,
#[serde(rename = "Recoverable+Purgeable")]
RecoverablePurgeable,
Recoverable,
#[serde(rename = "Recoverable+ProtectedSubscription")]
RecoverableProtectedSubscription,
#[serde(rename = "CustomizedRecoverable+Purgeable")]
CustomizedRecoverablePurgeable,
CustomizedRecoverable,
#[serde(rename = "CustomizedRecoverable+ProtectedSubscription")]
CustomizedRecoverableProtectedSubscription,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StorageBundle {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(rename = "resourceId", default, skip_serializing_if = "Option::is_none")]
pub resource_id: Option<String>,
#[serde(rename = "activeKeyName", default, skip_serializing_if = "Option::is_none")]
pub active_key_name: Option<String>,
#[serde(rename = "autoRegenerateKey", default, skip_serializing_if = "Option::is_none")]
pub auto_regenerate_key: Option<bool>,
#[serde(rename = "regenerationPeriod", default, skip_serializing_if = "Option::is_none")]
pub regeneration_period: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attributes: Option<StorageAccountAttributes>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DeletedStorageBundle {
#[serde(flatten)]
pub storage_bundle: StorageBundle,
#[serde(rename = "recoveryId", default, skip_serializing_if = "Option::is_none")]
pub recovery_id: Option<String>,
#[serde(rename = "scheduledPurgeDate", default, skip_serializing_if = "Option::is_none")]
pub scheduled_purge_date: Option<i64>,
#[serde(rename = "deletedDate", default, skip_serializing_if = "Option::is_none")]
pub deleted_date: Option<i64>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StorageAccountCreateParameters {
#[serde(rename = "resourceId")]
pub resource_id: String,
#[serde(rename = "activeKeyName")]
pub active_key_name: String,
#[serde(rename = "autoRegenerateKey")]
pub auto_regenerate_key: bool,
#[serde(rename = "regenerationPeriod", default, skip_serializing_if = "Option::is_none")]
pub regeneration_period: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attributes: Option<StorageAccountAttributes>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StorageAccountUpdateParameters {
#[serde(rename = "activeKeyName", default, skip_serializing_if = "Option::is_none")]
pub active_key_name: Option<String>,
#[serde(rename = "autoRegenerateKey", default, skip_serializing_if = "Option::is_none")]
pub auto_regenerate_key: Option<bool>,
#[serde(rename = "regenerationPeriod", default, skip_serializing_if = "Option::is_none")]
pub regeneration_period: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attributes: Option<StorageAccountAttributes>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StorageAccountRegenerteKeyParameters {
#[serde(rename = "keyName")]
pub key_name: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StorageAccountItem {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(rename = "resourceId", default, skip_serializing_if = "Option::is_none")]
pub resource_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attributes: Option<StorageAccountAttributes>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DeletedStorageAccountItem {
#[serde(flatten)]
pub storage_account_item: StorageAccountItem,
#[serde(rename = "recoveryId", default, skip_serializing_if = "Option::is_none")]
pub recovery_id: Option<String>,
#[serde(rename = "scheduledPurgeDate", default, skip_serializing_if = "Option::is_none")]
pub scheduled_purge_date: Option<i64>,
#[serde(rename = "deletedDate", default, skip_serializing_if = "Option::is_none")]
pub deleted_date: Option<i64>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StorageListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<StorageAccountItem>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DeletedStorageListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<DeletedStorageAccountItem>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SasDefinitionAttributes {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub enabled: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub created: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub updated: Option<i64>,
#[serde(rename = "recoverableDays", default, skip_serializing_if = "Option::is_none")]
pub recoverable_days: Option<i32>,
#[serde(rename = "recoveryLevel", default, skip_serializing_if = "Option::is_none")]
pub recovery_level: Option<sas_definition_attributes::RecoveryLevel>,
}
pub mod sas_definition_attributes {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum RecoveryLevel {
Purgeable,
#[serde(rename = "Recoverable+Purgeable")]
RecoverablePurgeable,
Recoverable,
#[serde(rename = "Recoverable+ProtectedSubscription")]
RecoverableProtectedSubscription,
#[serde(rename = "CustomizedRecoverable+Purgeable")]
CustomizedRecoverablePurgeable,
CustomizedRecoverable,
#[serde(rename = "CustomizedRecoverable+ProtectedSubscription")]
CustomizedRecoverableProtectedSubscription,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SasDefinitionBundle {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sid: Option<String>,
#[serde(rename = "templateUri", default, skip_serializing_if = "Option::is_none")]
pub template_uri: Option<String>,
#[serde(rename = "sasType", default, skip_serializing_if = "Option::is_none")]
pub sas_type: Option<sas_definition_bundle::SasType>,
#[serde(rename = "validityPeriod", default, skip_serializing_if = "Option::is_none")]
pub validity_period: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attributes: Option<SasDefinitionAttributes>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
pub mod sas_definition_bundle {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum SasType {
#[serde(rename = "account")]
Account,
#[serde(rename = "service")]
Service,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DeletedSasDefinitionBundle {
#[serde(flatten)]
pub sas_definition_bundle: SasDefinitionBundle,
#[serde(rename = "recoveryId", default, skip_serializing_if = "Option::is_none")]
pub recovery_id: Option<String>,
#[serde(rename = "scheduledPurgeDate", default, skip_serializing_if = "Option::is_none")]
pub scheduled_purge_date: Option<i64>,
#[serde(rename = "deletedDate", default, skip_serializing_if = "Option::is_none")]
pub deleted_date: Option<i64>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SasDefinitionItem {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sid: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attributes: Option<SasDefinitionAttributes>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DeletedSasDefinitionItem {
#[serde(flatten)]
pub sas_definition_item: SasDefinitionItem,
#[serde(rename = "recoveryId", default, skip_serializing_if = "Option::is_none")]
pub recovery_id: Option<String>,
#[serde(rename = "scheduledPurgeDate", default, skip_serializing_if = "Option::is_none")]
pub scheduled_purge_date: Option<i64>,
#[serde(rename = "deletedDate", default, skip_serializing_if = "Option::is_none")]
pub deleted_date: Option<i64>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SasDefinitionListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<SasDefinitionItem>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DeletedSasDefinitionListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<DeletedSasDefinitionItem>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SasDefinitionCreateParameters {
#[serde(rename = "templateUri")]
pub template_uri: String,
#[serde(rename = "sasType")]
pub sas_type: sas_definition_create_parameters::SasType,
#[serde(rename = "validityPeriod")]
pub validity_period: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attributes: Option<SasDefinitionAttributes>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
pub mod sas_definition_create_parameters {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum SasType {
#[serde(rename = "account")]
Account,
#[serde(rename = "service")]
Service,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SasDefinitionUpdateParameters {
#[serde(rename = "templateUri", default, skip_serializing_if = "Option::is_none")]
pub template_uri: Option<String>,
#[serde(rename = "sasType", default, skip_serializing_if = "Option::is_none")]
pub sas_type: Option<sas_definition_update_parameters::SasType>,
#[serde(rename = "validityPeriod", default, skip_serializing_if = "Option::is_none")]
pub validity_period: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attributes: Option<SasDefinitionAttributes>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
pub mod sas_definition_update_parameters {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum SasType {
#[serde(rename = "account")]
Account,
#[serde(rename = "service")]
Service,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BackupStorageResult {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
}
|
use crate::{
buffer::{CellBuffer, Contacts, Span},
fragment,
fragment::{Arc, Circle},
Cell, Point, Settings,
};
use indexmap::IndexMap;
use once_cell::sync::Lazy;
use std::{
collections::{BTreeMap, HashMap},
iter::FromIterator,
};
/// skip the first 3 circles for constructing our arcs, otherwise it will just be a mess
pub const CIRCLES_TO_SKIP_FOR_ARC: usize = 3;
// These are circle map, when a group is detected to have these set of characters
// arrange together in such this way, then endorse them as a circle
// Each of these character formation will have a certain circle parameters: center, and radius.
//
/// ```ignore
/// 0 1 2 3 4 B C D
/// 0โโโฌโโฌโโฌโโ AโโโฌโโฌโโฌโโE
/// 1โโโผโโผโโผโโค โ โ โ โ โ
/// 2โโโผโโผโโผโโค FโโGโHโIโโคJ
/// 3โโโผโโผโโผโโค โ โ โ โ โ
/// 4โโโผโโผโโผโโค KโโLโMโNโโคO
/// 5โโโผโโผโโผโโค โ โ โ โ โ
/// 6โโโผโโผโโผโโค PโโQโRโSโโคT
/// 7โโโผโโผโโผโโค โ โ โ โ โ
/// 8โโโดโโดโโดโโ UโโโดโโดโโดโโY
/// ``` V W X
/// (
/// art - the ascii art of the circle, the empty space is automatically removed
/// edge_case - where the edge from the left most cell of the circle
/// f32 - how many cell from the left most to the center.x of the circle
/// f32 - how many cell from the top most to the center.y of the circle,
/// Cell - center cell in arc2
/// )
static CIRCLE_ART_MAP: Lazy<Vec<(&'static str, Horizontal, f32, f32, Cell)>> =
Lazy::new(|| {
vec![
// CIRCLE_0
//center 1,0,k, radius = 0.5
// 2 cell width , radius formula: (n-1)/2 = (2-1)/2 = 0.5
// where n is the number of cells used
// if edge_case starts at edge then n is added by 1.
// vert_mid: half (0.5/1.0)
// cx_lies: edge
// cy_lies: mid
//
// edge_case: start_half = 0.5, start_edge = 0.0
// if radius + edge_case has 0.5 then mid, 0.0 then edge
//
//
(
r#"
()
"#,
Horizontal::Half,
1.0,
0.5,
Cell::new(0, 0),
),
// CIRCLE_1
//center = 1,1,m radius = 1.0
// 3 cell width, (n-1)/2 = (3-1)/2 = 1.0
// vert_mid: half (0.5/1.0)
// cx_lies: mid
// cy_lies: mid
(
r#"
(_)
"#,
Horizontal::Half,
1.5,
0.5,
Cell::new(1, 0),
),
// CIRCLE_2
//center = 1,1,o radius = 1.5,
// 4 cell width, (n-1)/2 = (4-1)/2 = 1.5
// vert_mid: 3/4 (1.5/2.0)
// cx_lies: edge
// cy_lies: mid
(
r#"
__
(__)
"#,
Horizontal::Half,
2.0,
1.5,
Cell::new(1, 1),
),
// CIRCLE_3
//center: 2,1,m radius: 2.0
// 5 cell width, (n-1)/2 = (5-1)/2 = 2.0
// vert_mid: half (1.5/3.0)
// cx_lies: mid
// cy_lies: mid
//
// shared x, if starts at half and offset_center_x * 2.0 is odd
// shared y
(
r#"
,-.
( )
`-'
"#,
Horizontal::Half,
2.5,
1.5,
Cell::new(2, 1),
),
// CIRCLE_4
//center: 2,1,o radius: 2.5
// 6 cell width, (n-1)/2 = (6-1)/2 = 2.5
// vert_mid: half (1.5/3.0)
// cx_lies: edge
// cy_lies: mid
//
// no shared x, offset_center_x * 2.0 is even
// shared y
(
r#"
.--.
( )
`--'
"#,
Horizontal::Half,
3.0,
1.5,
Cell::new(2, 1),
),
// CIRCLE_5
//center: 3,2,m radius: 3.0
// 7 cell width, (n-1)/2 = (7-1)/2 = 3.0
// vert_mid: 2.5/4
// cx_lies: mid
// cy_lies: mid
//
// shared x
// shared y
(
r#"
_
.' '.
( )
`._.'
"#,
Horizontal::Half,
3.5,
2.5,
Cell::new(3, 2),
),
// CIRCLE_6
//center: 3,2,o radius: 3.5
// 8 cell width, (n-1)/2 = (8-1)/2 = 3.5
// vert_mid: 2.5/4
// cx_lies: edge
// cy_lies: mid
//
// no shared x
// shared y
(
r#"
__
,' '.
( )
`.__.'
"#,
Horizontal::Half,
4.0,
2.5,
Cell::new(3, 2),
),
// CIRCLE_7
//center: 4,2,m radius:4.0
// 9 cell width, (n-1)/2 = (9-1)/2 = 4.0
// vert_mid: half (2.5/5.0)
// cx_lies: mid
// cy_lies: mid
//
// shared x
// shared y
(
r#"
___
,' '.
( )
`. .'
`-'
"#,
Horizontal::Half,
4.5,
2.5,
Cell::new(4, 2),
),
// circle 8 and up can be divided into 4 quadrants these quadrants can be arcs and can be used as
// rounded edge with larger radius for rouded rect
// CIRCLE_8
//center: 4,2,w radius: 4.5
// start_edge: true
// 9 cell width, (n-0)/2 = (9-0)/2 = 4.5
// vert_mid: 3.0/5.0
// cx_lies: mid
// cy_lies: edge
//
// shared x
// no shared y
(
r#"
___
,' `.
/ \
\ /
`.___.'
"#,
Horizontal::LeftEdge,
4.5,
3.0,
Cell::new(4, 2),
),
// CIRCLE_9
//center: 4,2,y radius: 5.0
//start_edge: true
// 10 cell width, (n-0)/2 = (10-0)/2 = 5.0
// vert_mid: 3.0/5.0
// cx_lies: edge
// cy_lies: edge
//
// no shared x, if offset_center_x * 2.0 is even
// no shared y, if the offset_center_y * 2.0 is even
(
r#"
____
,' `.
/ \
\ /
`.____.'
"#,
Horizontal::LeftEdge,
5.0,
3.0,
Cell::new(4, 2),
),
// CIRCLE_10
//center:5,3,o radius: 5.5
// 12 cell width, (n-1)/2 = (12-1)/2 = 5.5
// vert_mid: 3.5/6.0
// cx_lies: edge
// cy_lies: mid
//
// no shared x
// shared y
(
r#"
____
.' `.
/ \
( )
\ /
`.____.'
"#,
Horizontal::Half,
6.0,
3.5,
Cell::new(5, 3),
),
// CIRCLE_11
//center:6,3,m radius: 6.0
// 13 cell width, (n-1)/2 = (13-1)/2 = 6.0
// vert_mid: 3.5/6.0
// cx_lies: mid
// cy_lies: mid
//
// shared x
// shared y
(
r#"
_____
,' `.
/ \
( )
\ /
`._____.'
"#,
Horizontal::Half,
6.5,
3.5,
Cell::new(6, 3),
),
// CIRCLE_12
// center: 6,3,y radius: 6.5
// vert_mid: 4.0/7.0
// cx_lies: edge
// cy_lies: edge
//
// no shared x
// no shared y
(
r#"
______
,' `.
/ \
| |
| |
\ /
`.______.'
"#,
Horizontal::Half,
7.0,
4.0,
Cell::new(6, 3),
),
// CIRCLE_13
//center: 7,3,w radius: 7.0
//vert_mid: 4.0/7.0
// cx_lies: mid
// cy_lies: edge
//
// shared x
// no shared y
(
r#"
_______
,' `.
/ \
| |
| |
\ /
`._______.'
"#,
Horizontal::Half,
7.5,
4.0,
Cell::new(7, 3),
),
// CIRCLE_14
//center: 7,4,o radius: 7.5
//vert_mid: 4.5/8.0
// cx_lies: edge
// cy_lies: mid
//
// no shared x
// shared y
(
r#"
________
,' `.
/ \
| |
| |
| |
\ /
`.________.'
"#,
Horizontal::Half,
8.0,
4.5,
Cell::new(7, 4),
),
// CIRCLE_15
//center: 8,4,m radius: 8.0
//vert_mid: 4.5/9.0
// cx_lies: mid
// cy_lies: mid
//
// shared x
// shared y
(
r#"
__-----__
,' `.
/ \
| |
| |
| |
\ /
`. .'
`-------'
"#,
Horizontal::Half,
8.5,
4.5,
Cell::new(8, 4),
),
// CIRCLE_16
//center: 8,4,o radius: 8.5
// vert_mid: 4.5/9.0
// cx_lies: edge
// cy_lies: mid
//
// no shared x
// shared y
(
r#"
.--------.
,' `.
/ \
| |
| |
| |
\ /
`. .'
`--------'
"#,
Horizontal::Half,
9.0,
4.5,
Cell::new(8, 4),
),
// CIRCLE_17
//center:9,5,m radius: 9.0
//vert_mid: 5.5/10.0
// cx_lies: mid
// cy_lies: mid
//
// shared x
// shared y
(
r#"
_.-'''''-._
,' `.
/ \
. .
| |
| |
| |
\ /
`._ _.'
'-.....-'
"#,
Horizontal::Half,
9.5,
5.5,
Cell::new(9, 5),
),
// CIRCLE_18
// center: 9,5,o radius: 9.5
// vert_mid: 5.5/10.0
// cx_lies: edge
// cy_lies: mid
//
// no shared x
// shared y
//
(
r#"
_.-''''''-._
,' `.
/ \
. .
| |
| |
| |
\ /
`._ _.'
'-......-'
"#,
Horizontal::Half,
10.0,
5.5,
Cell::new(9, 5),
),
// CIRCLE_19
// center: 10,5,m radius: 10
// vert_mid: 5.5/10.0
// cx_lies: mid
// cy_lies: mid
//
// shared x
// shared y
(
r#"
_.-'''''''-._
,' `.
/ \
. .
| |
| |
| |
\ /
`._ _.'
'-.......-'
"#,
Horizontal::Half,
10.5,
5.5,
Cell::new(10, 5),
),
// CIRCLE_20
// center: 10,5,o radius: 10.5
// vert_mid: 5.5/11.0
// cx_lies: edge
// cy_lies: mid
//
// no shared x
// shared y
(
r#"
_.-''''''''-._
,' `.
/ \
. .
| |
| |
| |
| |
\ /
`._ _.'
'-........-'
"#,
Horizontal::Half,
11.0,
5.5,
Cell::new(10, 5),
),
// CIRCLE_21
// center: 10,5,m radius: 11
// radius = (n-1)/2 = (23-1)/2 = 11
// vert_mid: 5.5/11.0
// cx_lies: mid
// cy_lies: mid
//
// shared x
// shared y
(
r#"
_.-'''''''''-._
,' `.
/ \
. .
| |
| |
| |
| |
\ /
`._ _.'
'-.........-'
"#,
Horizontal::Half,
11.5,
5.5,
Cell::new(11, 5),
),
]
});
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
/// edge cases of the circle art
pub enum Horizontal {
/// circle arc is touching the left edge of the first cell
/// ie: if the left most cell is `/` then it is touching the dge
LeftEdge,
/// if the left most cell is `(` or `|` then it starts at half the cell
Half,
}
pub struct CircleArt {
/// the ascii art of the circel
/// empty lines are ignored
/// empty vertical columns are ignored
ascii_art: &'static str,
start_edge: Horizontal,
/// distance in cell units, from the left edge of the ascii art to the center.x of the circle
offset_center_x: f32,
/// distance in cell units, from the top edge of the ascii art to the center.y of the circle
offset_center_y: f32,
}
impl CircleArt {
/// calculate the centel cell of this circle art
/// based on offset center
fn center_cell(&self) -> Cell {
let mut center_cell_x = self.offset_center_x - self.edge_increment_x();
// if no shared x (meaning even number of ascii art along x axis)
// we want to use the cell before it as the center cell
if !self.is_shared_x() {
center_cell_x -= 0.5;
}
let mut center_cell_y = self.offset_center_y;
if !self.is_shared_y() {
center_cell_y -= 0.5;
}
Cell::new(center_cell_x.floor() as i32, center_cell_y.floor() as i32)
}
/// returns the width in cells of the ascii art of this circle
fn width(&self) -> f32 {
let cb = CellBuffer::from(self.ascii_art);
let (lo, hi) = cb.bounds().expect("circle must have bounds");
match self.start_edge {
Horizontal::LeftEdge => (hi.x - lo.x) as f32 + 1.0,
Horizontal::Half => (hi.x - lo.x) as f32,
}
}
fn center(&self) -> Point {
let center_x = self.radius() + self.edge_increment_x();
let center_y = self.offset_center_y * 2.0;
Point::new(center_x, center_y)
}
fn edge_increment_x(&self) -> f32 {
match self.start_edge {
Horizontal::LeftEdge => 0.0,
Horizontal::Half => 0.5,
}
}
fn radius(&self) -> f32 {
self.width() / 2.0
}
fn diameter(&self) -> i32 {
(self.radius() * 2.0).floor() as i32
}
/// center cell at x will be shared if it is on the odd count
fn is_shared_x(&self) -> bool {
self.offset_center_x * 2.0 % 2.0 == 1.0
}
/// center cell at y will be shared if it is on the odd count
fn is_shared_y(&self) -> bool {
self.offset_center_y * 2.0 % 2.0 == 1.0
}
}
pub struct ArcSpans {
diameter: i32,
arc_spans: Vec<(Arc, Span)>,
}
static CIRCLE_MAP: Lazy<Vec<CircleArt>> = Lazy::new(|| {
Vec::from_iter(CIRCLE_ART_MAP.iter().enumerate().map(
|(
ndx,
(art, edge_case, offset_center_x, offset_center_y, arc2_center),
)| {
CircleArt {
ascii_art: *art,
start_edge: *edge_case,
offset_center_x: *offset_center_x,
offset_center_y: *offset_center_y,
}
},
))
});
/// The fragments for each of the circle
/// Calculate the span and get the group fragments
static FRAGMENTS_CIRCLE: Lazy<Vec<(Vec<Contacts>, Circle)>> = Lazy::new(|| {
Vec::from_iter(CIRCLE_MAP.iter().map(|circle_art| {
(
circle_art_to_group(circle_art.ascii_art),
Circle::new(circle_art.center(), circle_art.radius(), false),
)
}))
});
/// map of circle spans and their radius
pub static DIAMETER_CIRCLE: Lazy<HashMap<i32, (Point, Span)>> =
Lazy::new(|| {
HashMap::from_iter(CIRCLE_MAP.iter().map(|circle_art| {
let cb = CellBuffer::from(circle_art.ascii_art);
let mut spans: Vec<Span> = cb.into();
assert_eq!(spans.len(), 1);
let span = spans.remove(0).localize();
(circle_art.diameter(), (circle_art.center(), span))
}))
});
/// There is only 1 span per circle, and localized
pub static CIRCLES_SPAN: Lazy<IndexMap<Circle, Span>> = Lazy::new(|| {
IndexMap::from_iter(CIRCLE_MAP.iter().map(|circle_art| {
let cb = CellBuffer::from(circle_art.ascii_art);
let mut spans: Vec<Span> = cb.into();
assert_eq!(spans.len(), 1);
let span = spans.remove(0).localize();
(
Circle::new(circle_art.center(), circle_art.radius(), false),
span,
)
}))
});
/// top_left top top_right
/// p2
/// arc2 | arc1
/// |
/// left p3----+----- p1 right
/// |
/// arc3 | arc4
/// p4
/// bottom_left bottom bottom_right
///
/// (diameter, quarter arcs)
pub static QUARTER_ARC_SPAN: Lazy<BTreeMap<i32, ArcSpans>> = Lazy::new(|| {
BTreeMap::from_iter(CIRCLE_MAP.iter().skip(CIRCLES_TO_SKIP_FOR_ARC).map(
|circle_art| {
let span = circle_art_to_span(circle_art.ascii_art);
let bounds = span.cell_bounds().expect("must have bounds");
let top_left = bounds.top_left();
let bottom_right = bounds.bottom_right();
let top_right = bounds.top_right();
let bottom_left = bounds.bottom_left();
let center = circle_art.center();
let radius = circle_art.radius();
let p1 = Point::new(center.x + radius, center.y);
let p2 = Point::new(center.x, center.y - radius);
let p3 = Point::new(center.x - radius, center.y);
let p4 = Point::new(center.x, center.y + radius);
let arc2_center = circle_art.center_cell();
let span1_center = Cell::new(
(center.x.floor() / Cell::width()) as i32,
arc2_center.y,
);
let span2_center = arc2_center;
let span3_center = Cell::new(
arc2_center.x,
(center.y.floor() / Cell::height()) as i32,
);
let span4_center = Cell::new(
(center.x.floor() / Cell::width()) as i32,
(center.y.floor() / Cell::height()) as i32,
);
let bounds1 = Cell::rearrange_bound(span1_center, top_right);
let bounds2 = Cell::rearrange_bound(top_left, span2_center);
let bounds3 = Cell::rearrange_bound(bottom_left, span3_center);
let bounds4 = Cell::rearrange_bound(span4_center, bottom_right);
let span1 = span.extract(bounds1.0, bounds1.1).localize();
let span2 = span.extract(bounds2.0, bounds2.1).localize();
let span3 = span.extract(bounds3.0, bounds3.1).localize();
let span4 = span.extract(bounds4.0, bounds4.1).localize();
let arc1_start = bounds1.0.localize_point(p1);
let arc1_end = bounds1.0.localize_point(p2);
let arc2_start = bounds2.0.localize_point(p2);
let arc2_end = bounds2.0.localize_point(p3);
let arc3_start = bounds3.0.localize_point(p3);
let arc3_end = bounds3.0.localize_point(p4);
let arc4_start = bounds4.0.localize_point(p4);
let arc4_end = bounds4.0.localize_point(p1);
let arc1 = Arc::new(arc1_start, arc1_end, radius);
let arc2 = Arc::new(arc2_start, arc2_end, radius);
let arc3 = Arc::new(arc3_start, arc3_end, radius);
let arc4 = Arc::new(arc4_start, arc4_end, radius);
let diameter = circle_art.diameter();
(
diameter,
ArcSpans {
diameter,
arc_spans: vec![
(arc1, span1),
(arc2, span2),
(arc3, span3),
(arc4, span4),
],
},
)
},
))
});
pub static HALF_ARC_SPAN: Lazy<BTreeMap<i32, ArcSpans>> = Lazy::new(|| {
BTreeMap::from_iter(CIRCLE_MAP.iter().skip(CIRCLES_TO_SKIP_FOR_ARC).map(
|circle_art| {
let span = circle_art_to_span(circle_art.ascii_art);
let bounds = span.cell_bounds().expect("must have bounds");
let top_left = bounds.top_left();
let bottom_right = bounds.bottom_right();
let top_right = bounds.top_right();
let bottom_left = bounds.bottom_left();
assert_eq!(top_left.y, top_right.y);
assert_eq!(top_left.x, bottom_left.x);
assert_eq!(top_right.x, bottom_right.x);
assert_eq!(bottom_left.y, bottom_right.y);
let center_cell = circle_art.center_cell();
let center = circle_art.center();
let radius = circle_art.radius();
let p1 = Point::new(center.x + radius, center.y);
let p2 = Point::new(center.x, center.y - radius);
let p3 = Point::new(center.x - radius, center.y);
let p4 = Point::new(center.x, center.y + radius);
let arc2_center = center_cell;
let span1_center = Cell::new(
(center.x.floor() / Cell::width()) as i32,
arc2_center.y,
);
let span2_center = arc2_center;
let span3_center = Cell::new(
arc2_center.x,
(center.y.floor() / Cell::height()) as i32,
);
let span4_center = Cell::new(
(center.x.floor() / Cell::width()) as i32,
(center.y.floor() / Cell::height()) as i32,
);
let top_tangent = Cell::new(top_right.x, span1_center.y);
let bottom_tangent = Cell::new(bottom_left.x, span3_center.y);
let left_tangent = Cell::new(span2_center.x, top_left.y);
let right_tangent = Cell::new(span1_center.x, top_right.y);
let bounds_top_half = Cell::rearrange_bound(top_left, top_tangent);
let bounds_bottom_half =
Cell::rearrange_bound(bottom_tangent, bottom_right);
let bounds_left_half =
Cell::rearrange_bound(left_tangent, bottom_left);
let bounds_right_half =
Cell::rearrange_bound(right_tangent, bottom_right);
let span_top_half = span
.extract(bounds_top_half.0, bounds_top_half.1)
.localize();
let span_bottom_half = span
.extract(bounds_bottom_half.0, bounds_bottom_half.1)
.localize();
let span_left_half = span
.extract(bounds_left_half.0, bounds_left_half.1)
.localize();
let span_right_half = span
.extract(bounds_right_half.0, bounds_right_half.1)
.localize();
let bottom_half_start = bounds_bottom_half.0.localize_point(p3);
let bottom_half_end = bounds_bottom_half.0.localize_point(p1);
let right_half_start = bounds_right_half.0.localize_point(p4);
let right_half_end = bounds_right_half.0.localize_point(p2);
let arc_top_half = Arc::new(p1, p3, radius);
let arc_bottom_half =
Arc::new(bottom_half_start, bottom_half_end, radius);
let arc_left_half = Arc::new(p2, p4, radius);
let arc_right_half =
Arc::new(right_half_start, right_half_end, radius);
let diameter = circle_art.diameter();
(
diameter,
ArcSpans {
diameter,
arc_spans: vec![
(arc_top_half, span_top_half),
(arc_bottom_half, span_bottom_half),
(arc_left_half, span_left_half),
(arc_right_half, span_right_half),
],
},
)
},
))
});
pub static THREE_QUARTERS_ARC_SPAN: Lazy<BTreeMap<i32, ArcSpans>> =
Lazy::new(|| {
BTreeMap::from_iter(
CIRCLE_MAP
.iter()
.skip(CIRCLES_TO_SKIP_FOR_ARC)
.map(|circle_art| {
let span = circle_art_to_span(circle_art.ascii_art);
let bounds = span.cell_bounds().expect("must have bounds");
let top_left = bounds.top_left();
let bottom_right = bounds.bottom_right();
let top_right = bounds.top_right();
let bottom_left = bounds.bottom_left();
let center = circle_art.center();
let radius = circle_art.radius();
let p1 = Point::new(center.x + radius, center.y);
let p2 = Point::new(center.x, center.y - radius);
let p3 = Point::new(center.x - radius, center.y);
let p4 = Point::new(center.x, center.y + radius);
let arc2_center = circle_art.center_cell();
let span1_center = Cell::new(
(center.x.floor() / Cell::width()) as i32,
arc2_center.y,
);
let span2_center = arc2_center;
let span3_center = Cell::new(
arc2_center.x,
(center.y.floor() / Cell::height()) as i32,
);
let span4_center = Cell::new(
(center.x.floor() / Cell::width()) as i32,
(center.y.floor() / Cell::height()) as i32,
);
let top_tangent = Cell::new(top_right.x, span1_center.y);
let bottom_tangent =
Cell::new(bottom_left.x, span3_center.y);
let left_tangent = Cell::new(span2_center.x, top_left.y);
let right_tangent = Cell::new(span1_center.x, top_right.y);
let bounds1 =
Cell::rearrange_bound(span1_center, top_right);
let bounds2 = Cell::rearrange_bound(top_left, span2_center);
let bounds3 =
Cell::rearrange_bound(bottom_left, span3_center);
let bounds4 =
Cell::rearrange_bound(span4_center, bottom_right);
let span1 = span.extract(bounds1.0, bounds1.1);
let span2 = span.extract(bounds2.0, bounds2.1);
let span3 = span.extract(bounds3.0, bounds3.1);
let span4 = span.extract(bounds4.0, bounds4.1);
let span_123 = span1
.merge_no_check(&span2)
.merge_no_check(&span3)
.localize();
let span_234 = span2
.merge_no_check(&span3)
.merge_no_check(&span4)
.localize();
let span_341 = span3
.merge_no_check(&span4)
.merge_no_check(&span1)
.localize();
let span_412 = span4
.merge_no_check(&span1)
.merge_no_check(&span2)
.localize();
let arc_123 = Arc::major(p1, p4, radius);
let arc_234 = Arc::major(p2, p1, radius);
let arc_341 = Arc::major(p3, p2, radius);
let arc_412 = Arc::major(p4, p3, radius);
let diameter = circle_art.diameter();
(
diameter,
ArcSpans {
diameter,
arc_spans: vec![
(arc_123, span_123),
(arc_234, span_234),
(arc_341, span_341),
(arc_412, span_412),
],
},
)
}),
)
});
pub static FLATTENED_QUARTER_ARC_SPAN: Lazy<
BTreeMap<DiameterArc, (Arc, Span)>,
> = Lazy::new(|| {
BTreeMap::from_iter(QUARTER_ARC_SPAN.iter().flat_map(
|(diameter, arc_spans)| {
arc_spans.arc_spans.iter().enumerate().map(
move |(arc_index, arc_span)| {
(
DiameterArc {
diameter: *diameter,
arc: arc_index,
},
arc_span.clone(),
)
},
)
},
))
});
pub static FLATTENED_HALF_ARC_SPAN: Lazy<BTreeMap<DiameterArc, (Arc, Span)>> =
Lazy::new(|| {
BTreeMap::from_iter(HALF_ARC_SPAN.iter().flat_map(
|(diameter, arc_spans)| {
arc_spans.arc_spans.iter().enumerate().map(
move |(arc_index, arc_span)| {
(
DiameterArc {
diameter: *diameter,
arc: arc_index,
},
arc_span.clone(),
)
},
)
},
))
});
pub static FLATTENED_THREE_QUARTERS_ARC_SPAN: Lazy<
BTreeMap<DiameterArc, (Arc, Span)>,
> = Lazy::new(|| {
BTreeMap::from_iter(THREE_QUARTERS_ARC_SPAN.iter().flat_map(
|(diameter, arc_spans)| {
arc_spans.arc_spans.iter().enumerate().map(
move |(arc_index, arc_span)| {
(
DiameterArc {
diameter: *diameter,
arc: arc_index,
},
arc_span.clone(),
)
},
)
},
))
});
#[derive(Default, Hash, PartialEq, Eq)]
pub struct DiameterArc {
/// the arc diameter
diameter: i32,
/// arc number
arc: usize,
}
impl Ord for DiameterArc {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.diameter
.cmp(&other.diameter)
.then(self.arc.cmp(&other.arc))
}
}
impl PartialOrd for DiameterArc {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
fn circle_art_to_group(art: &str) -> Vec<Contacts> {
circle_art_to_span(art).into()
}
fn circle_art_to_span(art: &str) -> Span {
let cell_buffer = CellBuffer::from(art);
let mut spans: Vec<Span> = cell_buffer.into();
assert_eq!(spans.len(), 1);
spans.remove(0).localize()
}
pub fn endorse_circle_span(search: &Span) -> Option<(&Circle, Span)> {
CIRCLES_SPAN.iter().rev().find_map(|(circle, span)| {
let search_localized = search.clone().localize();
let (matched, unmatched) = is_subset_of(span, &search_localized);
if matched {
let unmatched_cell_chars = search
.iter()
.enumerate()
.filter_map(|(i, cell_char)| {
if unmatched.contains(&i) {
Some(*cell_char)
} else {
None
}
})
.collect::<Vec<_>>();
Some((circle, Span::from(unmatched_cell_chars)))
} else {
None
}
})
}
pub fn endorse_quarter_arc_span(search: &Span) -> Option<(&Arc, Span)> {
FLATTENED_QUARTER_ARC_SPAN.iter().rev().find_map(
|(_diameter, (arc, span))| {
let search_localized = search.clone().localize();
let (matched, unmatched) = is_subset_of(span, &search_localized);
if matched {
let unmatched_cell_chars = search
.iter()
.enumerate()
.filter_map(|(i, cell_char)| {
if unmatched.contains(&i) {
Some(*cell_char)
} else {
None
}
})
.collect::<Vec<_>>();
Some((arc, Span::from(unmatched_cell_chars)))
} else {
None
}
},
)
}
pub fn endorse_half_arc_span(search: &Span) -> Option<(&Arc, Span)> {
FLATTENED_HALF_ARC_SPAN
.iter()
.rev()
.find_map(|(_diameter, (arc, span))| {
let search_localized = search.clone().localize();
let (matched, unmatched) = is_subset_of(span, &search_localized);
if matched {
let unmatched_cell_chars = search
.iter()
.enumerate()
.filter_map(|(i, cell_char)| {
if unmatched.contains(&i) {
Some(*cell_char)
} else {
None
}
})
.collect::<Vec<_>>();
Some((arc, Span::from(unmatched_cell_chars)))
} else {
None
}
})
}
pub fn endorse_three_quarters_arc_span(search: &Span) -> Option<(&Arc, Span)> {
FLATTENED_THREE_QUARTERS_ARC_SPAN.iter().rev().find_map(
|(_diameter, (arc, span))| {
let search_localized = search.clone().localize();
let (matched, unmatched) = is_subset_of(span, &search_localized);
if matched {
let unmatched_cell_chars = search
.iter()
.enumerate()
.filter_map(|(i, cell_char)| {
if unmatched.contains(&i) {
Some(*cell_char)
} else {
None
}
})
.collect::<Vec<_>>();
Some((arc, Span::from(unmatched_cell_chars)))
} else {
None
}
},
)
}
/// returns true if all the contacts in subset is in big_set
/// This also returns the indices of big_set that are not found in the subset
fn is_subset_of<T: PartialEq>(
subset: &[T],
big_set: &[T],
) -> (bool, Vec<usize>) {
let mut unmatched = vec![];
let mut matched = 0;
for (_i, set) in subset.iter().enumerate() {
if big_set.contains(set) {
matched += 1;
}
}
for (bi, bset) in big_set.iter().enumerate() {
if !subset.contains(bset) {
unmatched.push(bi);
}
}
(matched == subset.len(), unmatched)
}
#[cfg(test)]
mod test_circle_map;
|
use crate::headers::{HeaderName, HeaderValue, Headers, EXPECT};
use crate::{ensure_eq_status, headers::Header};
use std::fmt::Debug;
/// HTTP `Expect` header
///
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Expect)
///
/// # Specifications
///
/// - [RFC 7231, section 5.1.1: Expect](https://tools.ietf.org/html/rfc7231#section-5.1.1)
///
/// # Examples
///
/// ```
/// # fn main() -> http_types::Result<()> {
/// #
/// use http_types::Response;
/// use http_types::other::Expect;
///
/// let expect = Expect::new();
///
/// let mut res = Response::new(200);
/// res.insert_header(&expect, &expect);
///
/// let expect = Expect::from_headers(res)?.unwrap();
/// assert_eq!(expect, Expect::new());
/// #
/// # Ok(()) }
/// ```
#[derive(Debug, Ord, PartialOrd, Eq, PartialEq)]
pub struct Expect {
_priv: (),
}
impl Expect {
/// Create a new instance of `Expect`.
pub fn new() -> Self {
Self { _priv: () }
}
/// Create an instance of `Expect` from a `Headers` instance.
pub fn from_headers(headers: impl AsRef<Headers>) -> crate::Result<Option<Self>> {
let headers = match headers.as_ref().get(EXPECT) {
Some(headers) => headers,
None => return Ok(None),
};
// If we successfully parsed the header then there's always at least one
// entry. We want the last entry.
let header = headers.iter().last().unwrap();
ensure_eq_status!(header, "100-continue", 400, "malformed `Expect` header");
Ok(Some(Self { _priv: () }))
}
}
impl Header for Expect {
fn header_name(&self) -> HeaderName {
EXPECT
}
fn header_value(&self) -> HeaderValue {
let value = "100-continue";
// SAFETY: the internal string is validated to be ASCII.
unsafe { HeaderValue::from_bytes_unchecked(value.into()) }
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::headers::Headers;
#[test]
fn smoke() -> crate::Result<()> {
let expect = Expect::new();
let mut headers = Headers::new();
expect.apply_header(&mut headers);
let expect = Expect::from_headers(headers)?.unwrap();
assert_eq!(expect, Expect::new());
Ok(())
}
#[test]
fn bad_request_on_parse_error() {
let mut headers = Headers::new();
headers.insert(EXPECT, "<nori ate the tag. yum.>");
let err = Expect::from_headers(headers).unwrap_err();
assert_eq!(err.status(), 400);
}
}
|
use std::collections::HashSet;
use crate::utils::file2vec;
pub fn day24(filename:&String){
let contents = file2vec::<String>(filename);
let contents:Vec<String> = contents.iter()
.filter_map(|x| {
match x {
Ok(line) => {
if !line.is_empty(){
Some(line.to_owned())
} else {None}
},
_ => None
}
}
).collect();
let mut seen = HashSet::new();
for line in &contents{
let tile = find_tile(line);
if seen.contains(&tile){
seen.remove(&tile);
} else {
seen.insert(tile);
}
}
println!("Part 1 ans: {}", seen.len());
let directions: Vec<(i32,i32)> = vec!["se", "sw", "nw", "ne", "e", "w"].iter().map(|x|find_tile(*x)).collect();
let mut day = 0;
while day < 100{
seen = tick_day(&seen, &directions);
day+=1;
}
println!("part 2 ans: {}", seen.len());
}
fn find_tile(line: &str)->(i32, i32){
let mut ans = (0, 0);
let mut chars = line.chars().peekable();
while let Some(ch) = chars.next(){
match ch {
'n' => {
if let Some(x) = chars.peek() {
match x {
'e' => {ans.0 += 1;},
'w' => {ans.0 -= 1;},
_ => ()
}
ans.1 += 1;
};
chars.next();
},
's' => {
if let Some(x) = chars.peek() {
match x {
'e' => {ans.0 += 1;},
'w' => {ans.0 -= 1;},
_ => ()
}
ans.1 -= 1;
};
chars.next();
},
'e' => {
ans.0 += 2;
},
'w' => {
ans.0 -= 2;
},
_ => ()
};
}
ans
}
fn turns_black(tile: (i32, i32), seen: &HashSet<(i32,i32)>, directions: &Vec<(i32,i32)>)->bool{
let is_black = seen.contains(&tile);
let mut count = 0;
for dir in directions{
let neighbour = (tile.0 + dir.0, tile.1 + dir.1);
if seen.contains(&neighbour){
count += 1;
}
};
if is_black {
!((count == 0) | (count > 2))
} else {
count == 2
}
}
fn tick_day(black_tiles: &HashSet<(i32,i32)>, directions: &Vec<(i32,i32)>)->HashSet<(i32,i32)>{
let mut n = -120;
let mut new_black_tiles = HashSet::new();
while n < 120 {
let mut e = -150 - (n%2);
while e < 150 + (n%2) {
if turns_black((n,e), black_tiles, directions){
new_black_tiles.insert((n,e));
}
e += 2;
}
n +=1;
}
new_black_tiles
} |
use std::thread;
use std::net::{TcpListener, TcpStream};
use std::io::{Read, Write};
use std::fs;
use std::str; //for parsing TCP stream
fn main() {
listen_connection();
}
fn listen_connection(){
let port = match get_port(){
Some(v) => v,
None => return,
};
let listener = TcpListener::bind(format!("0.0.0.0:{}", port)).unwrap();
println!("Server listening on port {}", port);
for stream in listener.incoming(){
match stream{
Ok(stream) => {
println!("New connection: {}", stream.peer_addr().unwrap());
handler(stream);
/*
thread::spawn(move|| {
send_files(stream)
});
*/
}
Err(e) => {
println!("Error: {}", e);
}
}
}
}
fn get_port() -> Option<i32>{
let mut file = match fs::File::open("./info/port.txt"){
Ok(v) => v,
Err(e) => {
println!("ERR: {}", e);
return None;
},
};
let mut contents = String::new();
match file.read_to_string(&mut contents){
Ok(_v) => (),
Err(e) => {
println!("couldn't read info from port");
println!("ERR: {}", e);
return None;
}
};
println!("CONTENT: {}", contents);
match contents.trim_end().parse::<i32>(){
Ok(v) => return Some(v),
Err(e) => {
println!("ERR: {}", e);
return None;
},
}
}
/*
* Function Name: handler()
*
* Arguments: mut stream: TcpStream
*
* Functionality: takes a TcpStream connection as an argument. Meant to receive data from client
* side, parse the data for an argument, and then send back the appropriate response, and do the
* action that is wanted.
* */
fn handler(mut stream: TcpStream){
const CHUNK:usize = 1024;
let mut buffer: [u8; CHUNK] = [0; CHUNK];
loop{
match stream.read(&mut buffer){
Ok(_) => break,
Err(e) => {
println!("Error in reading TCP stream\nERR: {}", e);
return;
},
}
}
let result = match str::from_utf8(&buffer){
Ok(v) => v,
Err(e) => {
println!("Error in converting TCP stream to string\nERR: {}", e);
return;
},
};
let args: Vec<&str> = result.split("\n").collect();
match args[0]{
"list" => {
println!("going to send list of files to client");
send_files(stream);
},
"file" => println!("going to receive file from client"),
"delete" => println!("going to delete the file on server"),
_ => println!("NOT A CASE: {}", args[0]),
}
}
fn send_files(mut stream: TcpStream){
let mut files:String = String::new();
let paths = match fs::read_dir("./files"){
Ok(v) => v,
Err(e) => {
println!("Couldn't open directory ./files");
println!("ERR: {:?}", e);
return;
},
};
for path in paths {
let temp:String = match path.unwrap().path().into_os_string().into_string(){
Ok(v) => v,
Err(e) => {
println!("Wasn't able to convert path to string");
println!("ERR: {:?}", e);
continue;
},
};
let vec: Vec<&str> = temp.split("/").collect();
let file: &str = vec[vec.len()-1];
files.push_str(&file.len().to_string());
files.push_str("\n");
files.push_str(vec[vec.len()-1]);
files.push_str("\n");
}
match stream.write(files.as_bytes()){
Ok(_v) => println!("send list of files to client"),
Err(e) => {
println!("Error occurred while trying to send list of files to client");
println!("ERR: {}", e);
},
};
}
|
use super::types;
use super::{Error, Header, SectionContent};
use num_traits::FromPrimitive;
use std::io::Read;
#[derive(Debug, Clone)]
pub enum DynamicContent {
None,
String((Vec<u8>, Option<u64>)),
Address(u64),
Flags1(types::DynamicFlags1),
}
impl Default for DynamicContent {
fn default() -> Self {
DynamicContent::None
}
}
#[derive(Debug, Clone, Default)]
pub struct Dynamic {
pub dhtype: types::DynamicType,
pub content: DynamicContent,
}
impl Dynamic {
pub fn from_reader<R>(
mut io: R,
linked: Option<&SectionContent>,
eh: &Header,
) -> Result<SectionContent, Error>
where
R: Read,
{
let strtab = match linked {
None => None,
Some(&SectionContent::Strtab(ref s)) => Some(s),
any => {
return Err(Error::LinkedSectionIsNotStrtab {
during: "reading dynamic",
link: any.cloned(),
});
}
};
let mut r = Vec::new();
while let Ok(tag) = elf_read_uclass!(eh, io) {
let val = elf_read_uclass!(eh, io)?;
match types::DynamicType::from_u64(tag) {
None => {
//return Err(Error::InvalidDynamicType(tag)),
// be conservative and return UNKNOWN
r.push(Dynamic {
dhtype: types::DynamicType::UNKNOWN,
content: DynamicContent::None,
});
}
Some(types::DynamicType::NULL) => {
r.push(Dynamic {
dhtype: types::DynamicType::NULL,
content: DynamicContent::None,
});
break;
}
Some(types::DynamicType::RPATH) => {
r.push(Dynamic {
dhtype: types::DynamicType::RPATH,
content: DynamicContent::String(match strtab {
None => (Vec::default(), None),
Some(s) => (s.get(val as usize), Some(val)),
}),
});
}
Some(types::DynamicType::RUNPATH) => {
r.push(Dynamic {
dhtype: types::DynamicType::RUNPATH,
content: DynamicContent::String(match strtab {
None => (Vec::default(), None),
Some(s) => (s.get(val as usize), Some(val)),
}),
});
}
Some(types::DynamicType::NEEDED) => {
r.push(Dynamic {
dhtype: types::DynamicType::NEEDED,
content: DynamicContent::String(match strtab {
None => (Vec::default(), None),
Some(s) => (s.get(val as usize), Some(val)),
}),
});
}
Some(types::DynamicType::FLAGS_1) => {
r.push(Dynamic {
dhtype: types::DynamicType::FLAGS_1,
content: DynamicContent::Flags1(
match types::DynamicFlags1::from_bits(val) {
Some(v) => v,
None => return Err(Error::InvalidDynamicFlags1(val)),
},
),
});
}
Some(x) => {
r.push(Dynamic {
dhtype: x,
content: DynamicContent::Address(val),
});
}
};
}
Ok(SectionContent::Dynamic(r))
}
}
|
use super::ide;
use super::BLK_SIZE;
use crate::lock::sleep::{SleepMutex, SleepMutexGuard};
use crate::lock::spin::SpinMutex;
use alloc::boxed::Box;
use alloc::collections::BTreeMap;
use core::sync::atomic::{AtomicU8, Ordering};
use lazy_static::lazy_static;
/// buffer has been read from disk
const B_VALID: u8 = 0x2;
/// buffer needs to be written to disk
const B_DIRTY: u8 = 0x4;
pub struct Flags(AtomicU8);
impl Flags {
pub fn empty() -> Self {
Self(AtomicU8::new(0))
}
pub fn set_dirty(&self, dirty: bool) {
if dirty {
self.0.fetch_or(B_DIRTY, Ordering::SeqCst);
} else {
self.0.fetch_and(!B_DIRTY, Ordering::SeqCst);
}
}
pub fn dirty(&self) -> bool {
self.0.load(Ordering::SeqCst) & B_DIRTY != 0
}
pub fn set_valid(&self, valid: bool) {
if valid {
self.0.fetch_or(B_VALID, Ordering::SeqCst);
} else {
self.0.fetch_and(!B_VALID, Ordering::SeqCst);
}
}
pub fn valid(&self) -> bool {
self.0.load(Ordering::SeqCst) & B_VALID != 0
}
}
pub struct BufLocked {
guard: SleepMutexGuard<'static, Buf>,
}
impl core::ops::Deref for BufLocked {
type Target = Buf;
fn deref(&self) -> &Self::Target {
&*self.guard
}
}
impl core::ops::DerefMut for BufLocked {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut *self.guard
}
}
impl Drop for BufLocked {
fn drop(&mut self) {
unsafe { BCACHE.lock().put(self.dev, self.block_no) };
}
}
pub struct Buf {
pub dev: u32,
pub block_no: u32,
pub flags: Flags,
pub data: [u8; BLK_SIZE],
}
impl Buf {
pub fn zero() -> Self {
Self {
dev: 0,
block_no: 0,
flags: Flags::empty(),
data: [0; BLK_SIZE],
}
}
pub fn id(&self) -> usize {
self as *const _ as usize
}
pub fn write(&self) {
if self.flags.dirty() {
ide::write_to_disk(self);
}
debug_assert!(!self.flags.dirty());
}
}
impl Drop for Buf {
fn drop(&mut self) {
log!("buf drop");
}
}
struct Bcache {
cache: BTreeMap<(u32, u32), (usize, &'static SleepMutex<Buf>)>,
}
impl Bcache {
pub fn new() -> Self {
Self {
cache: BTreeMap::new(),
}
}
fn get(&mut self, dev: u32, block_no: u32) -> &'static SleepMutex<Buf> {
let key = (dev, block_no);
match self.cache.get_mut(&key) {
Some((ref_cnt, r)) => {
*ref_cnt += 1;
r
}
None => {
let buf = {
let mut buf = Buf::zero();
buf.dev = dev;
buf.block_no = block_no;
buf
};
let buf = Box::leak(Box::new(SleepMutex::new("buf", buf)));
self.cache.insert(key, (1, buf));
buf
}
}
}
unsafe fn put(&mut self, dev: u32, block_no: u32) {
let key = (dev, block_no);
match self.cache.get_mut(&key) {
Some((ref_cnt, mtx)) => {
*ref_cnt -= 1;
if *ref_cnt == 0 {
// Retrieve the box and drop it.
drop(Box::from_raw(mtx));
self.cache.remove(&key);
}
}
None => panic!("Bcache::put: no entry"),
}
}
}
lazy_static! {
static ref BCACHE: SpinMutex<Bcache> = SpinMutex::new("bcache", Bcache::new());
}
pub fn read(dev: u32, block_no: u32) -> BufLocked {
let b = BCACHE.lock().get(dev, block_no);
let mut b = BufLocked { guard: b.lock() };
if !b.flags.valid() {
ide::read_from_disk(&mut b);
}
debug_assert!(b.flags.valid());
b
}
pub fn init() {
lazy_static::initialize(&BCACHE);
}
|
use std::old_io as io;
use std::collections::HashMap;
fn main() {
// Read numbers
let (n,m) = get_nums();
// Fill cache up to n:
let mut fibs = HashMap::with_capacity(n as usize);
{
let mut fib: Fibonacci = Fibonacci{ curr: 1, next:0};
for (i, num) in fib.take((n + 1) as usize).enumerate() {
fibs.insert(i,num);
}
}
let mut result = fib(n+1-m,m, &fibs);
println!("{}", result);
}
fn fib(n:u64, m: u64, cache: &HashMap<usize,u64>) -> u64 {
match cache.get(&(n as usize)) {
Some(&num) => num,
None => match n {
0 => 0,
1 => 1,
_ => fib(n - 1, m, &cache) + fib(n - 2,m,&cache)
}
}
}
struct Fibonacci {
curr: u64,
next: u64,
}
impl Iterator for Fibonacci {
type Item = u64;
fn next(&mut self) -> Option<u64> {
let new_next = self.curr + self.next;
self.curr = self.next;
self.next = new_next;
Some(self.curr)
}
}
fn get_nums() -> (u64,u64) {
let input = io::stdin().read_line().ok().expect("Reading stdin failed!");
let inputs: Vec<&str>= input.split_str(" ").take(2).map(|x| x.trim()).collect();
if inputs.len() != 2 { panic!("More ints please!") };
let a: Result<u64,_> = inputs[0].parse();
let b: Result<u64,_> = inputs[1].parse();
match (a,b) {
(Ok(a_), Ok(b_)) => (a_, b_),
_ => panic!("Not a number.")
}
} |
use libp2p::core::upgrade::ReadyUpgrade;
use libp2p::swarm::handler::ConnectionEvent;
use libp2p::swarm::{ConnectionHandler, ConnectionHandlerEvent, KeepAlive, SubstreamProtocol};
use libp2p::StreamProtocol;
use std::error::Error;
use std::fmt;
use std::task::{Context, Poll};
use void::Void;
/// Connection handler for managing connections within our `reserved peers` protocol.
///
/// This `Handler` is part of our custom protocol designed to maintain persistent connections
/// with a set of predefined peers.
///
/// ## Connection Handling
///
/// The `Handler` manages the lifecycle of a connection to each peer. If it's connected to a
/// reserved peer, it maintains the connection alive (`KeepAlive::Yes`). If not, it allows the
/// connection to close (`KeepAlive::No`).
///
/// This behavior ensures that connections to reserved peers are maintained persistently,
/// while connections to non-reserved peers are allowed to close.
pub struct Handler {
/// Protocol name.
protocol_name: &'static str,
/// A boolean flag indicating whether the handler is currently connected to a reserved peer.
connected_to_reserved_peer: bool,
}
impl Handler {
/// Builds a new [`Handler`].
pub fn new(protocol_name: &'static str, connected_to_reserved_peer: bool) -> Self {
Handler {
protocol_name,
connected_to_reserved_peer,
}
}
}
#[derive(Debug)]
pub struct ReservedPeersError;
impl fmt::Display for ReservedPeersError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Reserved peers error.")
}
}
impl Error for ReservedPeersError {}
impl ConnectionHandler for Handler {
type FromBehaviour = Void;
type ToBehaviour = ();
type Error = ReservedPeersError;
type InboundProtocol = ReadyUpgrade<StreamProtocol>;
type OutboundProtocol = ReadyUpgrade<StreamProtocol>;
type OutboundOpenInfo = ();
type InboundOpenInfo = ();
fn listen_protocol(&self) -> SubstreamProtocol<ReadyUpgrade<StreamProtocol>, ()> {
SubstreamProtocol::new(
ReadyUpgrade::new(StreamProtocol::new(self.protocol_name)),
(),
)
}
fn on_behaviour_event(&mut self, _: Void) {}
fn connection_keep_alive(&self) -> KeepAlive {
if self.connected_to_reserved_peer {
KeepAlive::Yes
} else {
KeepAlive::No
}
}
fn poll(
&mut self,
_: &mut Context<'_>,
) -> Poll<ConnectionHandlerEvent<ReadyUpgrade<StreamProtocol>, (), (), Self::Error>> {
Poll::Pending
}
fn on_connection_event(
&mut self,
_: ConnectionEvent<
Self::InboundProtocol,
Self::OutboundProtocol,
Self::InboundOpenInfo,
Self::OutboundOpenInfo,
>,
) {
}
}
|
#[doc = "Register `CRH` reader"]
pub type R = crate::R<CRH_SPEC>;
#[doc = "Register `CRH` writer"]
pub type W = crate::W<CRH_SPEC>;
#[doc = "Field `MODE8` reader - Port n.8 mode bits"]
pub type MODE8_R = crate::FieldReader<MODE8_A>;
#[doc = "Port n.8 mode bits\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum MODE8_A {
#[doc = "0: Input mode (reset state)"]
Input = 0,
#[doc = "1: Output mode 10 MHz"]
Output = 1,
#[doc = "2: Output mode 2 MHz"]
Output2 = 2,
#[doc = "3: Output mode 50 MHz"]
Output50 = 3,
}
impl From<MODE8_A> for u8 {
#[inline(always)]
fn from(variant: MODE8_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for MODE8_A {
type Ux = u8;
}
impl MODE8_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> MODE8_A {
match self.bits {
0 => MODE8_A::Input,
1 => MODE8_A::Output,
2 => MODE8_A::Output2,
3 => MODE8_A::Output50,
_ => unreachable!(),
}
}
#[doc = "Input mode (reset state)"]
#[inline(always)]
pub fn is_input(&self) -> bool {
*self == MODE8_A::Input
}
#[doc = "Output mode 10 MHz"]
#[inline(always)]
pub fn is_output(&self) -> bool {
*self == MODE8_A::Output
}
#[doc = "Output mode 2 MHz"]
#[inline(always)]
pub fn is_output2(&self) -> bool {
*self == MODE8_A::Output2
}
#[doc = "Output mode 50 MHz"]
#[inline(always)]
pub fn is_output50(&self) -> bool {
*self == MODE8_A::Output50
}
}
#[doc = "Field `MODE8` writer - Port n.8 mode bits"]
pub type MODE8_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 2, O, MODE8_A>;
impl<'a, REG, const O: u8> MODE8_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "Input mode (reset state)"]
#[inline(always)]
pub fn input(self) -> &'a mut crate::W<REG> {
self.variant(MODE8_A::Input)
}
#[doc = "Output mode 10 MHz"]
#[inline(always)]
pub fn output(self) -> &'a mut crate::W<REG> {
self.variant(MODE8_A::Output)
}
#[doc = "Output mode 2 MHz"]
#[inline(always)]
pub fn output2(self) -> &'a mut crate::W<REG> {
self.variant(MODE8_A::Output2)
}
#[doc = "Output mode 50 MHz"]
#[inline(always)]
pub fn output50(self) -> &'a mut crate::W<REG> {
self.variant(MODE8_A::Output50)
}
}
#[doc = "Field `CNF8` reader - Port n.8 configuration bits"]
pub type CNF8_R = crate::FieldReader<CNF8_A>;
#[doc = "Port n.8 configuration bits\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum CNF8_A {
#[doc = "0: Analog mode / Push-Pull mode"]
PushPull = 0,
#[doc = "1: Floating input (reset state) / Open Drain-Mode"]
OpenDrain = 1,
#[doc = "2: Input with pull-up/pull-down / Alternate Function Push-Pull Mode"]
AltPushPull = 2,
#[doc = "3: Alternate Function Open-Drain Mode"]
AltOpenDrain = 3,
}
impl From<CNF8_A> for u8 {
#[inline(always)]
fn from(variant: CNF8_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for CNF8_A {
type Ux = u8;
}
impl CNF8_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> CNF8_A {
match self.bits {
0 => CNF8_A::PushPull,
1 => CNF8_A::OpenDrain,
2 => CNF8_A::AltPushPull,
3 => CNF8_A::AltOpenDrain,
_ => unreachable!(),
}
}
#[doc = "Analog mode / Push-Pull mode"]
#[inline(always)]
pub fn is_push_pull(&self) -> bool {
*self == CNF8_A::PushPull
}
#[doc = "Floating input (reset state) / Open Drain-Mode"]
#[inline(always)]
pub fn is_open_drain(&self) -> bool {
*self == CNF8_A::OpenDrain
}
#[doc = "Input with pull-up/pull-down / Alternate Function Push-Pull Mode"]
#[inline(always)]
pub fn is_alt_push_pull(&self) -> bool {
*self == CNF8_A::AltPushPull
}
#[doc = "Alternate Function Open-Drain Mode"]
#[inline(always)]
pub fn is_alt_open_drain(&self) -> bool {
*self == CNF8_A::AltOpenDrain
}
}
#[doc = "Field `CNF8` writer - Port n.8 configuration bits"]
pub type CNF8_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 2, O, CNF8_A>;
impl<'a, REG, const O: u8> CNF8_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "Analog mode / Push-Pull mode"]
#[inline(always)]
pub fn push_pull(self) -> &'a mut crate::W<REG> {
self.variant(CNF8_A::PushPull)
}
#[doc = "Floating input (reset state) / Open Drain-Mode"]
#[inline(always)]
pub fn open_drain(self) -> &'a mut crate::W<REG> {
self.variant(CNF8_A::OpenDrain)
}
#[doc = "Input with pull-up/pull-down / Alternate Function Push-Pull Mode"]
#[inline(always)]
pub fn alt_push_pull(self) -> &'a mut crate::W<REG> {
self.variant(CNF8_A::AltPushPull)
}
#[doc = "Alternate Function Open-Drain Mode"]
#[inline(always)]
pub fn alt_open_drain(self) -> &'a mut crate::W<REG> {
self.variant(CNF8_A::AltOpenDrain)
}
}
#[doc = "Field `CNF9` reader - Port n.9 configuration bits"]
pub use CNF8_R as CNF9_R;
#[doc = "Field `CNF10` reader - Port n.10 configuration bits"]
pub use CNF8_R as CNF10_R;
#[doc = "Field `CNF11` reader - Port n.11 configuration bits"]
pub use CNF8_R as CNF11_R;
#[doc = "Field `CNF12` reader - Port n.12 configuration bits"]
pub use CNF8_R as CNF12_R;
#[doc = "Field `CNF13` reader - Port n.13 configuration bits"]
pub use CNF8_R as CNF13_R;
#[doc = "Field `CNF14` reader - Port n.14 configuration bits"]
pub use CNF8_R as CNF14_R;
#[doc = "Field `CNF15` reader - Port n.15 configuration bits"]
pub use CNF8_R as CNF15_R;
#[doc = "Field `CNF9` writer - Port n.9 configuration bits"]
pub use CNF8_W as CNF9_W;
#[doc = "Field `CNF10` writer - Port n.10 configuration bits"]
pub use CNF8_W as CNF10_W;
#[doc = "Field `CNF11` writer - Port n.11 configuration bits"]
pub use CNF8_W as CNF11_W;
#[doc = "Field `CNF12` writer - Port n.12 configuration bits"]
pub use CNF8_W as CNF12_W;
#[doc = "Field `CNF13` writer - Port n.13 configuration bits"]
pub use CNF8_W as CNF13_W;
#[doc = "Field `CNF14` writer - Port n.14 configuration bits"]
pub use CNF8_W as CNF14_W;
#[doc = "Field `CNF15` writer - Port n.15 configuration bits"]
pub use CNF8_W as CNF15_W;
#[doc = "Field `MODE9` reader - Port n.9 mode bits"]
pub use MODE8_R as MODE9_R;
#[doc = "Field `MODE10` reader - Port n.10 mode bits"]
pub use MODE8_R as MODE10_R;
#[doc = "Field `MODE11` reader - Port n.11 mode bits"]
pub use MODE8_R as MODE11_R;
#[doc = "Field `MODE12` reader - Port n.12 mode bits"]
pub use MODE8_R as MODE12_R;
#[doc = "Field `MODE13` reader - Port n.13 mode bits"]
pub use MODE8_R as MODE13_R;
#[doc = "Field `MODE14` reader - Port n.14 mode bits"]
pub use MODE8_R as MODE14_R;
#[doc = "Field `MODE15` reader - Port n.15 mode bits"]
pub use MODE8_R as MODE15_R;
#[doc = "Field `MODE9` writer - Port n.9 mode bits"]
pub use MODE8_W as MODE9_W;
#[doc = "Field `MODE10` writer - Port n.10 mode bits"]
pub use MODE8_W as MODE10_W;
#[doc = "Field `MODE11` writer - Port n.11 mode bits"]
pub use MODE8_W as MODE11_W;
#[doc = "Field `MODE12` writer - Port n.12 mode bits"]
pub use MODE8_W as MODE12_W;
#[doc = "Field `MODE13` writer - Port n.13 mode bits"]
pub use MODE8_W as MODE13_W;
#[doc = "Field `MODE14` writer - Port n.14 mode bits"]
pub use MODE8_W as MODE14_W;
#[doc = "Field `MODE15` writer - Port n.15 mode bits"]
pub use MODE8_W as MODE15_W;
impl R {
#[doc = "Bits 0:1 - Port n.8 mode bits"]
#[inline(always)]
pub fn mode8(&self) -> MODE8_R {
MODE8_R::new((self.bits & 3) as u8)
}
#[doc = "Bits 2:3 - Port n.8 configuration bits"]
#[inline(always)]
pub fn cnf8(&self) -> CNF8_R {
CNF8_R::new(((self.bits >> 2) & 3) as u8)
}
#[doc = "Bits 4:5 - Port n.9 mode bits"]
#[inline(always)]
pub fn mode9(&self) -> MODE9_R {
MODE9_R::new(((self.bits >> 4) & 3) as u8)
}
#[doc = "Bits 6:7 - Port n.9 configuration bits"]
#[inline(always)]
pub fn cnf9(&self) -> CNF9_R {
CNF9_R::new(((self.bits >> 6) & 3) as u8)
}
#[doc = "Bits 8:9 - Port n.10 mode bits"]
#[inline(always)]
pub fn mode10(&self) -> MODE10_R {
MODE10_R::new(((self.bits >> 8) & 3) as u8)
}
#[doc = "Bits 10:11 - Port n.10 configuration bits"]
#[inline(always)]
pub fn cnf10(&self) -> CNF10_R {
CNF10_R::new(((self.bits >> 10) & 3) as u8)
}
#[doc = "Bits 12:13 - Port n.11 mode bits"]
#[inline(always)]
pub fn mode11(&self) -> MODE11_R {
MODE11_R::new(((self.bits >> 12) & 3) as u8)
}
#[doc = "Bits 14:15 - Port n.11 configuration bits"]
#[inline(always)]
pub fn cnf11(&self) -> CNF11_R {
CNF11_R::new(((self.bits >> 14) & 3) as u8)
}
#[doc = "Bits 16:17 - Port n.12 mode bits"]
#[inline(always)]
pub fn mode12(&self) -> MODE12_R {
MODE12_R::new(((self.bits >> 16) & 3) as u8)
}
#[doc = "Bits 18:19 - Port n.12 configuration bits"]
#[inline(always)]
pub fn cnf12(&self) -> CNF12_R {
CNF12_R::new(((self.bits >> 18) & 3) as u8)
}
#[doc = "Bits 20:21 - Port n.13 mode bits"]
#[inline(always)]
pub fn mode13(&self) -> MODE13_R {
MODE13_R::new(((self.bits >> 20) & 3) as u8)
}
#[doc = "Bits 22:23 - Port n.13 configuration bits"]
#[inline(always)]
pub fn cnf13(&self) -> CNF13_R {
CNF13_R::new(((self.bits >> 22) & 3) as u8)
}
#[doc = "Bits 24:25 - Port n.14 mode bits"]
#[inline(always)]
pub fn mode14(&self) -> MODE14_R {
MODE14_R::new(((self.bits >> 24) & 3) as u8)
}
#[doc = "Bits 26:27 - Port n.14 configuration bits"]
#[inline(always)]
pub fn cnf14(&self) -> CNF14_R {
CNF14_R::new(((self.bits >> 26) & 3) as u8)
}
#[doc = "Bits 28:29 - Port n.15 mode bits"]
#[inline(always)]
pub fn mode15(&self) -> MODE15_R {
MODE15_R::new(((self.bits >> 28) & 3) as u8)
}
#[doc = "Bits 30:31 - Port n.15 configuration bits"]
#[inline(always)]
pub fn cnf15(&self) -> CNF15_R {
CNF15_R::new(((self.bits >> 30) & 3) as u8)
}
}
impl W {
#[doc = "Bits 0:1 - Port n.8 mode bits"]
#[inline(always)]
#[must_use]
pub fn mode8(&mut self) -> MODE8_W<CRH_SPEC, 0> {
MODE8_W::new(self)
}
#[doc = "Bits 2:3 - Port n.8 configuration bits"]
#[inline(always)]
#[must_use]
pub fn cnf8(&mut self) -> CNF8_W<CRH_SPEC, 2> {
CNF8_W::new(self)
}
#[doc = "Bits 4:5 - Port n.9 mode bits"]
#[inline(always)]
#[must_use]
pub fn mode9(&mut self) -> MODE9_W<CRH_SPEC, 4> {
MODE9_W::new(self)
}
#[doc = "Bits 6:7 - Port n.9 configuration bits"]
#[inline(always)]
#[must_use]
pub fn cnf9(&mut self) -> CNF9_W<CRH_SPEC, 6> {
CNF9_W::new(self)
}
#[doc = "Bits 8:9 - Port n.10 mode bits"]
#[inline(always)]
#[must_use]
pub fn mode10(&mut self) -> MODE10_W<CRH_SPEC, 8> {
MODE10_W::new(self)
}
#[doc = "Bits 10:11 - Port n.10 configuration bits"]
#[inline(always)]
#[must_use]
pub fn cnf10(&mut self) -> CNF10_W<CRH_SPEC, 10> {
CNF10_W::new(self)
}
#[doc = "Bits 12:13 - Port n.11 mode bits"]
#[inline(always)]
#[must_use]
pub fn mode11(&mut self) -> MODE11_W<CRH_SPEC, 12> {
MODE11_W::new(self)
}
#[doc = "Bits 14:15 - Port n.11 configuration bits"]
#[inline(always)]
#[must_use]
pub fn cnf11(&mut self) -> CNF11_W<CRH_SPEC, 14> {
CNF11_W::new(self)
}
#[doc = "Bits 16:17 - Port n.12 mode bits"]
#[inline(always)]
#[must_use]
pub fn mode12(&mut self) -> MODE12_W<CRH_SPEC, 16> {
MODE12_W::new(self)
}
#[doc = "Bits 18:19 - Port n.12 configuration bits"]
#[inline(always)]
#[must_use]
pub fn cnf12(&mut self) -> CNF12_W<CRH_SPEC, 18> {
CNF12_W::new(self)
}
#[doc = "Bits 20:21 - Port n.13 mode bits"]
#[inline(always)]
#[must_use]
pub fn mode13(&mut self) -> MODE13_W<CRH_SPEC, 20> {
MODE13_W::new(self)
}
#[doc = "Bits 22:23 - Port n.13 configuration bits"]
#[inline(always)]
#[must_use]
pub fn cnf13(&mut self) -> CNF13_W<CRH_SPEC, 22> {
CNF13_W::new(self)
}
#[doc = "Bits 24:25 - Port n.14 mode bits"]
#[inline(always)]
#[must_use]
pub fn mode14(&mut self) -> MODE14_W<CRH_SPEC, 24> {
MODE14_W::new(self)
}
#[doc = "Bits 26:27 - Port n.14 configuration bits"]
#[inline(always)]
#[must_use]
pub fn cnf14(&mut self) -> CNF14_W<CRH_SPEC, 26> {
CNF14_W::new(self)
}
#[doc = "Bits 28:29 - Port n.15 mode bits"]
#[inline(always)]
#[must_use]
pub fn mode15(&mut self) -> MODE15_W<CRH_SPEC, 28> {
MODE15_W::new(self)
}
#[doc = "Bits 30:31 - Port n.15 configuration bits"]
#[inline(always)]
#[must_use]
pub fn cnf15(&mut self) -> CNF15_W<CRH_SPEC, 30> {
CNF15_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 = "Port configuration register high (GPIOn_CRL)\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`crh::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 [`crh::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct CRH_SPEC;
impl crate::RegisterSpec for CRH_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`crh::R`](R) reader structure"]
impl crate::Readable for CRH_SPEC {}
#[doc = "`write(|w| ..)` method takes [`crh::W`](W) writer structure"]
impl crate::Writable for CRH_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets CRH to value 0x4444_4444"]
impl crate::Resettable for CRH_SPEC {
const RESET_VALUE: Self::Ux = 0x4444_4444;
}
|
extern crate bulletrs;
extern crate cgmath;
use cgmath::{Vector3, Vector4};
use bulletrs::*;
#[test()]
fn set_get_user_index() {
let configuration = CollisionConfiguration::new_default();
let mut dynamics_world = DynamicsWorld::new_discrete_world(
CollisionDispatcher::new(&configuration),
Broadphase::new(BroadphaseInterface::DbvtBroadphase),
ConstraintSolver::new(),
configuration,
);
let shape = Shape::new_sphere(1.0);
let mass = 0.1;
let mut body1 = dynamics_world.add_rigid_body(RigidBody::new(
mass,
shape.calculate_local_inertia(mass),
shape,
Vector3::new(-4.0, 0.0, 0.0),
Vector4::new(0.0, 0.0, 0.0, 1.0),
));
assert_eq!(body1.get_user_index(), -1);
body1.set_user_index(5);
assert_eq!(body1.get_user_index(), 5);
}
#[test()]
fn set_get_user_data() {
let configuration = CollisionConfiguration::new_default();
let mut dynamics_world = DynamicsWorld::new_discrete_world(
CollisionDispatcher::new(&configuration),
Broadphase::new(BroadphaseInterface::DbvtBroadphase),
ConstraintSolver::new(),
configuration,
);
let shape = Shape::new_sphere(1.0);
let mass = 0.1;
let mut body1 = dynamics_world.add_rigid_body(RigidBody::new(
mass,
shape.calculate_local_inertia(mass),
shape,
Vector3::new(-4.0, 0.0, 0.0),
Vector4::new(0.0, 0.0, 0.0, 1.0),
));
body1.set_user_data(5);
assert_eq!(*unsafe { body1.get_user_data::<i32>().unwrap() }, 5);
}
#[test()]
fn ray_test_user_data() {
let configuration = CollisionConfiguration::new_default();
let mut dynamics_world = DynamicsWorld::new_discrete_world(
CollisionDispatcher::new(&configuration),
Broadphase::new(BroadphaseInterface::DbvtBroadphase),
ConstraintSolver::new(),
configuration,
);
let shape = Shape::new_sphere(1.0);
let mass = 0.1;
let mut body1 = dynamics_world.add_rigid_body(RigidBody::new(
mass,
shape.calculate_local_inertia(mass),
shape,
Vector3::new(-4.0, 0.0, 0.0),
Vector4::new(0.0, 0.0, 0.0, 1.0),
));
body1.set_user_data(5);
let shape2 = Shape::new_sphere(2.0);
let mass = 0.1;
let mut body2 = dynamics_world.add_rigid_body(RigidBody::new(
mass,
shape2.calculate_local_inertia(mass),
shape2,
Vector3::new(4.0, 0.0, 0.0),
Vector4::new(0.0, 0.0, 0.0, 1.0),
));
body2.set_user_data(8);
let result = dynamics_world.raytest(ClosestRayResultCallback::new(
Vector3::new(-10.0, 0.0, 0.0),
Vector3::new(10.0, 0.0, 0.0),
));
assert_eq!(result.closest_hit_fraction(), 0.25);
assert_eq!(result.intersections().len(), 1);
let body = result.intersections()[0].rigidbody();
assert!(body.is_some());
assert_eq!(*unsafe { body.unwrap().get_user_data::<i32>().unwrap() }, 5);
let result = dynamics_world.raytest(AllRayResultCallback::new(
Vector3::new(-10.0, 0.0, 0.0),
Vector3::new(10.0, 0.0, 0.0),
));
assert_eq!(result.intersections().len(), 2);
}
|
use crate::*;
#[derive(Encode, Decode, Clone, RuntimeDebug, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))]
pub struct Asset<AssetId, AssetBalance> {
pub id: AssetId,
pub amount: AssetBalance,
}
impl<AssetId, AssetBalance> Asset<AssetId, AssetBalance> {
pub fn new(id: AssetId, amount: AssetBalance) -> Self {
Self { id, amount }
}
}
|
use crate::enums::{Align, Color, ColorDepth, Cursor, Font, FrameType, Shortcut};
use crate::image::RgbImage;
use crate::prelude::*;
use crate::utils::FlString;
use fltk_sys::draw::*;
use std::ffi::{CStr, CString};
use std::mem;
use std::os::raw;
/// Defines a coordinate of x and y
#[derive(Copy, Clone, Debug)]
pub struct Coord<T: Copy>(pub T, pub T);
bitflags! {
/// Defines the line styles supported by fltk
pub struct LineStyle: i32 {
/// Solid line
const Solid = 0;
/// Dash
const Dash = 1;
/// Dot
const Dot =2;
/// Dash dot
const DashDot = 3;
/// Dash dot dot
const DashDotDot =4;
/// Cap flat
const CapFlat = 100;
/// Cap round
const CapRound = 200;
/// Cap square
const CapSquare = 300;
/// Join miter
const JoinMiter = 1000;
/// Join round
const JoinRound = 2000;
/// Join bevel
const JoinBevel = 3000;
}
}
/// Opaque type around `Fl_Region`
pub type Region = *mut raw::c_void;
/// Opaque type around `Fl_Offscreen`
#[derive(Debug)]
pub struct Offscreen {
inner: *mut raw::c_void,
}
unsafe impl Sync for Offscreen {}
unsafe impl Send for Offscreen {}
impl Offscreen {
/// Creates a new offscreen type
pub fn new(w: i32, h: i32) -> Option<Offscreen> {
unsafe {
let x = Fl_create_offscreen(w, h);
if x.is_null() {
None
} else {
Some(Offscreen { inner: x })
}
}
}
/// Creates an uninitialized offscreen type
/// # Safety
/// Leaves the offscreen in an uninitialized state
pub unsafe fn uninit() -> Offscreen {
Offscreen {
inner: std::ptr::null_mut(),
}
}
/// Begins drawing in the offscreen
pub fn begin(&self) {
assert!(!self.inner.is_null());
unsafe { Fl_begin_offscreen(self.inner) }
}
/// Ends drawing in the offscreen
pub fn end(&self) {
assert!(!self.inner.is_null());
unsafe { Fl_end_offscreen() }
}
/// Copies the offscreen
pub fn copy(&self, x: i32, y: i32, w: i32, h: i32, src_x: i32, src_y: i32) {
assert!(!self.inner.is_null());
unsafe { Fl_copy_offscreen(x, y, w, h, self.inner, src_x, src_y) }
}
/// Rescales the offscreen
pub fn rescale(&mut self) {
assert!(!self.inner.is_null());
unsafe { Fl_rescale_offscreen(self.inner) }
}
/// Checks the validity of the offscreen
pub fn is_valid(&self) -> bool {
assert!(!self.inner.is_null());
!self.inner.is_null()
}
/// Performs a shallow copy of the offscreen
/// # Safety
/// This can lead to multiple mutable references to the same offscreen
pub unsafe fn shallow_copy(&self) -> Offscreen {
assert!(!self.inner.is_null());
Offscreen { inner: self.inner }
}
}
impl Drop for Offscreen {
fn drop(&mut self) {
unsafe { Fl_delete_offscreen(self.inner) }
}
}
/// Shows a color map
pub fn show_colormap(old_color: Color) -> Color {
unsafe { mem::transmute(Fl_show_colormap(old_color.bits() as u32)) }
}
/// Sets the color using rgb values
pub fn set_color_rgb(r: u8, g: u8, b: u8) {
unsafe { Fl_set_color_rgb(r, g, b) }
}
/// Gets the last used color
pub fn get_color() -> Color {
unsafe { mem::transmute(Fl_get_color()) }
}
/// Draws a line
pub fn draw_line(x1: i32, y1: i32, x2: i32, y2: i32) {
unsafe {
Fl_line(x1, y1, x2, y2);
}
}
/// Draws a line from (x,y) to (x1,y1) and another from (x1,y1) to (x2,y2)
pub fn draw_line2(pos1: Coord<i32>, pos2: Coord<i32>, pos3: Coord<i32>) {
unsafe { Fl_line2(pos1.0, pos1.1, pos2.0, pos2.1, pos3.0, pos3.1) }
}
/// Draws a point
pub fn draw_point(x: i32, y: i32) {
unsafe { Fl_point(x, y) }
}
/// Draws a point
pub fn draw_point2(pos: Coord<i32>) {
unsafe { Fl_point(pos.0, pos.1) }
}
/// Draws a rectangle
pub fn draw_rect(x: i32, y: i32, w: i32, h: i32) {
unsafe { Fl_rect(x, y, w, h) }
}
/// Draws a rectangle with border color
pub fn draw_rect_with_color(x: i32, y: i32, w: i32, h: i32, color: Color) {
unsafe { Fl_rect_with_color(x, y, w, h, color.bits() as u32) }
}
/// Draws a non-filled 3-sided polygon
pub fn draw_loop(x1: i32, y1: i32, x2: i32, y2: i32, x3: i32, y3: i32) {
unsafe {
Fl_loop(x1, y1, x2, y2, x3, y3);
}
}
/// Draws a non-filled 3-sided polygon
pub fn draw_loop2(pos1: Coord<i32>, pos2: Coord<i32>, pos3: Coord<i32>) {
unsafe { Fl_loop(pos1.0, pos1.1, pos2.0, pos2.1, pos3.0, pos3.1) }
}
/// Draws a non-filled 4-sided polygon
pub fn draw_loop3(pos1: Coord<i32>, pos2: Coord<i32>, pos3: Coord<i32>, pos4: Coord<i32>) {
unsafe {
Fl_loop2(
pos1.0, pos1.1, pos2.0, pos2.1, pos3.0, pos3.1, pos4.0, pos4.1,
)
}
}
/// Draws a filled rectangle
pub fn draw_rect_fill(x: i32, y: i32, w: i32, h: i32, color: Color) {
unsafe { Fl_rectf_with_color(x, y, w, h, color.bits() as u32) }
}
/// Draws a focus rectangle
pub fn draw_focus_rect(x: i32, y: i32, w: i32, h: i32) {
unsafe { Fl_focus_rect(x, y, w, h) }
}
/// Sets the drawing color
pub fn set_draw_hex_color(color: u32) {
let (r, g, b) = crate::utils::hex2rgb(color);
unsafe { Fl_set_color_rgb(r, g, b) }
}
/// Sets the drawing color
pub fn set_draw_rgb_color(r: u8, g: u8, b: u8) {
unsafe { Fl_set_color_rgb(r, g, b) }
}
/// Sets the drawing color
pub fn set_draw_color(color: Color) {
unsafe { Fl_set_color_int(color.bits() as u32) }
}
/// Draws a circle
pub fn draw_circle(x: f64, y: f64, r: f64) {
unsafe {
Fl_circle(x, y, r);
}
}
/// Draws an arc
pub fn draw_arc(x: i32, y: i32, width: i32, height: i32, a: f64, b: f64) {
unsafe {
Fl_arc(x, y, width, height, a, b);
}
}
/// Draws an arc
pub fn draw_arc2(x: f64, y: f64, r: f64, start: f64, end: f64) {
unsafe { Fl_arc2(x, y, r, start, end) }
}
/// Draws a filled pie
pub fn draw_pie(x: i32, y: i32, width: i32, height: i32, a: f64, b: f64) {
unsafe {
Fl_pie(x, y, width, height, a, b);
}
}
/// Sets the line style
pub fn set_line_style(style: LineStyle, width: i32) {
unsafe {
Fl_line_style(
style.bits(),
width,
std::ptr::null_mut() as *mut std::os::raw::c_char,
);
}
}
/// Limits drawing to a region
pub fn push_clip(x: i32, y: i32, w: i32, h: i32) {
unsafe {
Fl_push_clip(x, y, w, h);
}
}
/// Puts the drawing back
pub fn pop_clip() {
unsafe {
Fl_pop_clip();
}
}
/// Sets the clip region
pub fn set_clip_region(r: Region) {
assert!(!r.is_null());
unsafe { Fl_set_clip_region(r) }
}
/// Gets the clip region
pub fn clip_region() -> Region {
unsafe {
let ptr = Fl_clip_region();
assert!(!ptr.is_null());
ptr
}
}
/// Pushes an empty clip region onto the stack so nothing will be clipped
pub fn push_no_clip() {
unsafe { Fl_push_no_clip() }
}
/// Returns whether the rectangle intersect with the current clip region
pub fn not_clipped(x: i32, y: i32, w: i32, h: i32) -> bool {
unsafe { Fl_not_clipped(x, y, w, h) != 0 }
}
/// Restores the clip region
pub fn restore_clip() {
unsafe { Fl_restore_clip() }
}
/// Transforms coordinate using the current transformation matrix
pub fn transform_x(x: f64, y: f64) -> f64 {
unsafe { Fl_transform_x(x, y) }
}
/// Transforms coordinate using the current transformation matrix
pub fn transform_y(x: f64, y: f64) -> f64 {
unsafe { Fl_transform_y(x, y) }
}
/// Transforms distance using current transformation matrix
pub fn transform_dx(x: f64, y: f64) -> f64 {
unsafe { Fl_transform_dx(x, y) }
}
/// Transforms distance using current transformation matrix
pub fn transform_dy(x: f64, y: f64) -> f64 {
unsafe { Fl_transform_dy(x, y) }
}
/// Adds coordinate pair to the vertex list without further transformations
pub fn transformed_vertex(xf: f64, yf: f64) {
unsafe { Fl_transformed_vertex(xf, yf) }
}
/// Draws a filled rectangle
pub fn draw_rectf(x: i32, y: i32, w: i32, h: i32) {
unsafe { Fl_rectf(x, y, w, h) }
}
/// Draws a filled rectangle with specified RGB color
pub fn draw_rectf_with_rgb(
x: i32,
y: i32,
width: i32,
height: i32,
color_r: u8,
color_g: u8,
color_b: u8,
) {
unsafe { Fl_rectf_with_rgb(x, y, width, height, color_r, color_g, color_b) }
}
/// Fills a 3-sided polygon. The polygon must be convex
pub fn draw_polygon(x: i32, y: i32, x1: i32, y1: i32, x2: i32, y2: i32) {
unsafe { Fl_polygon(x, y, x1, y1, x2, y2) }
}
/// Fills a 3-sided polygon. The polygon must be convex
pub fn draw_polygon2(pos1: Coord<i32>, pos2: Coord<i32>, pos3: Coord<i32>) {
unsafe { Fl_polygon(pos1.0, pos1.1, pos2.0, pos2.1, pos3.0, pos3.1) }
}
/// Fills a 4-sided polygon. The polygon must be convex
pub fn draw_polygon3(pos1: Coord<i32>, pos2: Coord<i32>, pos3: Coord<i32>, pos4: Coord<i32>) {
unsafe {
Fl_polygon2(
pos1.0, pos1.1, pos2.0, pos2.1, pos3.0, pos3.1, pos4.0, pos4.1,
)
}
}
/// Adds a series of points on a Bezier curve to the path
pub fn draw_curve(pos1: Coord<f64>, pos2: Coord<f64>, pos3: Coord<f64>, pos4: Coord<f64>) {
unsafe {
Fl_curve(
pos1.0, pos1.1, pos2.0, pos2.1, pos3.0, pos3.1, pos4.0, pos4.1,
)
}
}
/// Draws a horizontal line from (x,y) to (x1,y)
pub fn draw_xyline(x: i32, y: i32, x1: i32) {
unsafe { Fl_xyline(x, y, x1) }
}
/// Draws a horizontal line from (x,y) to (x1,y), then vertical from (x1,y) to (x1,y2)
pub fn draw_xyline2(x: i32, y: i32, x1: i32, y2: i32) {
unsafe { Fl_xyline2(x, y, x1, y2) }
}
/// Draws a horizontal line from (x,y) to (x1,y), then a vertical from (x1,y) to (x1,y2)
/// and then another horizontal from (x1,y2) to (x3,y2)
pub fn draw_xyline3(x: i32, y: i32, x1: i32, y2: i32, x3: i32) {
unsafe { Fl_xyline3(x, y, x1, y2, x3) }
}
/// Draws a vertical line from (x,y) to (x,y1)
pub fn draw_yxline(x: i32, y: i32, y1: i32) {
unsafe { Fl_yxline(x, y, y1) }
}
/// Draws a vertical line from (x,y) to (x,y1), then a horizontal from (x,y1) to (x2,y1)
pub fn draw_yxline2(x: i32, y: i32, y1: i32, x2: i32) {
unsafe { Fl_yxline2(x, y, y1, x2) }
}
/// Draws a vertical line from (x,y) to (x,y1) then a horizontal from (x,y1)
/// to (x2,y1), then another vertical from (x2,y1) to (x2,y3)
pub fn draw_yxline3(x: i32, y: i32, y1: i32, x2: i32, y3: i32) {
unsafe { Fl_yxline3(x, y, y1, x2, y3) }
}
/// Saves the current transformation matrix on the stack
pub fn push_matrix() {
unsafe { Fl_push_matrix() }
}
/// Pops the current transformation matrix from the stack
pub fn pop_matrix() {
unsafe { Fl_pop_matrix() }
}
/// Concatenates scaling transformation onto the current one
pub fn scale_xy(x: f64, y: f64) {
unsafe { Fl_scale(x, y) }
}
/// Concatenates scaling transformation onto the current one
pub fn scale_x(x: f64) {
unsafe { Fl_scale2(x) }
}
/// Concatenates translation transformation onto the current one
pub fn translate(x: f64, y: f64) {
unsafe { Fl_translate(x, y) }
}
/// Concatenates rotation transformation onto the current one
pub fn rotate(d: f64) {
unsafe { Fl_rotate(d) }
}
/// Concatenates another transformation onto the current one
pub fn mult_matrix(val_a: f64, val_b: f64, val_c: f64, val_d: f64, x: f64, y: f64) {
unsafe { Fl_mult_matrix(val_a, val_b, val_c, val_d, x, y) }
}
/// Starts drawing a list of points. Points are added to the list with `fl_vertex()`
pub fn begin_points() {
unsafe { Fl_begin_points() }
}
/// Starts drawing a list of lines
pub fn begin_line() {
unsafe { Fl_begin_line() }
}
/// Starts drawing a closed sequence of lines
pub fn begin_loop() {
unsafe { Fl_begin_loop() }
}
/// Starts drawing a convex filled polygon
pub fn begin_polygon() {
unsafe { Fl_begin_polygon() }
}
/// Adds a single vertex to the current path
pub fn vertex(x: f64, y: f64) {
unsafe { Fl_vertex(x, y) }
}
/// Ends list of points, and draws
pub fn end_points() {
unsafe { Fl_end_points() }
}
/// Ends list of lines, and draws
pub fn end_line() {
unsafe { Fl_end_line() }
}
/// Ends closed sequence of lines, and draws
pub fn end_loop() {
unsafe { Fl_end_loop() }
}
/// Ends closed sequence of lines, and draws
pub fn end_polygon() {
unsafe { Fl_end_polygon() }
}
/// Starts drawing a complex filled polygon
pub fn begin_complex_polygon() {
unsafe { Fl_begin_complex_polygon() }
}
/// Call gap() to separate loops of the path
pub fn gap() {
unsafe { Fl_gap() }
}
/// Ends complex filled polygon, and draws
pub fn end_complex_polygon() {
unsafe { Fl_end_complex_polygon() }
}
/// Sets the current font, which is then used in various drawing routines
pub fn set_font(face: Font, fsize: i32) {
unsafe { Fl_set_draw_font(face.bits() as i32, fsize as i32) }
}
/// Gets the current font, which is used in various drawing routines
pub fn font() -> Font {
unsafe { mem::transmute(Fl_font()) }
}
/// Gets the current font size, which is used in various drawing routines
pub fn size() -> i32 {
unsafe { Fl_size() as i32 }
}
/// Returns the recommended minimum line spacing for the current font
pub fn height() -> i32 {
unsafe { Fl_height() as i32 }
}
/// Sets the line spacing for the current font
pub fn set_height(font: Font, size: i32) {
unsafe {
Fl_set_height(font.bits() as i32, size as i32);
}
}
/// Returns the recommended distance above the bottom of a height() tall box to
/// draw the text at so it looks centered vertically in that box
pub fn descent() -> i32 {
unsafe { Fl_descent() }
}
/// Returns the typographical width of a string
pub fn width(txt: &str) -> f64 {
let txt = CString::safe_new(txt);
unsafe { Fl_width(txt.as_ptr()) }
}
/// Returns the typographical width of a sequence of n characters
pub fn width2(txt: &str, n: i32) -> f64 {
let txt = CString::safe_new(txt);
unsafe { Fl_width2(txt.as_ptr(), n) }
}
/// Measure the width and height of a text
pub fn measure(txt: &str, draw_symbols: bool) -> (i32, i32) {
let txt = CString::safe_new(txt);
let mut x = 0;
let mut y = 0;
unsafe {
Fl_measure(txt.as_ptr(), &mut x, &mut y, draw_symbols as i32);
}
(x, y)
}
/// Returns the typographical width of a single character
pub fn char_width(c: char) -> f64 {
unsafe { Fl_width3(c as u32) }
}
/// Converts text from Windows/X11 latin1 character set to local encoding
pub fn latin1_to_local(txt: &str, n: i32) -> String {
let txt = CString::safe_new(txt);
unsafe {
let x = Fl_latin1_to_local(txt.as_ptr(), n);
assert!(!x.is_null());
CStr::from_ptr(x as *mut raw::c_char)
.to_string_lossy()
.to_string()
}
}
/// Converts text from local encoding to Windowx/X11 latin1 character set
pub fn local_to_latin1(txt: &str, n: i32) -> String {
let txt = CString::safe_new(txt);
unsafe {
let x = Fl_local_to_latin1(txt.as_ptr(), n);
assert!(!x.is_null());
CStr::from_ptr(x as *mut raw::c_char)
.to_string_lossy()
.to_string()
}
}
/// Draws a string starting at the given x, y location
pub fn draw_text(txt: &str, x: i32, y: i32) {
let txt = CString::safe_new(txt);
unsafe { Fl_draw(txt.as_ptr(), x, y) }
}
/// Draws a string starting at the given x, y location with width and height and alignment
pub fn draw_text2(string: &str, x: i32, y: i32, width: i32, height: i32, align: Align) {
let s = CString::safe_new(string);
unsafe { Fl_draw_text2(s.as_ptr(), x, y, width, height, align.bits() as i32) }
}
/// Draws a string starting at the given x, y location, rotated to an angle
pub fn draw_text_angled(angle: i32, txt: &str, x: i32, y: i32) {
let txt = CString::safe_new(txt);
unsafe { Fl_draw2(angle, txt.as_ptr(), x, y) }
}
/// Draws a UTF-8 string right to left starting at the given x, y location
pub fn rtl_draw(txt: &str, x: i32, y: i32) {
let len = txt.len() as i32;
let txt = CString::safe_new(txt);
unsafe { Fl_rtl_draw(txt.as_ptr(), len, x, y) }
}
/// Draws a frame with text
pub fn draw_frame(string: &str, x: i32, y: i32, width: i32, height: i32) {
let s = CString::safe_new(string);
unsafe { Fl_frame(s.as_ptr(), x, y, width, height) }
}
/// Draws a frame with text.
/// Differs from frame() by the order of the line segments
pub fn draw_frame2(string: &str, x: i32, y: i32, width: i32, height: i32) {
let s = CString::safe_new(string);
unsafe { Fl_frame2(s.as_ptr(), x, y, width, height) }
}
/// Draws a box given the box type, size, position and color
pub fn draw_box(box_type: FrameType, x: i32, y: i32, w: i32, h: i32, color: Color) {
unsafe { Fl_draw_box(box_type as i32, x, y, w, h, color.bits() as u32) }
}
/// Checks whether platform supports true alpha blending for RGBA images
pub fn can_do_alpha_blending() -> bool {
unsafe { Fl_can_do_alpha_blending() != 0 }
}
/// Get a human-readable string from a shortcut value
pub fn shortcut_label(shortcut: Shortcut) -> String {
unsafe {
let x = Fl_shortcut_label(shortcut.bits() as u32);
assert!(!x.is_null());
CStr::from_ptr(x as *mut raw::c_char)
.to_string_lossy()
.to_string()
}
}
/// Draws a selection rectangle, erasing a previous one by XOR'ing it first.
pub fn overlay_rect(x: i32, y: i32, w: i32, h: i32) {
unsafe { Fl_overlay_rect(x, y, w, h) }
}
/// Erase a selection rectangle without drawing a new one
pub fn overlay_clear() {
unsafe { Fl_overlay_clear() }
}
/// Sets the cursor style
pub fn set_cursor(cursor: Cursor) {
unsafe { Fl_set_cursor(cursor as i32) }
}
/// Sets the cursor style
pub fn set_cursor_with_color(cursor: Cursor, fg: Color, bg: Color) {
unsafe { Fl_set_cursor2(cursor as i32, fg.bits() as i32, bg.bits() as i32) }
}
/// Sets the status
pub fn set_status(x: i32, y: i32, w: i32, h: i32) {
unsafe { Fl_set_status(x, y, w, h) }
}
/// Sets spot within the window
pub fn set_spot<Win: WindowExt>(font: Font, size: i32, x: i32, y: i32, w: i32, h: i32, win: &Win) {
unsafe {
assert!(!win.was_deleted());
Fl_set_spot(
font.bits() as i32,
size as i32,
x,
y,
w,
h,
win.as_widget_ptr() as *mut raw::c_void,
)
}
}
/// Resets the spot within the window
pub fn reset_spot() {
unsafe { Fl_reset_spot() }
}
/**
Captures part of the window and returns raw data.
Example usage:
```rust,no_run
use fltk::{prelude::*, *};
let mut win = window::Window::default();
let image = draw::capture_window(&mut win).unwrap();
```
# Errors
The api can fail to capture the window as an image
*/
pub fn capture_window<Win: WindowExt>(win: &mut Win) -> Result<RgbImage, FltkError> {
assert!(!win.was_deleted());
let cp = win.width() * win.height() * 3;
win.show();
unsafe {
let x = Fl_read_image(std::ptr::null_mut(), 0, 0, win.width(), win.height(), 0);
if x.is_null() {
Err(FltkError::Internal(FltkErrorKind::FailedOperation))
} else {
let x = std::slice::from_raw_parts(x, cp as usize);
Ok(RgbImage::new(
x,
win.width(),
win.height(),
ColorDepth::Rgb8,
)?)
}
}
}
/// Draw a framebuffer (rgba) into a widget
/// # Errors
/// Errors on invalid or unsupported image formats
pub fn draw_rgba<'a, T: WidgetBase>(wid: &'a mut T, fb: &'a [u8]) -> Result<(), FltkError> {
let width = wid.width();
let height = wid.height();
let mut img = crate::image::RgbImage::new(fb, width, height, ColorDepth::Rgba8)?;
wid.draw(move |s| {
let x = s.x();
let y = s.y();
let w = s.width();
let h = s.height();
img.scale(w, h, false, true);
img.draw(x, y, w, h);
});
Ok(())
}
/// Draw a framebuffer (rgba) into a widget
/// # Safety
/// The data passed should be valid and outlive the widget
pub unsafe fn draw_rgba_nocopy<T: WidgetBase>(wid: &mut T, fb: &[u8]) {
let ptr = fb.as_ptr();
let len = fb.len();
let width = wid.width();
let height = wid.height();
wid.draw(move |s| {
let x = s.x();
let y = s.y();
let w = s.width();
let h = s.height();
if let Ok(mut img) = crate::image::RgbImage::from_data(
std::slice::from_raw_parts(ptr, len),
width,
height,
ColorDepth::Rgba8,
) {
img.scale(w, h, false, true);
img.draw(x, y, w, h);
}
});
}
/// Draw a framebuffer (rgba) into a widget
/// # Errors
/// Errors on invalid or unsupported image formats
pub fn draw_rgb<'a, T: WidgetBase>(wid: &'a mut T, fb: &'a [u8]) -> Result<(), FltkError> {
let width = wid.width();
let height = wid.height();
let mut img = crate::image::RgbImage::new(fb, width, height, ColorDepth::Rgb8)?;
wid.draw(move |s| {
let x = s.x();
let y = s.y();
let w = s.width();
let h = s.height();
img.scale(w, h, false, true);
img.draw(x, y, w, h);
});
Ok(())
}
/// Draw a framebuffer (rgba) into a widget
/// # Safety
/// The data passed should be valid and outlive the widget
pub unsafe fn draw_rgb_nocopy<T: WidgetBase>(wid: &mut T, fb: &[u8]) {
let ptr = fb.as_ptr();
let len = fb.len();
let width = wid.width();
let height = wid.height();
wid.draw(move |s| {
let x = s.x();
let y = s.y();
let w = s.width();
let h = s.height();
if let Ok(mut img) = crate::image::RgbImage::from_data(
std::slice::from_raw_parts(ptr, len),
width,
height,
ColorDepth::Rgb8,
) {
img.scale(w, h, false, true);
img.draw(x, y, w, h);
}
});
}
/// Draw an image into a widget.
/// Requires a call to `app::set_visual(Mode::Rgb8).unwrap()`
/// # Errors
/// Errors on invalid or unsupported image formats
pub fn draw_image(
data: &[u8],
x: i32,
y: i32,
w: i32,
h: i32,
depth: ColorDepth,
) -> Result<(), FltkError> {
let sz = (w * h * depth as i32) as usize;
if sz > data.len() {
return Err(FltkError::Internal(FltkErrorKind::ImageFormatError));
}
unsafe {
Fl_draw_image(data.as_ptr(), x, y, w, h, depth as i32, 0);
}
Ok(())
}
/// Draw an image into a widget.
/// Requires a call to `app::set_visual(Mode::Rgb8).unwrap()`.
/// A negative depth flips the image horizontally,
/// while a negative line data flips it vertically.
/// Allows passing a line-data parameter
/// # Errors
/// Errors on invalid or unsupported image formats
/// # Safety
/// Passing wrong line data can read to over or underflow
pub unsafe fn draw_image2(data: &[u8], x: i32, y: i32, w: i32, h: i32, depth: i32, line_data: i32) {
Fl_draw_image(data.as_ptr(), x, y, w, h, depth, line_data);
}
|
//! Easy use of buttons.
use peripheral;
/// The user button.
pub static BUTTONS: [Button; 1] = [Button { i: 0 }];
/// A single button.
pub struct Button {
i: u8,
}
impl Button {
/// Read the state of the button.
pub fn pressed(&self) -> bool {
let idr = &peripheral::gpioa().idr;
match self.i {
0 => idr.read().idr0(),
_ => false
}
}
}
/// Initializes the necessary stuff to enable the button.
///
/// # Safety
///
/// - Must be called once
/// - Must be called in an interrupt-free environment
pub unsafe fn init() {
let rcc = peripheral::rcc_mut();
// RCC: Enable GPIOA
rcc.ahb1enr.modify(|_, w| w.gpioaen(true));
}
/// An enum over the Buttons, each Button is associated but its name.
pub enum Buttons {
/// User
User,
}
impl Buttons {
/// Read the state of this button.
pub fn pressed(&self) -> bool {
match *self {
Buttons::User => BUTTONS[0].pressed()
}
}
}
|
pub mod almost_infinite;
pub mod gillespie;
|
use std::fs;
use nom::{
branch::alt,
bytes::complete::tag,
character::complete::{char, digit1, line_ending},
combinator::{map, map_res},
multi::separated_list1,
sequence::{preceded, terminated},
IResult,
};
#[derive(Debug)]
enum Operation {
Add(usize),
Multiply(usize),
MultiplyBySelf,
}
#[derive(Debug)]
struct Monkey {
items: Vec<usize>,
operation: Operation,
divisible_by: usize,
true_target: usize,
false_target: usize,
actions: usize,
}
fn parse_usize(input: &str) -> IResult<&str, usize> {
let (input, number) = map_res(digit1, |s: &str| s.parse::<usize>())(input)?;
Ok((input, number))
}
fn parse_items(input: &str) -> IResult<&str, Vec<usize>> {
let (input, _) = tag(" Starting items: ")(input)?;
let (input, items) = separated_list1(tag(", "), parse_usize)(input)?;
let (input, _) = line_ending(input)?;
Ok((input, items))
}
fn parse_operation(input: &str) -> IResult<&str, Operation> {
let (input, _) = tag(" Operation: new = old ")(input)?;
let (input, operation) = terminated(
alt((
map(preceded(tag("+ "), parse_usize), Operation::Add),
map(tag("* old"), |_| Operation::MultiplyBySelf),
map(preceded(tag("* "), parse_usize), Operation::Multiply),
)),
line_ending,
)(input)?;
Ok((input, operation))
}
fn parse_divisible_by(input: &str) -> IResult<&str, usize> {
let (input, _) = tag(" Test: divisible by ")(input)?;
let (input, divisible_by) = parse_usize(input)?;
let (input, _) = line_ending(input)?;
Ok((input, divisible_by))
}
fn parse_true_false(input: &str) -> IResult<&str, (usize, usize)> {
let (input, _) = tag(" If true: throw to monkey ")(input)?;
let (input, true_target) = parse_usize(input)?;
let (input, _) = line_ending(input)?;
let (input, _) = tag(" If false: throw to monkey ")(input)?;
let (input, false_target) = parse_usize(input)?;
let (input, _) = line_ending(input)?;
Ok((input, (true_target, false_target)))
}
fn parse_monkey(input: &str) -> IResult<&str, Monkey> {
let (input, _) = tag("Monkey ")(input)?;
let (input, _) = parse_usize(input)?;
let (input, _) = char(':')(input)?;
let (input, _) = line_ending(input)?;
let (input, items) = parse_items(input)?;
let (input, operation) = parse_operation(input)?;
let (input, divisible_by) = parse_divisible_by(input)?;
let (input, (true_target, false_target)) = parse_true_false(input)?;
Ok((
input,
Monkey {
items,
operation,
divisible_by,
true_target,
false_target,
actions: 0,
},
))
}
fn do_the_thing(input: &str) -> usize {
let (input, mut monkeys) = separated_list1(line_ending, parse_monkey)(input).unwrap();
assert!(input.is_empty());
for _ in 0..20 {
for index in 0..monkeys.len() {
let mut items = Vec::new();
for item in &monkeys[index].items {
let mut new_item = match &monkeys[index].operation {
Operation::Add(i) => *item + *i,
Operation::Multiply(i) => *item * *i,
Operation::MultiplyBySelf => *item * *item,
};
new_item /= 3;
items.push(new_item);
}
monkeys[index].actions += items.len();
for item in items {
let target = if item % monkeys[index].divisible_by == 0 {
monkeys[index].true_target
} else {
monkeys[index].false_target
};
monkeys[target].items.push(item);
}
monkeys[index].items.clear();
}
}
let mut scores = monkeys.into_iter().map(|m| m.actions).collect::<Vec<_>>();
scores.sort_unstable();
scores.reverse();
scores[0] * scores[1]
}
fn main() {
let input = fs::read_to_string("input.txt").unwrap();
println!("{:?}", do_the_thing(&input));
}
#[cfg(test)]
mod tests {
use super::*;
use test_case::test_case;
#[test_case("Monkey 0:
Starting items: 79, 98
Operation: new = old * 19
Test: divisible by 23
If true: throw to monkey 2
If false: throw to monkey 3
Monkey 1:
Starting items: 54, 65, 75, 74
Operation: new = old + 6
Test: divisible by 19
If true: throw to monkey 2
If false: throw to monkey 0
Monkey 2:
Starting items: 79, 60, 97
Operation: new = old * old
Test: divisible by 13
If true: throw to monkey 1
If false: throw to monkey 3
Monkey 3:
Starting items: 74
Operation: new = old + 3
Test: divisible by 17
If true: throw to monkey 0
If false: throw to monkey 1
" => 10605)]
fn test(input: &str) -> usize {
do_the_thing(&input)
}
}
|
fn main() {
let s1 = String::from("Hello World!");
let s2 = s1;
// println!("s1={}", s1)
let s3 = s2.clone();
println!("s2={},s3={}", s2, s3);
let s = String::from("Hello");
takes_ownership(s);
// println!("s={}",s);
let x = 5;
makes_copy(x);
let str1 = give_ownership();
println!("str1={}", str1);
let str2 = String::from("Hello!");
println!("str2={}", str2);
let str3 = take_and_give_back(str2);
println!("str3={}", str3);
// println!("str1={}๏ผstr2={},str3={}", str1, str2,str3);
let string1 = String::from("Hello!");
let len = calc_len(&string1);
println!("The length of {} is {}",string1, len);
let ss1 = String::from("Word!!!");
let mut ss2 = &ss1;
let ss3 = ss1;
ss2 = &ss3;
println!("{}", ss2);
let mut astr1 = String::from("A string");
// let mut s = String::from("hello");
let another_str = &mut astr1;
// let r1 = &mut s;
// println!("{}", another_str);
// another_str.push_str("oob");
// println!("{}", another_str);
// let third_string = &mut astr1;
// let r2 = &mut s;
// println!("{}, {}", r1, r2);
// println!("{}, {}", another_str, third_string);
let r = dangle();
}
fn dangle() -> String {
let s = String::from("Hello dangle");
s
}
fn calc_len(s: &String)->usize {
s.len()
}
fn takes_ownership(s: String){
println!("{}", s)
}
fn makes_copy(i: i32) {
println!("{}", i);
}
fn give_ownership() -> String {
let s = String::from("hello");
return s
}
fn take_and_give_back(s: String) -> String {
s
} |
use aoc_runner_derive::aoc_main;
aoc_main! { lib = advent_of_code }
|
use super::session::Session;
use super::tmux::*;
use crate::config::Config;
use fuzzy_matcher::skim::SkimMatcherV2;
use fuzzy_matcher::FuzzyMatcher;
use std::error::Error;
use tui::backend::Backend;
use tui::layout::Rect;
use tui::style::{Modifier, Style};
use tui::widgets::{Block, Borders, List, ListState, Text};
use tui::Frame;
enum Action {
Select,
Delete,
}
pub struct SessionList<'a> {
sessions: Vec<Session>,
filtered_sessions: Vec<Session>,
session_state: ListState,
last_search: String,
config: &'a Config,
}
impl SessionList<'_> {
pub fn new<'a>(config: &'a Config) -> Result<SessionList<'a>, Box<dyn Error>> {
let mut state = ListState::default();
state.select(Some(0));
let sessions = get_sessions(&config)?;
Ok(SessionList {
sessions: sessions.clone(),
filtered_sessions: sessions.clone(),
session_state: state,
last_search: String::from(""),
config,
})
}
pub fn draw<B: Backend>(&mut self, region: Rect, f: &mut Frame<B>) {
let sessions = self
.filtered_sessions
.iter()
.map(|x| Text::raw(format!("{}", x)));
let sessions = List::new(sessions)
.block(
Block::default()
.borders(Borders::ALL)
.title("Sessions")
.title_style(Style::default().fg(self.config.theme.get_session_list_border()))
.border_style(Style::default().fg(self.config.theme.get_session_list_border())),
)
.style(Style::default().fg(self.config.theme.get_session_foreground()))
.highlight_style(
Style::default()
.fg(self.config.theme.get_highlight_foreground())
.modifier(Modifier::BOLD),
)
.highlight_symbol(">");
f.render_stateful_widget(sessions, region, &mut self.session_state);
}
pub fn filter_sessions(&mut self, search: &String) {
if search.len() > 0 {
let matcher = SkimMatcherV2::default();
self.filtered_sessions = self
.sessions
.iter()
.cloned()
.filter(|x| matcher.fuzzy_match(&x.name, search).is_some())
.collect();
self.filtered_sessions
.push(Session::new(String::from(search), true));
} else {
self.filtered_sessions = self.sessions.clone()
}
if self.filtered_sessions.len() > 0 {
self.session_state.select(Some(0));
} else {
self.session_state.select(None);
}
self.last_search = search.clone();
}
pub fn select_session(&mut self) -> Result<(), Box<dyn Error>> {
self.do_selection(Action::Select)?;
Ok(())
}
pub fn delete_session(&mut self) -> Result<(), Box<dyn Error>> {
self.do_selection(Action::Delete)?;
Ok(())
}
pub fn next(&mut self) {
self.session_state.select(Some(
(self.session_state.selected().unwrap() + 1) % self.filtered_sessions.len(),
));
}
pub fn previous(&mut self) {
let index = self.session_state.selected().unwrap();
let selected = if index == 0 {
self.filtered_sessions.len() - 1
} else {
index - 1
};
self.session_state.select(Some(selected));
}
fn do_selection(&mut self, action: Action) -> Result<(), Box<dyn Error>> {
if self.session_state.selected().is_some() {
let selected = self
.filtered_sessions
.get(self.session_state.selected().unwrap())
.unwrap();
match action {
Action::Select => {
if selected.new {
new_session(&selected.name, true, self.config);
} else {
attach_session(&selected.name);
}
}
Action::Delete => {
delete_session(&selected.name);
self.sessions = get_sessions(self.config)?;
let last = self.last_search.clone();
self.filter_sessions(&last);
}
}
}
Ok(())
}
}
|
use std::str::FromStr;
#[derive(Debug, PartialEq, Clone)]
pub struct Token {
pub kind: TokenKind,
pub position: Position,
}
pub type Position = (usize, usize);
#[derive(Debug, PartialEq, Clone)]
pub enum TokenKind {
EOF,
Symbol(Symbol),
Comment(String),
IntLiteral(u64),
FloatLiteral(f64),
BooleanLiteral(Boolean),
Identifier(String),
Keyword(Keyword),
Type(Type),
StringLiteral(String),
CharLiteral(char),
EOL,
SEP,
}
#[derive(Debug, Eq, PartialEq, Clone, Copy, Hash)]
pub enum Symbol {
LParen,
RParen,
Arrow,
LCurly,
RCurly,
LBracket,
RBracket,
At,
Unit,
Assign,
Plus,
Minus,
Star,
Slash,
Ampersand,
Dollar,
Comma,
Colon,
Equal,
NotEqual,
Greater,
GreaterEqual,
Lower,
LowerEqual,
Not,
And,
Pipe,
Or,
Xor,
Modulo,
Dot,
DoDot,
GoDot,
}
impl From<Symbol> for String {
fn from(sym: Symbol) -> String {
match sym {
Symbol::Plus => String::from("+"),
Symbol::Minus => String::from("-"),
Symbol::Star => String::from("*"),
Symbol::Slash => String::from("/"),
Symbol::Not => String::from("!"),
Symbol::Equal => String::from("=="),
Symbol::NotEqual => String::from("!="),
Symbol::Greater => String::from(">"),
Symbol::GreaterEqual => String::from(">="),
Symbol::Lower => String::from("<"),
Symbol::LowerEqual => String::from("<="),
Symbol::Pipe => String::from("|"),
Symbol::Or => String::from("||"),
Symbol::Ampersand => String::from("&"),
Symbol::And => String::from("&&"),
Symbol::Xor => String::from("^"),
Symbol::Modulo => String::from("%"),
_ => panic!("Symbol to str {:?}", sym),
}
}
}
#[derive(Debug, Eq, PartialEq, Clone, Copy)]
pub enum Boolean {
True,
False,
}
#[derive(Debug, Eq, PartialEq, Clone, Copy)]
pub enum Keyword {
Fn,
Extern,
Var,
Val,
If,
Else,
Use,
Bool,
Record,
As,
Then,
Const,
Global,
Ret,
While,
Until,
Type,
Is,
Exp,
}
#[derive(Debug, Eq, PartialEq, Clone, Copy)]
pub enum Type {
Char,
Str,
I8,
I16,
I32,
I64,
U8,
U16,
U32,
U64,
F32,
F64,
}
macro_rules! to_tok {
($name:ident, $kind:ident, $ty:ident) => {
pub fn $name(val: &str) -> Option<TokenKind> {
match $ty::from_str(val) {
Ok(k) => Some(TokenKind::$kind(k)),
Err(_) => None,
}
}
};
}
macro_rules! from_tok {
($name:ident, $kind:ident, $res:ident) => {
pub fn $name(&self) -> Option<$res> {
match &self.kind {
TokenKind::$kind(res) => Some(res.clone()),
_ => None,
}
}
};
}
impl Token {
pub fn new(kind: TokenKind, position: Position) -> Self {
Self { kind, position }
}
to_tok!(keyword, Keyword, Keyword);
to_tok!(boolean, BooleanLiteral, Boolean);
to_tok!(r#type, Type, Type);
pub fn op(&self) -> Option<Symbol> {
if let TokenKind::Symbol(sym) = self.kind {
return match sym {
Symbol::Plus
| Symbol::Minus
| Symbol::Star
| Symbol::Slash
| Symbol::Equal
| Symbol::NotEqual
| Symbol::Greater
| Symbol::GreaterEqual
| Symbol::Lower
| Symbol::LowerEqual
| Symbol::Not
| Symbol::Ampersand
| Symbol::And
| Symbol::Pipe
| Symbol::Or
| Symbol::Xor
| Symbol::Modulo => Some(sym),
_ => None,
};
}
None
}
pub fn split_accessor(&self) -> Option<Vec<String>> {
match &self.kind {
TokenKind::Identifier(accessor) => {
match accessor.clone().split(".").collect::<Vec<_>>() {
acc => Some(acc.iter().map(|val| String::from(*val)).collect()),
}
}
_ => None,
}
}
from_tok!(kw, Keyword, Keyword);
from_tok!(bl, BooleanLiteral, Boolean);
from_tok!(sym, Symbol, Symbol);
from_tok!(int, IntLiteral, u64);
from_tok!(float, FloatLiteral, f64);
from_tok!(ident, Identifier, String);
from_tok!(ty, Type, Type);
from_tok!(st, StringLiteral, String);
from_tok!(comm, Comment, String);
from_tok!(ch, CharLiteral, char);
}
impl FromStr for Type {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"char" => Ok(Self::Char),
"str" => Ok(Self::Str),
"i8" => Ok(Self::I8),
"i16" => Ok(Self::I16),
"i32" => Ok(Self::I32),
"i64" => Ok(Self::I64),
"u8" => Ok(Self::U8),
"u16" => Ok(Self::U16),
"u32" => Ok(Self::U32),
"u64" => Ok(Self::U64),
"f32" => Ok(Self::F32),
"f64" => Ok(Self::F64),
_ => Err(()),
}
}
}
impl FromStr for Keyword {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"fn" => Ok(Self::Fn),
"extern" => Ok(Self::Extern),
"var" => Ok(Self::Var),
"val" => Ok(Self::Val),
"if" => Ok(Self::If),
"else" => Ok(Self::Else),
"use" => Ok(Self::Use),
"bool" => Ok(Self::Bool),
"rec" => Ok(Self::Record),
"as" => Ok(Self::As),
"then" => Ok(Self::Then),
"const" => Ok(Self::Const),
"global" => Ok(Self::Global),
"ret" => Ok(Self::Ret),
"while" => Ok(Self::While),
"until" => Ok(Self::Until),
"type" => Ok(Self::Type),
"is" => Ok(Self::Is),
"exp" => Ok(Self::Exp),
_ => Err(()),
}
}
}
impl FromStr for Boolean {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"true" => Ok(Self::True),
"false" => Ok(Self::False),
_ => Err(()),
}
}
}
|
use std::fmt;
struct MinMax(i64, i64);
impl fmt::Display for MinMax {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, {})", self.0, self.1)
}
}
struct Point2D {
x: f64,
y: f64,
}
impl fmt::Display for Point2D {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "x: {}, y: {}", self.x, self.y)
}
}
fn main() {
println!(
"The big range is {big} and the small is {small}.",
small = MinMax(-3, 3),
big = MinMax(-300, 300)
);
println!("{}", Point2D { x: 2.3, y: 9.2 });
}
|
extern crate env_logger;
use limn::prelude::*;
use limn::input::{EscKeyCloseHandler, DebugSettingsHandler};
use limn::resources;
use limn::resources::font::FontDescriptor;
use limn::draw::rect::RectStyle;
use limn::draw::text::TextStyle;
use limn::draw::ellipse::EllipseStyle;
use limn::widgets::slider::*;
pub fn default_style() {
let mut res = resources::resources();
res.font_loader.register_font_data(FontDescriptor::from_family("NotoSans"), include_bytes!("../../assets/fonts/NotoSans/NotoSans-Regular.ttf").to_vec()).unwrap();
res.theme.register_type_style(EllipseStyle::default());
res.theme.register_type_style(RectStyle::default());
res.theme.register_type_style(style!(TextStyle {
font: FontDescriptor::from_family("NotoSans"),
font_size: 24.0,
text_color: BLACK,
background_color: TRANSPARENT,
wrap: Wrap::Whitespace,
align: Align::Start,
}));
res.theme.register_class_prop_style("static_text", INACTIVE.clone(), style!(TextStyle {
text_color: GRAY_50,
}));
res.theme.register_class_style("list_item_rect", style!(RectStyle {
background_color: GRAY_30,
}));
res.theme.register_class_prop_style("list_item_rect", SELECTED.clone(), style!(RectStyle {
background_color: BLUE_HIGHLIGHT,
}));
res.theme.register_class_prop_style("list_item_rect", MOUSEOVER.clone(), style!(RectStyle {
background_color: GRAY_60,
}));
res.theme.register_class_style("list_item_text", style!(TextStyle {
text_color: WHITE,
}));
res.theme.register_class_style("button_rect", style!(RectStyle {
background_color: GRAY_80,
corner_radius: Some(5.0),
border: Some((1.0, GRAY_40)),
}));
res.theme.register_class_prop_style("button_rect", INACTIVE.clone(), style!(RectStyle {
background_color: GRAY_90,
border: Some((1.0, GRAY_70)),
}));
res.theme.register_class_prop_style("button_rect", ACTIVATED_PRESSED.clone(), style!(RectStyle {
background_color: GRAY_30,
}));
res.theme.register_class_prop_style("button_rect", ACTIVATED.clone(), style!(RectStyle {
background_color: GRAY_40,
}));
res.theme.register_class_prop_style("button_rect", PRESSED.clone(), style!(RectStyle {
background_color: GRAY_60,
}));
res.theme.register_class_prop_style("button_rect", MOUSEOVER.clone(), style!(RectStyle {
background_color: GRAY_90,
}));
res.theme.register_modifier_class_style("scrollbar_slider", style!(SliderStyle {
variable_handle_size: true,
handle_style: HandleStyle::Square,
bar_style: BarStyle::Wide,
border: None,
bar_color: GRAY_80,
handle_color: GRAY_70,
highlight: None,
width: 15.0,
}));
}
// Initialize a limn App with common handlers and set up logger
pub fn init(window_builder: glutin::WindowBuilder) -> App {
env_logger::init().unwrap();
let events_loop = glutin::EventsLoop::new();
let window = Window::new(window_builder, &events_loop);
let mut app = App::new(window, events_loop);
default_style();
// Closes app on ESC key
app.add_handler(EscKeyCloseHandler);
// Toggles debug bounds drawing on F1 key
app.add_handler(DebugSettingsHandler::new());
app
}
|
mod binary;
use std::cmp::Ordering;
pub fn solve_1() {
let max_seat_id = include_str!("input.txt")
.trim()
.lines()
.map(binary::parse)
.map(|instructions| binary::seat_id(binary::calculate_seat(&instructions)))
.max()
.unwrap();
println!("Max seat ID of all boarding passes: {}", max_seat_id);
}
pub fn solve_2() {
let mut seats: Vec<_> = include_str!("input.txt")
.trim()
.lines()
.map(binary::parse)
.map(|instructions| binary::calculate_seat(&instructions))
.collect();
seats.sort_by(|a, b| match a.y.cmp(&b.y) {
Ordering::Equal => a.x.cmp(&b.x),
other => other,
});
let found = (|seats: Vec<binary::Seat>| {
let mut iter = seats.iter().peekable();
while let (Some(&seat), Some(&&next)) = (iter.next(), iter.peek()) {
if seat.y == next.y {
if seat.x + 1 == next.x {
// Continuous
} else {
return binary::Seat {
x: seat.x + 1,
y: seat.y,
};
}
} else if seat.y + 1 == next.y {
if seat.x == 8 && next.x == 0 {
// Continuous
} else if seat.x == 6 && next.x == 0 {
return binary::Seat { x: 7, y: seat.y };
} else if seat.x == 7 && next.x == 2 {
return binary::Seat { x: 0, y: next.y };
}
} else {
panic!("Weird ordering: {:?}, {:?}", seat, next);
}
}
panic!("Really should have found a seat.");
})(seats);
println!(
"Found my seat: {:?} with ID {}.",
found,
binary::seat_id(found)
);
}
|
use iced::{Element, Sandbox, Settings, Text};
pub fn main() -> iced::Result {
Hello::run(Settings::default())
}
struct Hello;
impl Sandbox for Hello {
type Message = ();
fn new() -> Hello {
Hello
}
fn title(&self) -> String {
String::from("A moldy application")
}
fn update(&mut self, _message: Self::Message) {
// This application has no interactions
}
fn view(&mut self) -> Element<Self::Message> {
Text::new("Hello, world!!").into()
}
}
|
use common::result::Result;
use crate::application::dtos::{AuthorDto, CategoryDto, PublicationDto};
use crate::domain::author::{AuthorId, AuthorRepository};
use crate::domain::category::CategoryRepository;
use crate::domain::publication::PublicationRepository;
pub struct GetById<'a> {
author_repo: &'a dyn AuthorRepository,
category_repo: &'a dyn CategoryRepository,
publication_repo: &'a dyn PublicationRepository,
}
impl<'a> GetById<'a> {
pub fn new(
author_repo: &'a dyn AuthorRepository,
category_repo: &'a dyn CategoryRepository,
publication_repo: &'a dyn PublicationRepository,
) -> Self {
GetById {
author_repo,
category_repo,
publication_repo,
}
}
pub async fn exec(&self, author_id: String) -> Result<AuthorDto> {
let author_id = AuthorId::new(author_id)?;
let author = self.author_repo.find_by_id(&author_id).await?;
let publications = self.publication_repo.find_by_author_id(&author_id).await?;
let mut publication_dtos = Vec::new();
for publication in publications.iter() {
let category = self
.category_repo
.find_by_id(publication.header().category_id())
.await?;
publication_dtos
.push(PublicationDto::from(publication).category(CategoryDto::from(&category)));
}
Ok(AuthorDto::from(&author).publications(publication_dtos))
}
}
|
use alloc::{collections::BTreeMap, vec::Vec};
use core::{
cmp::{max, Ordering},
fmt::Debug,
hash::{Hash, Hasher},
ops::{Bound, Index, RangeBounds},
};
use crate::segment::{Segment, Start};
pub(crate) use key::Key;
pub mod iterators;
mod key;
#[cfg(test)]
mod tests;
/// # SegmentMap
///
/// A map of non-overlapping ranges to values. Inserted ranges will be merged
/// with adjacent ranges if they have the same value.
///
/// Internally, [`SegmentMap`] is represented by a [`BTreeMap`] in which the keys
/// are represented by a concrete [`Range`] type, sorted by their start values.
///
/// # Examples
///
/// TODO
///
/// # Entry API
///
/// TODO
///
#[derive(Clone)]
pub struct SegmentMap<K, V> {
pub(crate) map: BTreeMap<Key<K>, V>,
/// Reuseable storage for working set of keys
/// (many insertions/deletions will allocate less)
///
/// TODO Performance Improvement:
/// This (and successor key collection) could be more streamlined with a
/// few strategically placed `unsafe` blocks
pub(crate) store: Vec<Key<K>>,
}
impl<K, V> SegmentMap<K, V> {
/// Makes a new, empty `SegmentMap`.
///
/// Does not allocate anything on its own.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use segmap::*;
/// let mut map = SegmentMap::new();
///
/// // entries can now be inserted into the empty map
/// map.insert(0..1, "a");
/// ```
pub fn new() -> Self
where
K: Ord,
{
SegmentMap {
map: BTreeMap::new(),
store: Vec::new(),
}
}
/// Makes a new, empty [`SegmentMap`] with a value for the full range.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use segmap::*;
/// let mut map = SegmentMap::with_value(true);
///
/// // All values will return something
/// assert_eq!(map[&0], true);
/// assert_eq!(map[&10], true);
/// assert_eq!(map[&12345678], true);
/// ```
pub fn with_value(value: V) -> Self
where
K: Ord,
{
let mut inner = BTreeMap::new();
inner.insert(Key(Segment::full()), value);
SegmentMap {
map: inner,
store: Vec::new(),
}
}
/// Clears the map, removing all elements.
///
/// This also resets the capacity of the internal `store`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use segmap::*;
/// let mut a = SegmentMap::new();
/// a.insert(0..1, "a");
/// a.clear();
/// assert!(a.is_empty());
/// ```
pub fn clear(&mut self) {
self.map.clear();
self.store = Vec::new(); // Reset capacity
}
/// Resets the capacity of `store`
pub fn shrink_to_fit(&mut self) {
self.store = Vec::new(); // Reset capacity
}
/// Returns a reference to the value corresponding to the given point,
/// if the point is covered by any range in the map.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use segmap::*;
/// let mut map = SegmentMap::new();
/// map.insert(0..1, "a");
/// assert_eq!(map.get(&0), Some(&"a"));
/// assert_eq!(map.get(&2), None);
/// ```
pub fn get(&self, at: &K) -> Option<&V>
where
K: Clone + Ord,
{
self.get_range_value(at).map(|(_range, value)| value)
}
/// Returns the range-value pair (as a pair of references) corresponding
/// to the given point, if the point is covered by any range in the map.
///
/// # Examples
///
/// ```
/// # use segmap::*;
/// let mut map = SegmentMap::new();
/// map.insert(0..1, "a");
/// assert_eq!(map.get_range_value(&0), Some((&Segment::from(0..1), &"a")));
/// assert_eq!(map.get_range_value(&2), None);
/// ```
pub fn get_range_value(&self, at: &K) -> Option<(&Segment<K>, &V)>
where
K: Clone + Ord,
{
// The only stored range that could contain the given key is the
// last stored range whose start is less than or equal to this key.
self.map
.range(..=(Start(Bound::Included(at.clone()))))
.rev()
.map(|(w, v)| (&w.0, v))
.next()
.filter(|(range, _)| range.contains(at))
}
// TODO: entry api for get_range_value_mut (since we can't control when &mut V is changed to do a merge/coalesce)
/// Returns `true` if any range in the map covers the specified point.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use segmap::*;
/// let mut map = SegmentMap::new();
/// map.insert(0..1, "a");
/// assert_eq!(map.contains(&0), true);
/// assert_eq!(map.contains(&2), false);
/// ```
pub fn contains(&self, point: &K) -> bool
where
K: Clone + Ord,
{
self.get_range_value(point).is_some()
}
/// Get the widest bounds covered by the ranges in this map
///
/// **NOTE**: This is not necessarily (or likely) a contiguous range!
/// # Examples
///
/// ```
/// # use segmap::*;
/// let mut map = SegmentMap::new();
/// map.insert(0..9, "a");
/// map.insert(15..30, "b");
/// map.insert(35..90, "c");
///
/// assert_eq!(map.bounds(), Some(Segment::from(0..90).as_ref()));
/// ```
pub fn bounds(&self) -> Option<Segment<&K>> {
let mut iter = self.map.iter();
iter.next().map(|(first, _)| {
if let Some((last, _)) = iter.next_back() {
// 2 or more items, use widest possible bounds
Segment {
start: first.0.start.as_ref(),
end: last.0.end.as_ref(),
}
} else {
// 1 item, use it's bounds
first.0.as_ref()
}
})
}
/// Get the lowest bound covered by the ranges in this map
///
/// # Examples
///
/// ```
/// # use segmap::*;
/// let mut map = SegmentMap::new();
/// map.insert(0..9, "a");
/// map.insert(15..30, "b");
/// map.insert(35..90, "c");
///
/// assert_eq!(map.lower_bound(), Some(&Bound::Included(0)));
/// ```
pub fn lower_bound(&self) -> Option<&Bound<K>> {
self.map.iter().next().map(|(range, _)| &range.0.start.0)
}
/// Get the highest bound covered by the ranges in this map
///
/// # Examples
///
/// ```
/// # use segmap::*;
/// let mut map = SegmentMap::new();
/// map.insert(0..9, "a");
/// map.insert(15..30, "b");
/// map.insert(35..90, "c");
///
/// assert_eq!(map.upper_bound(), Some(&Bound::Excluded(90)));
/// ```
pub fn upper_bound(&self) -> Option<&Bound<K>> {
self.map.iter().next_back().map(|(range, _)| &range.0.end.0)
}
/// Retains only the elements specified by the predicate.
///
/// In other words, remove all pairs `(k, v)` such that `f(&k, &mut v)`
/// returns `false`.
///
/// # Examples
///
/// ```
/// # use segmap::*;
/// let mut map = SegmentMap::new();
/// map.set(0..5, true);
/// map.set(5..10, false);
/// map.set(10..15, true);
/// map.set(15..20, false);
/// map.set(20..25, true);
///
/// // Keep only the ranges with even numbered starts
/// map.retain(|k, _| k.start_value().unwrap() % 2 == 0);
///
/// assert!(map[&0] == true);
/// assert!(map[&10] == true);
/// assert!(map[&12] == true);
/// assert!(map[&20] == true);
/// assert!(map[&24] == true);
///
/// assert!(map.get(&15).is_none());
/// ```
///
pub fn retain<F>(&mut self, mut f: F)
where
K: Ord,
F: FnMut(&Segment<K>, &mut V) -> bool,
{
self.map.retain(|k, v| f(&k.0, v))
}
/// Insert a value for the specified range
///
/// If the inserted range completely overlaps any existing range in the map,
/// the existing range (or ranges) will be replaced by the inserted range.
///
/// If the inserted range partially overlaps any existing range in the map,
/// the existing ranges will be truncated to non-overlapping regions.
///
/// If the inserted range overlaps or is touching an existing range that
/// maps to the same value, the ranges will be merged into one contiguous
/// range
///
/// # Returns
///
/// Much like other maps ([`BTreeMap::insert`] or [`HashMap::insert`]),
/// insert returns the overwritten values (if any existed). Because multiple
/// ranges might be overwritten, another map will be constructed with those
/// values.
///
/// **Note**: This will allocate a new underlying [`SegmentMap`], though, so an
/// option is used in case no ranges were overwritten. If you don't care
/// about the overwritten values, use [`SegmentMap::set_range`] instead.
///
/// # Examples
///
/// ## Basic Usage
///
/// ```
/// # use segmap::*;
/// let mut map = SegmentMap::new();
/// map.insert(0..4, "a");
/// assert_eq!(map.is_empty(), false);
///
/// map.insert(2..6, "b");
/// assert_eq!(map[&1], "a");
/// assert_eq!(map[&3], "b");
/// ```
///
/// ## Overwriting
///
/// ```
/// # use segmap::*;
/// let mut map = SegmentMap::new();
/// map.insert(0..10, "a");
/// let out = map.insert(3..6, "b").unwrap();
///
/// assert_eq!(map[&2], "a");
/// assert_eq!(map[&4], "b");
/// assert_eq!(map[&7], "a");
/// assert!(out.into_iter().eq(vec![(Segment::from(3..6), "a")]));
///
/// ```
///
/// ## Coalescing
///
/// ```
/// # use segmap::*;
/// let mut map = SegmentMap::new();
/// map.insert(0..10, "a");
/// map.insert(10..20, "a");
///
/// assert!(map.into_iter().eq(vec![(Segment::from(0..20), "a")]));
///
/// ```
///
/// # See Also
///
/// - [`SegmentMap::set`] if you don't want to return the values
/// overwritten
/// - [`SegmentMap::insert_if_empty`] if you only want to insert the value if
/// no overlaps occur
/// - [`SegmentMap::insert_in_gaps`] if you only want to insert the value for
/// the empty parts of the range, not overwriting any values.
///
pub fn insert<R>(&mut self, range: R, value: V) -> Option<Self>
where
R: core::ops::RangeBounds<K>,
K: Clone + Ord,
V: Clone + Eq,
{
// assert!(range.start_bound() <= range.end_bound());
let range = Segment::from(&range);
let mut removed_ranges = MaybeMap::Uninitialized;
self.insert_internal(range, value, &mut removed_ranges);
removed_ranges.into()
}
/// Set a value for the specified range, overwriting any existing subset
/// ranges. This is the same as [`SegmentMap::insert`], but without a return
/// value, so overlapping ranges will be truncated and adjacent ranges with
/// the same value will be merged.
///
/// # Examples
///
/// ## Basic Usage
///
/// ```
/// # use segmap::*;
/// let mut map = SegmentMap::new();
/// map.set(0..4, "a");
/// assert_eq!(map.is_empty(), false);
///
/// map.set(2..6, "b");
/// assert_eq!(map[&1], "a");
/// assert_eq!(map[&3], "b");
/// ```
///
/// ## Overwriting
///
/// ```
/// # use segmap::*;
/// let mut map = SegmentMap::new();
/// map.set(0..10, "a");
/// map.set(3..6, "b");
///
/// assert_eq!(map[&2], "a");
/// assert_eq!(map[&4], "b");
/// assert_eq!(map[&7], "a");
///
/// ```
///
/// ## Coalescing
///
/// ```
/// # use segmap::*;
/// let mut map = SegmentMap::new();
/// map.set(0..10, "a");
/// map.set(10..20, "a");
///
/// assert!(map.into_iter().eq(vec![(Segment::from(0..20), "a")]))
///
/// ```
///
/// # See Also
///
/// - [`SegmentMap::insert`] if you want the value overwritten
/// - [`SegmentMap::insert_if_empty`] if you only want to insert the value if
/// no overlaps occur
/// - [`SegmentMap::insert_in_gaps`] if you only want to insert the value for
/// the empty parts of the range, not overwriting any values.
///
pub fn set<R>(&mut self, range: R, value: V)
where
R: core::ops::RangeBounds<K>,
K: Clone + Ord,
V: Clone + Eq,
{
let range = Segment::from(&range);
let mut removed_ranges = MaybeMap::Never;
self.insert_internal(range, value, &mut removed_ranges);
}
/// Insert a value into the map, only if there are no existing overlapping
/// ranges. Returns the given value if it wasn't inserted.
///
/// # Examples
///
/// ```
/// # use segmap::*;
/// let mut map = SegmentMap::new();
/// assert!(map.insert_if_empty(0..5, true).is_none());
/// assert!(map.insert_if_empty(5..10, true).is_none());
/// assert!(map.insert_if_empty(3..6, true).is_some());
///
/// ```
///
/// # See Also
///
/// - [`SegmentMap::insert`] or [`SegmentMap::set`] if you want to overwrite
/// existing values
/// - [`SegmentMap::insert_in_gaps`] if you only want to insert the value for
/// the empty parts of the range
///
pub fn insert_if_empty<R>(&mut self, range: R, value: V) -> Option<V>
where
R: core::ops::RangeBounds<K>,
K: Clone + Ord,
V: Clone + Eq,
{
// Get the ranges before and after this one
let range = Segment::from(&range);
// Check for any overlaps
let overlapped = if let Some(upper_bound) = range.end.after() {
self.map.range(..=upper_bound.cloned())
} else {
self.map.range::<Key<K>, _>(..)
}
.rev()
.take_while(|(k, _)| k.0.overlaps(&range))
.next()
.is_none();
// If no overlaps, we can insert directly into the map
if overlapped {
self.map.insert(Key(range), value);
None
} else {
Some(value)
}
}
/// Insert a value for empty regions (gaps) in the specified range. If
/// values exist for ranges overlapping this range, those values will be
/// preserved. As such, this method may add multiple ranges for the given
/// value.
///
/// # Examples
///
/// ```
/// # use segmap::*;
/// let mut map = SegmentMap::new();
/// map.set(5..10, "a");
/// map.set(15..20, "a");
/// map.insert_in_gaps(0..30, "b");
///
/// assert!(map.into_iter().eq(vec![
/// (Segment::from(0..5), "b"),
/// (Segment::from(5..10), "a"),
/// (Segment::from(10..15), "b"),
/// (Segment::from(15..20), "a"),
/// (Segment::from(20..30), "b"),
/// ]));
///
/// ```
///
/// # See Also
///
/// - [`SegmentMap::insert`] or [`SegmentMap::set`] if you want to overwrite
/// existing values
/// - [`SegmentMap::insert_if_empty`] if you only want to insert the value if
/// no overlaps occur
/// - [`SegmentMap::with_value`] if you'd instead like to construct your map
/// with a default value for all possible ranges
///
pub fn insert_in_gaps<R>(&mut self, range: R, value: V)
where
R: core::ops::RangeBounds<K>,
K: Clone + Ord,
V: Clone + Eq,
{
let mut range = Segment::from(&range);
// In case this is an empty map, exit early
if self.map.is_empty() {
self.map.insert(Key(range), value);
return;
}
// Similar to insert, we need to see if any preceeding ranges overlap
// or touch this one
let leftmost = self
.map
.range(..=range.start.clone())
.rev()
.take_while(|(r, _)| r.0.touches(&range))
.last()
.map(|(k, v)| (k.clone(), v));
if let Some((leftmost_touching_range, leftmost_touching_value)) = leftmost {
// And merge if they have the same value
if value.eq(leftmost_touching_value) {
range.start = leftmost_touching_range.0.start.clone(); // Min is implied
if leftmost_touching_range.0.end > range.end {
range.end = leftmost_touching_range.0.end.clone();
}
self.map.remove(&leftmost_touching_range);
} else if leftmost_touching_range.0.end < range.end {
// If this range extends past the end of the previous range,
// truncate this range.
range.start = leftmost_touching_range.0.bound_after().unwrap().cloned();
} else {
// Otherwise, we've exhausted the insertion range and don't need
// to add anything
return;
}
}
// Get successors of this insertion range. Both are treated the same
// (unlike in insert)
self.store.clear();
self.store.extend(
if let Some(bound_after) = range.bound_after().map(|b| b.cloned()) {
self.map.range(range.start.clone()..=bound_after)
} else {
self.map.range(range.start.clone()..)
}
.map(|(k, _)| k.clone()),
);
// Keep marching along the insertion range and insert gaps as we find them
for successor in self.store.drain(..) {
let successor_value = self.map.get(&successor).unwrap();
// If we can merge ranges, do so
if value.eq(successor_value) {
let (removed_range, _) = self.map.remove_entry(&successor).unwrap();
range.end = max(removed_range.0.end, range.end);
} else {
// Otherwise, we may need to insert a gap. We can only
// insert if the range starts before the successor
// (it shouldn't ever by greater, but could be equal)
if successor.0.start > range.start {
self.map.insert(
Key(Segment {
start: range.start.clone(),
end: successor
.0
.bound_before()
.expect("Unexpected unbounded start")
.cloned(),
}),
value.clone(),
);
}
// After inserting the gap, move the start of the range to
// the end of this successor, if it exists. If not, this
// successor extends to the end and we're done.
if let Some(next_gap_start) = successor.0.bound_after() {
range.start = next_gap_start.cloned();
} else {
// Shouldn't actually be necessary, as it would be the last itme
break;
}
}
}
// Any leftover range can then be inserted as a "last gap"
self.map.insert(Key(range), value);
}
/// Remove all values in a given range, returning the removed values.
/// Overlapping ranges will be truncated at the bounds of this range.
///
/// **Note**: This will allocate another [`SegmentMap`] for returning the
/// removed ranges, so if you don't care about them, use
/// [`SegmentMap::clear_range`] instead
///
/// # Examples
///
/// ```
/// # use segmap::*;
/// let mut map = SegmentMap::new();
/// map.insert(0..=10, 5);
/// let removed = map.remove(2..4).unwrap();
///
/// assert_eq!(map[&0], 5);
/// assert!(map.get(&2).is_none());
/// assert!(map.get(&3).is_none());
/// assert_eq!(map[&4], 5);
/// assert_eq!(map[&10], 5);
///
/// assert_eq!(removed[&2], 5);
/// assert_eq!(removed[&3], 5);
/// ```
///
/// # See Also
///
/// - [`SegmentMap::clear_range`] if you don't care about the removed values
///
pub fn remove<R: core::ops::RangeBounds<K>>(&mut self, range: R) -> Option<Self>
where
K: Clone + Ord,
V: Clone,
{
let mut removed_ranges = MaybeMap::Uninitialized;
self.remove_internal(Segment::from(&range), &mut removed_ranges);
removed_ranges.into()
}
// Unset all values in a given range. Overlapping ranges will be truncated at the bounds of this range
/// Remove all values in a given range. Overlapping ranges will be truncated
/// at the bounds of this range.
///
/// # Examples
///
/// ```
/// # use segmap::*;
/// let mut map = SegmentMap::new();
/// map.insert(0..=10, 5);
/// map.clear_range(2..4);
///
/// assert_eq!(map[&0], 5);
/// assert!(map.get(&2).is_none());
/// assert!(map.get(&3).is_none());
/// assert_eq!(map[&4], 5);
/// assert_eq!(map[&10], 5);
/// ```
///
/// # See Also
///
/// - [`SegmentMap::remove`] if you want the removed values
///
pub fn clear_range<R: core::ops::RangeBounds<K>>(&mut self, range: R)
where
K: Clone + Ord,
V: Clone,
{
let mut removed_ranges = MaybeMap::Never;
self.remove_internal(Segment::from(&range), &mut removed_ranges);
}
/// Moves all elements from `other` into `Self`, leaving `other` empty.
///
/// Note thate `V` must be `Clone` in case any ranges need to be split
///
/// # Examples
///
/// ```
/// # use segmap::*;
/// let mut a = SegmentMap::new();
/// a.insert(0..1, "a");
/// a.insert(1..2, "b");
/// a.insert(2..3, "c");
///
/// let mut b = SegmentMap::new();
/// b.insert(2..3, "d");
/// b.insert(3..4, "e");
/// b.insert(4..5, "f");
///
/// a.append(&mut b);
///
/// assert_eq!(a.len(), 5);
/// assert_eq!(b.len(), 0);
///
/// assert_eq!(a[&0], "a");
/// assert_eq!(a[&1], "b");
/// assert_eq!(a[&2], "d");
/// assert_eq!(a[&3], "e");
/// assert_eq!(a[&4], "f");
/// ```
pub fn append(&mut self, other: &mut Self)
where
K: Clone + Ord,
V: Clone + Eq,
{
// self.bounds().is_none() implies an empty map
match (self.bounds(), other.bounds()) {
// Other is empty, nothing to append
(_, None) => {
// NoOp
}
// Self is empty, swap it with other
(None, _) => core::mem::swap(self, other),
// Overlapping ranges, we must insert each range in other
(Some(a), Some(b)) if a.overlaps(&b) => {
for (range, value) in core::mem::take(&mut other.map) {
self.set(range.0, value)
}
}
// If there isn't any overlap, we can safely insert all of the
// items in other directly into the inner map
(Some(_), Some(_)) => {
for (range, value) in core::mem::take(&mut other.map) {
self.map.insert(range, value);
}
}
}
}
/// Split the map into two at the given bound. Returns everything including
/// and after that bound.
///
/// # Examples
///
/// # Basic Usage
///
/// ```
/// # use segmap::*;
/// let mut a = SegmentMap::new();
/// a.insert(0..1, "a");
/// a.insert(1..2, "b");
/// a.insert(2..3, "c");
/// a.insert(3..4, "d");
///
/// let b = a.split_off(Bound::Included(2));
///
/// assert!(a.into_iter().eq(vec![
/// (Segment::from(0..1), "a"),
/// (Segment::from(1..2), "b"),
/// ]));
/// assert!(b.into_iter().eq(vec![
/// (Segment::from(2..3), "c"),
/// (Segment::from(3..4), "d"),
/// ]));
/// ```
///
/// ## Mixed Bounds
///
/// ```
/// # use segmap::*;
/// let mut a = SegmentMap::new();
/// a.insert(0..1, "a");
/// a.insert(1..2, "b");
/// a.insert(2..3, "c");
/// a.insert(3..4, "d");
/// a.insert(4..5, "e");
/// a.insert(5..6, "f");
/// a.insert(6..7, "g");
///
/// let c = a.split_off(Bound::Excluded(4));
/// let b = a.split_off(Bound::Included(2));
///
/// assert_eq!(a.len(), 2);
/// assert_eq!(b.len(), 3);
/// assert_eq!(c.len(), 3);
///
/// assert_eq!(a[&0], "a");
/// assert_eq!(a[&1], "b");
/// assert!(a.get(&2).is_none());
///
/// assert!(b.get(&1).is_none());
/// assert_eq!(b[&2], "c");
/// assert_eq!(b[&3], "d");
/// assert_eq!(b[&4], "e");
/// assert!(b.get(&5).is_none());
///
/// // `c` also has a a range (4, 5), which is inaccessible with integers.
/// // if we were using floats, `c[4.5]` would be `"e"`.
/// assert!(c.get(&4).is_none());
/// assert_eq!(c[&5], "f");
/// assert_eq!(c[&6], "g");
/// assert!(c.get(&7).is_none());
/// ```
///
pub fn split_off(&mut self, at: Bound<K>) -> Self
where
K: Clone + Ord,
V: Clone,
{
let at = Start(at);
if self.is_empty() {
return Self::new();
}
// Split non-overlapping items
let mut other = self.map.split_off(&at);
// If there are still items in the lower map, check if the last range
// crosses the boundary into the upper map
// No split should be necessary if `at` is unbounded
if let Some(split_range) = self.map.iter().next_back().map(|(k, _)| k.clone()) {
// These should all be together and available if there's a split
if let Some((left_end, at_value)) = at.before().zip(at.value()) {
if split_range.0.contains(at_value) {
// This should always unwrap, because we know the key exists
let value = self.map.remove(&split_range).unwrap();
// Reinsert truncated range in each
self.map.insert(
Key(Segment {
start: split_range.0.start.clone(),
end: left_end.cloned(),
}),
value.clone(),
);
other.insert(
Key(Segment {
start: at.clone(),
end: split_range.0.end,
}),
value,
);
}
}
}
Self {
map: other,
store: Vec::new(),
}
}
// TODO: split_off_range
// /// Split the map into two, removing from `self` and returning everything in the given range
// pub fn split_off_range<R>(&mut self, range: R) where R: RangeBounds, K: Clone + Ord, V: Clone {
// }
/// Internal implementation for [`insert`], [`set`], and similar
fn insert_internal(
&mut self,
mut range: Segment<K>,
value: V,
removed_ranges: &mut MaybeMap<K, V>,
) where
K: Clone + Ord,
V: Clone + Eq,
{
// In case this is an empty map, exit early
if self.map.is_empty() {
self.map.insert(Key(range), value);
return;
}
// Get ranges starting at or before the new range that touch it. The
// iterator here should yeild:
// - None if no ranges touch the new range
// - The first previous range that touches or overlaps the new range
// - The range two previous if the new range starts right at a previous
// range (overlapping at the start) and touches one more previous range
// (like 0..3, 3..5, when inserting 3..4)
//
// We want to have the leftmost touching range (rather than just
// overlapping) in case we can combine the ranges when they have equal
// values
let leftmost = self
.map
.range(..=range.start.clone())
.rev()
.take_while(|(r, _)| r.0.touches(&range))
.last()
.map(|(k, v)| (k.clone(), v));
if let Some((leftmost_touching_range, leftmost_touching_value)) = leftmost {
if value.eq(leftmost_touching_value) {
// Remove the touching range and use it's start value (and maybe
// it's end, in the case of an overlap)
range.start = leftmost_touching_range.0.start.clone(); // Min is implied
if leftmost_touching_range.0.end > range.end {
range.end = leftmost_touching_range.0.end.clone();
}
self.map.remove(&leftmost_touching_range);
} else if range.overlaps(&leftmost_touching_range.0) {
// Split an overlapping range to preserve non-overlapped values
self.split_key(&leftmost_touching_range, &range, removed_ranges);
}
// Otherwise, touches (with a different value) but doesn't overlap,
// leave the existing range alone.
}
// After making the adjustment above, are there any following ranges
// that overlap with the new range?
//
// Or, following ranges that touch the end of this range (thus, bound_after)
//
// If there is no bound after the inserted range (i.e. the new range is
// unbounded on the right), all successor ranges can just be removed.
if let Some(bound_after) = range.bound_after().map(|b| b.cloned()) {
// Just store keys, so we don't clone values
self.store.clear();
self.store.extend(
self.map
.range(range.start.clone()..=bound_after.clone())
.map(|(k, _)| k.clone()),
);
for successor in self.store.drain(..) {
if let alloc::collections::btree_map::Entry::Occupied(entry) =
self.map.entry(successor)
{
if entry.get().eq(&value) {
// If values are the same, merge the ranges (and don't
// consider the successor part removed).
//
// For merging, we don't care if this is a touching or
// overlapping range, just that we may need to extend the
// end of the inserted range to merge with it.
let (successor, _) = entry.remove_entry();
if successor.0.end > range.end {
range.end = successor.0.end;
}
} else if entry.key().0.start < bound_after {
// Otherwise, if the range is overlapping (not just
// touching), it will need to be partially or fully removed
let (mut successor, successor_value) = entry.remove_entry();
// If overlapping, we need to split and reinsert it
if successor.0.end > range.end {
self.map.insert(
Key(Segment {
start: bound_after,
end: core::mem::replace(
&mut successor.0.end,
range.end.clone(),
),
}),
successor_value.clone(),
);
removed_ranges.insert(successor, successor_value);
break;
} else {
// Store the removed portion
removed_ranges.insert(successor, successor_value);
}
}
// Otherwise (touching and different value), leave the successor alone
}
}
} else {
// No upper bound, all following ranges are removed or merged
let successors = self
.map
.range(range.start.clone()..)
.map(|(k, _)| k.clone())
.collect::<alloc::vec::Vec<_>>();
for successor in successors {
let v = self.map.remove(&successor).unwrap();
if value != v {
removed_ranges.insert(successor, v);
}
}
}
// Finally, insert the new range and return the removed ranges
self.map.insert(Key(range), value);
}
/// Remove a specified range (`range_to_remove`) from an area of the map
/// overlapped by the range defined by `key`.
///
/// This is a helper function designed for use in `insert_internal`
/// and `remove_internal`. This method does no checking for overlaps, and
/// assumes that the ranges do!
fn split_key(
&mut self,
key: &Key<K>,
range_to_remove: &Segment<K>,
removed_ranges: &mut MaybeMap<K, V>,
) where
K: Clone + Ord,
V: Clone,
{
// Unwrap here is fine, since the callers of this should have already
// determined that the key exists
let (mut removed_range, value) = self.map.remove_entry(key).unwrap();
// Insert a split of the range to the left (if necessary)
if removed_range.0.start < range_to_remove.start {
self.map.insert(
Key(Segment {
start: core::mem::replace(
&mut removed_range.0.start,
range_to_remove.start.clone(),
),
end: range_to_remove.bound_before().unwrap().cloned(), // From above inequality, this must not be unbound
}),
value.clone(),
);
}
// Insert a split of the range to the right (if necessary)
if removed_range.0.end > range_to_remove.end {
self.map.insert(
Key(Segment {
start: range_to_remove.bound_after().unwrap().cloned(), // same as above
end: core::mem::replace(&mut removed_range.0.end, range_to_remove.end.clone()),
}),
value.clone(),
);
}
removed_ranges.insert(removed_range, value);
}
pub(crate) fn remove_internal(&mut self, range: Segment<K>, removed_ranges: &mut MaybeMap<K, V>)
where
K: Clone + Ord,
V: Clone,
{
// Return early if we can
if self.map.is_empty() {
return;
}
// Get the first range before this one
let previous_range = self
.map
.range(..=range.start.clone())
.rev()
.next()
.map(|(k, _)| k.clone());
if let Some(previous_range) = previous_range {
// Split an overlapping range to preserve non-overlapped values
if range.overlaps(&previous_range.0) {
self.split_key(&previous_range, &range, removed_ranges);
}
}
// Check if there are any ranges starting inside the range to remove.
// Unlike insert, we don't care about touching ranges because we
// won't be merging them.
self.store.clear();
self.store.extend(
if let Some(after) = range.bound_after().map(|b| b.cloned()) {
self.map.range(range.start.clone()..=after)
} else {
self.map.range(range.start.clone()..)
}
.map(|(k, _)| k.clone()),
);
for mut successor in self.store.drain(..) {
let value = self.map.remove(&successor).unwrap();
// Must be the last range
if successor.0.end > range.end {
self.map.insert(
Key(Segment {
start: range.bound_after().unwrap().cloned(), // Implicitly not none due to less than successor end
end: successor.0.end.clone(),
}),
value.clone(),
);
successor.0.end = range.end;
removed_ranges.insert(successor, value);
break;
} else {
removed_ranges.insert(successor, value);
}
}
}
}
// We can't just derive this automatically, because that would
// expose irrelevant (and private) implementation details.
// Instead implement it in the same way that the underlying BTreeMap does.
impl<K: Debug, V: Debug> Debug for SegmentMap<K, V>
where
K: Ord + Clone,
V: Eq + Clone,
{
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_map().entries(self.iter()).finish()
}
}
impl<K: Hash, V: Hash> Hash for SegmentMap<K, V> {
fn hash<H: Hasher>(&self, state: &mut H) {
for elt in self {
elt.hash(state);
}
}
}
impl<K: Ord, V> Default for SegmentMap<K, V> {
fn default() -> Self {
Self::new()
}
}
impl<K: PartialEq, V: PartialEq> PartialEq for SegmentMap<K, V> {
fn eq(&self, other: &Self) -> bool {
self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a == b)
}
}
impl<K: Eq, V: Eq> Eq for SegmentMap<K, V> {}
impl<K: PartialOrd + Ord, V: PartialOrd> PartialOrd for SegmentMap<K, V> {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.map.iter().partial_cmp(other.map.iter())
}
}
impl<K: Ord, V: Ord> Ord for SegmentMap<K, V> {
#[inline]
fn cmp(&self, other: &Self) -> Ordering {
self.map.iter().cmp(other.map.iter())
}
}
impl<K, V> Index<&K> for SegmentMap<K, V>
where
K: Clone + Ord,
V: Eq + Clone,
{
type Output = V;
/// Returns a reference to the value corresponding to the supplied key.
///
/// # Panics
///
/// Panics if the key is not present in the `SegmentMap`.
#[inline]
fn index(&self, key: &K) -> &V {
self.get(key).expect("no entry found for key")
}
}
pub(crate) enum MaybeMap<K, V> {
// Never do anything
Never,
// Hold whether the map would contain elements
None,
Some,
// Hold actual elements
Uninitialized,
Map(BTreeMap<Key<K>, V>),
}
impl<K: Ord, V> MaybeMap<K, V> {
fn insert(&mut self, key: Key<K>, value: V) {
match self {
MaybeMap::Never | MaybeMap::Some => {} //NoOp
MaybeMap::None => *self = MaybeMap::Some,
MaybeMap::Uninitialized => {
let mut map = BTreeMap::new();
map.insert(key, value);
*self = MaybeMap::Map(map);
}
MaybeMap::Map(map) => {
map.insert(key, value);
}
}
}
}
impl<K, V> From<MaybeMap<K, V>> for Option<SegmentMap<K, V>> {
fn from(map: MaybeMap<K, V>) -> Self {
if let MaybeMap::Map(map) = map {
Some(SegmentMap {
map,
store: Vec::new(),
})
} else {
None
}
}
}
impl<K, V> From<MaybeMap<K, V>> for bool {
fn from(map: MaybeMap<K, V>) -> Self {
matches!(map, MaybeMap::Some | MaybeMap::Map(_))
}
}
|
use rsocket_rust::Result;
use serde::{de::DeserializeOwned, Serialize};
pub trait SerDe {
fn marshal<T>(&self, data: &T) -> Result<Vec<u8>>
where
Self: Sized,
T: Sized + Serialize;
fn unmarshal<T>(&self, raw: &[u8]) -> Result<T>
where
Self: Sized,
T: Sized + DeserializeOwned;
}
#[derive(Default)]
struct JsonSerDe {}
impl SerDe for JsonSerDe {
fn marshal<T>(&self, data: &T) -> Result<Vec<u8>>
where
T: Sized + Serialize,
{
Ok(serde_json::to_vec(data)?)
}
fn unmarshal<T>(&self, raw: &[u8]) -> Result<T>
where
T: Sized + DeserializeOwned,
{
Ok(serde_json::from_slice(raw)?)
}
}
pub fn json() -> impl SerDe {
JsonSerDe {}
}
pub fn cbor() -> impl SerDe {
CborSerDe {}
}
struct CborSerDe {}
impl SerDe for CborSerDe {
fn marshal<T>(&self, data: &T) -> Result<Vec<u8>>
where
T: Sized + Serialize,
{
Ok(serde_cbor::to_vec(data)?)
}
fn unmarshal<T>(&self, raw: &[u8]) -> Result<T>
where
T: Sized + DeserializeOwned,
{
Ok(serde_cbor::from_slice(raw)?)
}
}
pub(crate) fn marshal<T>(ser: impl SerDe, data: &T) -> Result<Vec<u8>>
where
T: Sized + Serialize,
{
ser.marshal(data)
}
pub(crate) fn unmarshal<T>(de: impl SerDe, raw: &[u8]) -> Result<T>
where
T: Sized + DeserializeOwned,
{
de.unmarshal(raw)
}
|
use super::agent_vnet_test::*;
use super::*;
use crate::candidate::candidate_base::*;
use crate::candidate::candidate_host::*;
use crate::candidate::candidate_peer_reflexive::*;
use crate::candidate::candidate_relay::*;
use crate::candidate::candidate_server_reflexive::*;
use crate::control::AttrControlling;
use crate::priority::PriorityAttr;
use crate::use_candidate::UseCandidateAttr;
use crate::agent::agent_transport_test::pipe;
use async_trait::async_trait;
use std::io;
use std::net::Ipv4Addr;
use std::ops::Sub;
use std::str::FromStr;
use stun::message::*;
use stun::textattrs::Username;
use util::{vnet::*, Conn, Error};
use waitgroup::{WaitGroup, Worker};
#[tokio::test]
async fn test_pair_search() -> Result<(), Error> {
let config = AgentConfig::default();
let a = Agent::new(config).await?;
{
let ai = a.agent_internal.lock().await;
{
let checklist = ai.agent_conn.checklist.lock().await;
assert!(
checklist.is_empty(),
"TestPairSearch is only a valid test if a.validPairs is empty on construction"
);
}
let cp = ai.agent_conn.get_best_available_candidate_pair().await;
assert!(cp.is_none(), "No Candidate pairs should exist");
}
let _ = a.close().await?;
Ok(())
}
#[tokio::test]
async fn test_pair_priority() -> Result<(), Error> {
let a = Agent::new(AgentConfig::default()).await?;
let host_config = CandidateHostConfig {
base_config: CandidateBaseConfig {
network: "udp".to_owned(),
address: "192.168.1.1".to_owned(),
port: 19216,
component: 1,
..Default::default()
},
..Default::default()
};
let host_local: Arc<dyn Candidate + Send + Sync> = Arc::new(
host_config
.new_candidate_host(Some(a.agent_internal.clone()))
.await?,
);
let relay_config = CandidateRelayConfig {
base_config: CandidateBaseConfig {
network: "udp".to_owned(),
address: "1.2.3.4".to_owned(),
port: 12340,
component: 1,
..Default::default()
},
rel_addr: "4.3.2.1".to_owned(),
rel_port: 43210,
..Default::default()
};
let relay_remote = relay_config
.new_candidate_relay(Some(a.agent_internal.clone()))
.await?;
let srflx_config = CandidateServerReflexiveConfig {
base_config: CandidateBaseConfig {
network: "udp".to_owned(),
address: "10.10.10.2".to_owned(),
port: 19218,
component: 1,
..Default::default()
},
rel_addr: "4.3.2.1".to_owned(),
rel_port: 43212,
};
let srflx_remote = srflx_config
.new_candidate_server_reflexive(Some(a.agent_internal.clone()))
.await?;
let prflx_config = CandidatePeerReflexiveConfig {
base_config: CandidateBaseConfig {
network: "udp".to_owned(),
address: "10.10.10.2".to_owned(),
port: 19217,
component: 1,
..Default::default()
},
rel_addr: "4.3.2.1".to_owned(),
rel_port: 43211,
};
let prflx_remote = prflx_config
.new_candidate_peer_reflexive(Some(a.agent_internal.clone()))
.await?;
let host_config = CandidateHostConfig {
base_config: CandidateBaseConfig {
network: "udp".to_owned(),
address: "1.2.3.5".to_owned(),
port: 12350,
component: 1,
..Default::default()
},
..Default::default()
};
let host_remote = host_config
.new_candidate_host(Some(a.agent_internal.clone()))
.await?;
let remotes: Vec<Arc<dyn Candidate + Send + Sync>> = vec![
Arc::new(relay_remote),
Arc::new(srflx_remote),
Arc::new(prflx_remote),
Arc::new(host_remote),
];
{
let mut ai = a.agent_internal.lock().await;
for remote in remotes {
if ai.find_pair(&host_local, &remote).await.is_none() {
ai.add_pair(host_local.clone(), remote.clone()).await;
}
if let Some(p) = ai.find_pair(&host_local, &remote).await {
p.state
.store(CandidatePairState::Succeeded as u8, Ordering::SeqCst);
}
if let Some(best_pair) = ai.agent_conn.get_best_available_candidate_pair().await {
assert_eq!(
best_pair.to_string(),
CandidatePair {
remote: remote.clone(),
local: host_local.clone(),
..Default::default()
}
.to_string(),
"Unexpected bestPair {} (expected remote: {})",
best_pair.to_string(),
remote.to_string(),
);
} else {
panic!("expected Some, but got None");
}
}
}
let _ = a.close().await?;
Ok(())
}
#[tokio::test]
async fn test_on_selected_candidate_pair_change() -> Result<(), Error> {
let a = Agent::new(AgentConfig::default()).await?;
let (callback_called_tx, mut callback_called_rx) = mpsc::channel::<()>(1);
let callback_called_tx = Arc::new(Mutex::new(Some(callback_called_tx)));
let cb: OnSelectedCandidatePairChangeHdlrFn = Box::new(move |_, _| {
let callback_called_tx_clone = Arc::clone(&callback_called_tx);
Box::pin(async move {
let mut tx = callback_called_tx_clone.lock().await;
tx.take();
})
});
a.on_selected_candidate_pair_change(cb).await;
let host_config = CandidateHostConfig {
base_config: CandidateBaseConfig {
network: "udp".to_owned(),
address: "192.168.1.1".to_owned(),
port: 19216,
component: 1,
..Default::default()
},
..Default::default()
};
let host_local = host_config
.new_candidate_host(Some(a.agent_internal.clone()))
.await?;
let relay_config = CandidateRelayConfig {
base_config: CandidateBaseConfig {
network: "udp".to_owned(),
address: "1.2.3.4".to_owned(),
port: 12340,
component: 1,
..Default::default()
},
rel_addr: "4.3.2.1".to_owned(),
rel_port: 43210,
..Default::default()
};
let relay_remote = relay_config
.new_candidate_relay(Some(a.agent_internal.clone()))
.await?;
// select the pair
let p = Arc::new(CandidatePair::new(
Arc::new(host_local),
Arc::new(relay_remote),
false,
));
{
let mut ai = a.agent_internal.lock().await;
ai.set_selected_pair(Some(p)).await;
}
// ensure that the callback fired on setting the pair
let _ = callback_called_rx.recv().await;
let _ = a.close().await?;
Ok(())
}
#[tokio::test]
async fn test_handle_peer_reflexive_udp_pflx_candidate() -> Result<(), Error> {
let a = Agent::new(AgentConfig::default()).await?;
let host_config = CandidateHostConfig {
base_config: CandidateBaseConfig {
network: "udp".to_owned(),
address: "192.168.0.2".to_owned(),
port: 777,
component: 1,
conn: Some(Arc::new(MockConn {})),
..Default::default()
},
..Default::default()
};
let local: Arc<dyn Candidate + Send + Sync> = Arc::new(
host_config
.new_candidate_host(Some(a.agent_internal.clone()))
.await?,
);
let remote = SocketAddr::from_str("172.17.0.3:999")?;
let (username, local_pwd, tie_breaker) = {
let ai = a.agent_internal.lock().await;
(
ai.local_ufrag.to_owned() + ":" + ai.remote_ufrag.as_str(),
ai.local_pwd.clone(),
ai.tie_breaker,
)
};
let mut msg = Message::new();
msg.build(&[
Box::new(BINDING_REQUEST),
Box::new(TransactionId::new()),
Box::new(Username::new(ATTR_USERNAME, username)),
Box::new(UseCandidateAttr::new()),
Box::new(AttrControlling(tie_breaker)),
Box::new(PriorityAttr(local.priority())),
Box::new(MessageIntegrity::new_short_term_integrity(local_pwd)),
Box::new(FINGERPRINT),
])?;
{
let agent_internal_clone = Arc::clone(&a.agent_internal);
let mut ai = a.agent_internal.lock().await;
ai.handle_inbound(&mut msg, &local, remote, agent_internal_clone)
.await;
// length of remote candidate list must be one now
assert_eq!(
ai.remote_candidates.len(),
1,
"failed to add a network type to the remote candidate list"
);
// length of remote candidate list for a network type must be 1
if let Some(cands) = ai.remote_candidates.get(&local.network_type()) {
assert_eq!(
cands.len(),
1,
"failed to add prflx candidate to remote candidate list"
);
let c = &cands[0];
assert_eq!(
c.candidate_type(),
CandidateType::PeerReflexive,
"candidate type must be prflx"
);
assert_eq!(c.address(), "172.17.0.3", "IP address mismatch");
assert_eq!(c.port(), 999, "Port number mismatch");
} else {
panic!(
"expected non-empty remote candidate for network type {}",
local.network_type()
);
}
}
let _ = a.close().await?;
Ok(())
}
#[tokio::test]
async fn test_handle_peer_reflexive_unknown_remote() -> Result<(), Error> {
let a = Agent::new(AgentConfig::default()).await?;
let mut tid = TransactionId::default();
tid.0[..3].copy_from_slice("ABC".as_bytes());
let remote_pwd = {
let mut ai = a.agent_internal.lock().await;
ai.pending_binding_requests = vec![BindingRequest {
timestamp: Instant::now(),
transaction_id: tid,
destination: SocketAddr::from_str("0.0.0.0:0")?,
is_use_candidate: false,
}];
ai.remote_pwd.clone()
};
let host_config = CandidateHostConfig {
base_config: CandidateBaseConfig {
network: "udp".to_owned(),
address: "192.168.0.2".to_owned(),
port: 777,
component: 1,
conn: Some(Arc::new(MockConn {})),
..Default::default()
},
..Default::default()
};
let local: Arc<dyn Candidate + Send + Sync> = Arc::new(
host_config
.new_candidate_host(Some(a.agent_internal.clone()))
.await?,
);
let remote = SocketAddr::from_str("172.17.0.3:999")?;
let mut msg = Message::new();
msg.build(&[
Box::new(BINDING_SUCCESS),
Box::new(tid),
Box::new(MessageIntegrity::new_short_term_integrity(remote_pwd)),
Box::new(FINGERPRINT),
])?;
{
let agent_internal_clone = Arc::clone(&a.agent_internal);
let mut ai = a.agent_internal.lock().await;
ai.handle_inbound(&mut msg, &local, remote, agent_internal_clone)
.await;
assert_eq!(
ai.remote_candidates.len(),
0,
"unknown remote was able to create a candidate"
);
}
let _ = a.close().await?;
Ok(())
}
//use std::io::Write;
// Assert that Agent on startup sends message, and doesn't wait for connectivityTicker to fire
#[tokio::test]
async fn test_connectivity_on_startup() -> Result<(), Error> {
/*env_logger::Builder::new()
.format(|buf, record| {
writeln!(
buf,
"{}:{} [{}] {} - {}",
record.file().unwrap_or("unknown"),
record.line().unwrap_or(0),
record.level(),
chrono::Local::now().format("%H:%M:%S.%6f"),
record.args()
)
})
.filter(None, log::LevelFilter::Trace)
.init();*/
// Create a network with two interfaces
let wan = Arc::new(Mutex::new(router::Router::new(router::RouterConfig {
cidr: "0.0.0.0/0".to_owned(),
..Default::default()
})?));
let net0 = Arc::new(net::Net::new(Some(net::NetConfig {
static_ips: vec!["192.168.0.1".to_owned()],
..Default::default()
})));
let net1 = Arc::new(net::Net::new(Some(net::NetConfig {
static_ips: vec!["192.168.0.2".to_owned()],
..Default::default()
})));
connect_net2router(&net0, &wan).await?;
connect_net2router(&net1, &wan).await?;
start_router(&wan).await?;
let (a_notifier, mut a_connected) = on_connected();
let (b_notifier, mut b_connected) = on_connected();
let keepalive_interval = Some(Duration::from_secs(3600)); //time.Hour
let check_interval = Duration::from_secs(3600); //time.Hour
let cfg0 = AgentConfig {
network_types: supported_network_types(),
multicast_dns_mode: MulticastDnsMode::Disabled,
net: Some(net0),
keepalive_interval,
check_interval,
..Default::default()
};
let a_agent = Arc::new(Agent::new(cfg0).await?);
a_agent.on_connection_state_change(a_notifier).await;
let cfg1 = AgentConfig {
network_types: supported_network_types(),
multicast_dns_mode: MulticastDnsMode::Disabled,
net: Some(net1),
keepalive_interval,
check_interval,
..Default::default()
};
let b_agent = Arc::new(Agent::new(cfg1).await?);
b_agent.on_connection_state_change(b_notifier).await;
// Manual signaling
let (a_ufrag, a_pwd) = a_agent.get_local_user_credentials().await;
let (b_ufrag, b_pwd) = b_agent.get_local_user_credentials().await;
gather_and_exchange_candidates(&a_agent, &b_agent).await?;
let (accepted_tx, mut accepted_rx) = mpsc::channel::<()>(1);
let (accepting_tx, mut accepting_rx) = mpsc::channel::<()>(1);
let (_a_cancel_tx, a_cancel_rx) = mpsc::channel(1);
let (_b_cancel_tx, b_cancel_rx) = mpsc::channel(1);
let accepting_tx = Arc::new(Mutex::new(Some(accepting_tx)));
a_agent
.on_connection_state_change(Box::new(move |s: ConnectionState| {
let accepted_tx_clone = Arc::clone(&accepting_tx);
Box::pin(async move {
if s == ConnectionState::Checking {
let mut tx = accepted_tx_clone.lock().await;
tx.take();
}
})
}))
.await;
tokio::spawn(async move {
let result = a_agent.accept(a_cancel_rx, b_ufrag, b_pwd).await;
assert!(result.is_ok(), "agent accept expected OK");
drop(accepted_tx);
});
let _ = accepting_rx.recv().await;
let _ = b_agent.dial(b_cancel_rx, a_ufrag, a_pwd).await?;
// Ensure accepted
let _ = accepted_rx.recv().await;
// Ensure pair selected
// Note: this assumes ConnectionStateConnected is thrown after selecting the final pair
let _ = a_connected.recv().await;
let _ = b_connected.recv().await;
{
let mut w = wan.lock().await;
w.stop().await?;
}
Ok(())
}
#[tokio::test]
async fn test_connectivity_lite() -> Result<(), Error> {
/*env_logger::Builder::new()
.format(|buf, record| {
writeln!(
buf,
"{}:{} [{}] {} - {}",
record.file().unwrap_or("unknown"),
record.line().unwrap_or(0),
record.level(),
chrono::Local::now().format("%H:%M:%S.%6f"),
record.args()
)
})
.filter(None, log::LevelFilter::Trace)
.init();*/
let stun_server_url = Url {
scheme: SchemeType::Stun,
host: "1.2.3.4".to_owned(),
port: 3478,
proto: ProtoType::Udp,
..Default::default()
};
let nat_type = nat::NatType {
mapping_behavior: nat::EndpointDependencyType::EndpointIndependent,
filtering_behavior: nat::EndpointDependencyType::EndpointIndependent,
..Default::default()
};
let v = build_vnet(nat_type, nat_type).await?;
let (a_notifier, mut a_connected) = on_connected();
let (b_notifier, mut b_connected) = on_connected();
let cfg0 = AgentConfig {
urls: vec![stun_server_url],
network_types: supported_network_types(),
multicast_dns_mode: MulticastDnsMode::Disabled,
net: Some(Arc::clone(&v.net0)),
..Default::default()
};
let a_agent = Arc::new(Agent::new(cfg0).await?);
a_agent.on_connection_state_change(a_notifier).await;
let cfg1 = AgentConfig {
urls: vec![],
lite: true,
candidate_types: vec![CandidateType::Host],
network_types: supported_network_types(),
multicast_dns_mode: MulticastDnsMode::Disabled,
net: Some(Arc::clone(&v.net1)),
..Default::default()
};
let b_agent = Arc::new(Agent::new(cfg1).await?);
b_agent.on_connection_state_change(b_notifier).await;
let _ = connect_with_vnet(&a_agent, &b_agent).await?;
// Ensure pair selected
// Note: this assumes ConnectionStateConnected is thrown after selecting the final pair
let _ = a_connected.recv().await;
let _ = b_connected.recv().await;
v.close().await?;
Ok(())
}
struct MockPacketConn;
#[async_trait]
impl Conn for MockPacketConn {
async fn connect(&self, _addr: SocketAddr) -> io::Result<()> {
Ok(())
}
async fn recv(&self, _buf: &mut [u8]) -> io::Result<usize> {
Ok(0)
}
async fn recv_from(&self, _buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
Ok((0, SocketAddr::new(Ipv4Addr::new(0, 0, 0, 0).into(), 0)))
}
async fn send(&self, _buf: &[u8]) -> io::Result<usize> {
Ok(0)
}
async fn send_to(&self, _buf: &[u8], _target: SocketAddr) -> io::Result<usize> {
Ok(0)
}
async fn local_addr(&self) -> io::Result<SocketAddr> {
Ok(SocketAddr::new(Ipv4Addr::new(0, 0, 0, 0).into(), 0))
}
}
fn build_msg(c: MessageClass, username: String, key: String) -> Result<Message, Error> {
let mut msg = Message::new();
msg.build(&[
Box::new(MessageType::new(METHOD_BINDING, c)),
Box::new(TransactionId::new()),
Box::new(Username::new(ATTR_USERNAME, username)),
Box::new(MessageIntegrity::new_short_term_integrity(key)),
Box::new(FINGERPRINT),
])?;
Ok(msg)
}
#[tokio::test]
async fn test_inbound_validity() -> Result<(), Error> {
/*env_logger::Builder::new()
.format(|buf, record| {
writeln!(
buf,
"{}:{} [{}] {} - {}",
record.file().unwrap_or("unknown"),
record.line().unwrap_or(0),
record.level(),
chrono::Local::now().format("%H:%M:%S.%6f"),
record.args()
)
})
.filter(None, log::LevelFilter::Trace)
.init();*/
let remote = SocketAddr::from_str("172.17.0.3:999")?;
let local: Arc<dyn Candidate + Send + Sync> = Arc::new(
CandidateHostConfig {
base_config: CandidateBaseConfig {
network: "udp".to_owned(),
address: "192.168.0.2".to_owned(),
port: 777,
component: 1,
conn: Some(Arc::new(MockPacketConn {})),
..Default::default()
},
..Default::default()
}
.new_candidate_host(None)
.await?,
);
//"Invalid Binding requests should be discarded"
{
let a = Agent::new(AgentConfig::default()).await?;
{
let agent_internal1 = Arc::clone(&a.agent_internal);
let agent_internal2 = Arc::clone(&a.agent_internal);
let mut ai = a.agent_internal.lock().await;
let local_pwd = ai.local_pwd.clone();
ai.handle_inbound(
&mut build_msg(CLASS_REQUEST, "invalid".to_owned(), local_pwd)?,
&local,
remote,
agent_internal1,
)
.await;
assert_ne!(
ai.remote_candidates.len(),
1,
"Binding with invalid Username was able to create prflx candidate"
);
let username = format!("{}:{}", ai.local_ufrag, ai.remote_ufrag);
ai.handle_inbound(
&mut build_msg(CLASS_REQUEST, username, "Invalid".to_owned())?,
&local,
remote,
agent_internal2,
)
.await;
assert_ne!(
ai.remote_candidates.len(),
1,
"Binding with invalid MessageIntegrity was able to create prflx candidate"
);
}
a.close().await?;
}
//"Invalid Binding success responses should be discarded"
{
let a = Agent::new(AgentConfig::default()).await?;
{
let agent_internal1 = Arc::clone(&a.agent_internal);
let mut ai = a.agent_internal.lock().await;
let username = format!("{}:{}", ai.local_ufrag, ai.remote_ufrag);
ai.handle_inbound(
&mut build_msg(CLASS_SUCCESS_RESPONSE, username, "Invalid".to_owned())?,
&local,
remote,
agent_internal1,
)
.await;
assert_ne!(
ai.remote_candidates.len(),
1,
"Binding with invalid Username was able to create prflx candidate"
);
}
a.close().await?;
}
//"Discard non-binding messages"
{
let a = Agent::new(AgentConfig::default()).await?;
{
let agent_internal1 = Arc::clone(&a.agent_internal);
let mut ai = a.agent_internal.lock().await;
let username = format!("{}:{}", ai.local_ufrag, ai.remote_ufrag);
ai.handle_inbound(
&mut build_msg(CLASS_ERROR_RESPONSE, username, "Invalid".to_owned())?,
&local,
remote,
agent_internal1,
)
.await;
assert_ne!(
ai.remote_candidates.len(),
1,
"non-binding message was able to create prflxRemote"
);
}
a.close().await?;
}
//"Valid bind request"
{
let a = Agent::new(AgentConfig::default()).await?;
{
let agent_internal1 = Arc::clone(&a.agent_internal);
let mut ai = a.agent_internal.lock().await;
let username = format!("{}:{}", ai.local_ufrag, ai.remote_ufrag);
let local_pwd = ai.local_pwd.clone();
ai.handle_inbound(
&mut build_msg(CLASS_REQUEST, username, local_pwd)?,
&local,
remote,
agent_internal1,
)
.await;
assert_eq!(
ai.remote_candidates.len(),
1,
"Binding with valid values was unable to create prflx candidate"
);
}
a.close().await?;
}
//"Valid bind without fingerprint"
{
let a = Agent::new(AgentConfig::default()).await?;
{
let agent_internal1 = Arc::clone(&a.agent_internal);
let mut ai = a.agent_internal.lock().await;
let username = format!("{}:{}", ai.local_ufrag, ai.remote_ufrag);
let local_pwd = ai.local_pwd.clone();
let mut msg = Message::new();
msg.build(&[
Box::new(BINDING_REQUEST),
Box::new(TransactionId::new()),
Box::new(Username::new(ATTR_USERNAME, username)),
Box::new(MessageIntegrity::new_short_term_integrity(local_pwd)),
])?;
ai.handle_inbound(&mut msg, &local, remote, agent_internal1)
.await;
assert_eq!(
ai.remote_candidates.len(),
1,
"Binding with valid values (but no fingerprint) was unable to create prflx candidate"
);
}
a.close().await?;
}
//"Success with invalid TransactionID"
{
let a = Agent::new(AgentConfig::default()).await?;
{
let agent_internal1 = Arc::clone(&a.agent_internal);
let mut ai = a.agent_internal.lock().await;
let remote = SocketAddr::from_str("172.17.0.3:999")?;
let mut t_id = TransactionId::default();
t_id.0[..3].copy_from_slice(b"ABC");
let remote_pwd = ai.remote_pwd.clone();
let mut msg = Message::new();
msg.build(&[
Box::new(BINDING_SUCCESS),
Box::new(t_id),
Box::new(MessageIntegrity::new_short_term_integrity(remote_pwd)),
Box::new(FINGERPRINT),
])?;
ai.handle_inbound(&mut msg, &local, remote, agent_internal1)
.await;
assert_eq!(
ai.remote_candidates.len(),
0,
"unknown remote was able to create a candidate"
);
}
a.close().await?;
}
Ok(())
}
#[tokio::test]
async fn test_invalid_agent_starts() -> Result<(), Error> {
let a = Agent::new(AgentConfig::default()).await?;
let (_cancel_tx1, cancel_rx1) = mpsc::channel(1);
let result = a.dial(cancel_rx1, "".to_owned(), "bar".to_owned()).await;
assert!(result.is_err());
if let Err(err) = result {
assert_eq!(err, *ERR_REMOTE_UFRAG_EMPTY);
}
let (_cancel_tx2, cancel_rx2) = mpsc::channel(1);
let result = a.dial(cancel_rx2, "foo".to_owned(), "".to_owned()).await;
assert!(result.is_err());
if let Err(err) = result {
assert_eq!(err, *ERR_REMOTE_PWD_EMPTY);
}
let (cancel_tx3, cancel_rx3) = mpsc::channel(1);
tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(100)).await;
drop(cancel_tx3);
});
let result = a.dial(cancel_rx3, "foo".to_owned(), "bar".to_owned()).await;
assert!(result.is_err());
if let Err(err) = result {
assert_eq!(err, *ERR_CANCELED_BY_CALLER);
}
let (_cancel_tx4, cancel_rx4) = mpsc::channel(1);
let result = a.dial(cancel_rx4, "foo".to_owned(), "bar".to_owned()).await;
assert!(result.is_err());
if let Err(err) = result {
assert_eq!(err, *ERR_MULTIPLE_START);
}
a.close().await?;
Ok(())
}
//use std::io::Write;
// Assert that Agent emits Connecting/Connected/Disconnected/Failed/Closed messages
#[tokio::test]
async fn test_connection_state_callback() -> Result<(), Error> {
/*env_logger::Builder::new()
.format(|buf, record| {
writeln!(
buf,
"{}:{} [{}] {} - {}",
record.file().unwrap_or("unknown"),
record.line().unwrap_or(0),
record.level(),
chrono::Local::now().format("%H:%M:%S.%6f"),
record.args()
)
})
.filter(None, log::LevelFilter::Trace)
.init();*/
let disconnected_duration = Duration::from_secs(1);
let failed_duration = Duration::from_secs(1);
let keepalive_interval = Duration::from_secs(0);
let cfg0 = AgentConfig {
urls: vec![],
network_types: supported_network_types(),
disconnected_timeout: Some(disconnected_duration),
failed_timeout: Some(failed_duration),
keepalive_interval: Some(keepalive_interval),
..Default::default()
};
let cfg1 = AgentConfig {
urls: vec![],
network_types: supported_network_types(),
disconnected_timeout: Some(disconnected_duration),
failed_timeout: Some(failed_duration),
keepalive_interval: Some(keepalive_interval),
..Default::default()
};
let a_agent = Arc::new(Agent::new(cfg0).await?);
let b_agent = Arc::new(Agent::new(cfg1).await?);
let (is_checking_tx, mut is_checking_rx) = mpsc::channel::<()>(1);
let (is_connected_tx, mut is_connected_rx) = mpsc::channel::<()>(1);
let (is_disconnected_tx, mut is_disconnected_rx) = mpsc::channel::<()>(1);
let (is_failed_tx, mut is_failed_rx) = mpsc::channel::<()>(1);
let (is_closed_tx, mut is_closed_rx) = mpsc::channel::<()>(1);
let is_checking_tx = Arc::new(Mutex::new(Some(is_checking_tx)));
let is_connected_tx = Arc::new(Mutex::new(Some(is_connected_tx)));
let is_disconnected_tx = Arc::new(Mutex::new(Some(is_disconnected_tx)));
let is_failed_tx = Arc::new(Mutex::new(Some(is_failed_tx)));
let is_closed_tx = Arc::new(Mutex::new(Some(is_closed_tx)));
a_agent
.on_connection_state_change(Box::new(move |c: ConnectionState| {
let is_checking_tx_clone = Arc::clone(&is_checking_tx);
let is_connected_tx_clone = Arc::clone(&is_connected_tx);
let is_disconnected_tx_clone = Arc::clone(&is_disconnected_tx);
let is_failed_tx_clone = Arc::clone(&is_failed_tx);
let is_closed_tx_clone = Arc::clone(&is_closed_tx);
Box::pin(async move {
match c {
ConnectionState::Checking => {
log::debug!("drop is_checking_tx");
let mut tx = is_checking_tx_clone.lock().await;
tx.take();
}
ConnectionState::Connected => {
log::debug!("drop is_connected_tx");
let mut tx = is_connected_tx_clone.lock().await;
tx.take();
}
ConnectionState::Disconnected => {
log::debug!("drop is_disconnected_tx");
let mut tx = is_disconnected_tx_clone.lock().await;
tx.take();
}
ConnectionState::Failed => {
log::debug!("drop is_failed_tx");
let mut tx = is_failed_tx_clone.lock().await;
tx.take();
}
ConnectionState::Closed => {
log::debug!("drop is_closed_tx");
let mut tx = is_closed_tx_clone.lock().await;
tx.take();
}
_ => {}
};
})
}))
.await;
connect_with_vnet(&a_agent, &b_agent).await?;
log::debug!("wait is_checking_tx");
let _ = is_checking_rx.recv().await;
log::debug!("wait is_connected_rx");
let _ = is_connected_rx.recv().await;
log::debug!("wait is_disconnected_rx");
let _ = is_disconnected_rx.recv().await;
log::debug!("wait is_failed_rx");
let _ = is_failed_rx.recv().await;
a_agent.close().await?;
b_agent.close().await?;
log::debug!("wait is_closed_rx");
let _ = is_closed_rx.recv().await;
Ok(())
}
#[tokio::test]
async fn test_invalid_gather() -> Result<(), Error> {
//"Gather with no OnCandidate should error"
let a = Agent::new(AgentConfig::default()).await?;
if let Err(err) = a.gather_candidates().await {
assert_eq!(
err, *ERR_NO_ON_CANDIDATE_HANDLER,
"trickle GatherCandidates succeeded without OnCandidate"
);
}
a.close().await?;
Ok(())
}
#[tokio::test]
async fn test_candidate_pair_stats() -> Result<(), Error> {
let a = Agent::new(AgentConfig::default()).await?;
let host_local: Arc<dyn Candidate + Send + Sync> = Arc::new(
CandidateHostConfig {
base_config: CandidateBaseConfig {
network: "udp".to_owned(),
address: "192.168.1.1".to_owned(),
port: 19216,
component: 1,
..Default::default()
},
..Default::default()
}
.new_candidate_host(Some(Arc::clone(&a.agent_internal)))
.await?,
);
let relay_remote: Arc<dyn Candidate + Send + Sync> = Arc::new(
CandidateRelayConfig {
base_config: CandidateBaseConfig {
network: "udp".to_owned(),
address: "1.2.3.4".to_owned(),
port: 2340,
component: 1,
..Default::default()
},
rel_addr: "4.3.2.1".to_owned(),
rel_port: 43210,
..Default::default()
}
.new_candidate_relay(Some(Arc::clone(&a.agent_internal)))
.await?,
);
let srflx_remote: Arc<dyn Candidate + Send + Sync> = Arc::new(
CandidateServerReflexiveConfig {
base_config: CandidateBaseConfig {
network: "udp".to_owned(),
address: "10.10.10.2".to_owned(),
port: 19218,
component: 1,
..Default::default()
},
rel_addr: "4.3.2.1".to_owned(),
rel_port: 43212,
}
.new_candidate_server_reflexive(Some(Arc::clone(&a.agent_internal)))
.await?,
);
let prflx_remote: Arc<dyn Candidate + Send + Sync> = Arc::new(
CandidatePeerReflexiveConfig {
base_config: CandidateBaseConfig {
network: "udp".to_owned(),
address: "10.10.10.2".to_owned(),
port: 19217,
component: 1,
..Default::default()
},
rel_addr: "4.3.2.1".to_owned(),
rel_port: 43211,
}
.new_candidate_peer_reflexive(Some(Arc::clone(&a.agent_internal)))
.await?,
);
let host_remote: Arc<dyn Candidate + Send + Sync> = Arc::new(
CandidateHostConfig {
base_config: CandidateBaseConfig {
network: "udp".to_owned(),
address: "1.2.3.5".to_owned(),
port: 12350,
component: 1,
..Default::default()
},
..Default::default()
}
.new_candidate_host(Some(Arc::clone(&a.agent_internal)))
.await?,
);
for remote in &[
Arc::clone(&relay_remote),
Arc::clone(&srflx_remote),
Arc::clone(&prflx_remote),
Arc::clone(&host_remote),
] {
let mut ai = a.agent_internal.lock().await;
let p = ai.find_pair(&host_local, remote).await;
if p.is_none() {
ai.add_pair(Arc::clone(&host_local), Arc::clone(remote))
.await;
}
}
{
let ai = a.agent_internal.lock().await;
if let Some(p) = ai.find_pair(&host_local, &prflx_remote).await {
p.state
.store(CandidatePairState::Failed as u8, Ordering::SeqCst);
}
}
let stats = a.get_candidate_pairs_stats().await;
assert_eq!(stats.len(), 4, "expected 4 candidate pairs stats");
let (mut relay_pair_stat, mut srflx_pair_stat, mut prflx_pair_stat, mut host_pair_stat) = (
CandidatePairStats::default(),
CandidatePairStats::default(),
CandidatePairStats::default(),
CandidatePairStats::default(),
);
for cps in stats {
assert_eq!(
cps.local_candidate_id,
host_local.id(),
"invalid local candidate id"
);
if cps.remote_candidate_id == relay_remote.id() {
relay_pair_stat = cps;
} else if cps.remote_candidate_id == srflx_remote.id() {
srflx_pair_stat = cps;
} else if cps.remote_candidate_id == prflx_remote.id() {
prflx_pair_stat = cps;
} else if cps.remote_candidate_id == host_remote.id() {
host_pair_stat = cps;
} else {
panic!("invalid remote candidate ID");
}
}
assert_eq!(
relay_pair_stat.remote_candidate_id,
relay_remote.id(),
"missing host-relay pair stat"
);
assert_eq!(
srflx_pair_stat.remote_candidate_id,
srflx_remote.id(),
"missing host-srflx pair stat"
);
assert_eq!(
prflx_pair_stat.remote_candidate_id,
prflx_remote.id(),
"missing host-prflx pair stat"
);
assert_eq!(
host_pair_stat.remote_candidate_id,
host_remote.id(),
"missing host-host pair stat"
);
assert_eq!(
prflx_pair_stat.state,
CandidatePairState::Failed,
"expected host-prfflx pair to have state failed, it has state {} instead",
prflx_pair_stat.state
);
a.close().await?;
Ok(())
}
#[tokio::test]
async fn test_local_candidate_stats() -> Result<(), Error> {
let a = Agent::new(AgentConfig::default()).await?;
let host_local: Arc<dyn Candidate + Send + Sync> = Arc::new(
CandidateHostConfig {
base_config: CandidateBaseConfig {
network: "udp".to_owned(),
address: "192.168.1.1".to_owned(),
port: 19216,
component: 1,
..Default::default()
},
..Default::default()
}
.new_candidate_host(Some(Arc::clone(&a.agent_internal)))
.await?,
);
let srflx_local: Arc<dyn Candidate + Send + Sync> = Arc::new(
CandidateServerReflexiveConfig {
base_config: CandidateBaseConfig {
network: "udp".to_owned(),
address: "192.168.1.1".to_owned(),
port: 19217,
component: 1,
..Default::default()
},
rel_addr: "4.3.2.1".to_owned(),
rel_port: 43212,
}
.new_candidate_server_reflexive(Some(Arc::clone(&a.agent_internal)))
.await?,
);
{
let mut ai = a.agent_internal.lock().await;
ai.local_candidates.insert(
NetworkType::Udp4,
vec![Arc::clone(&host_local), Arc::clone(&srflx_local)],
);
}
let local_stats = a.get_local_candidates_stats().await;
assert_eq!(
local_stats.len(),
2,
"expected 2 local candidates stats, got {} instead",
local_stats.len()
);
let (mut host_local_stat, mut srflx_local_stat) =
(CandidateStats::default(), CandidateStats::default());
for stats in local_stats {
let candidate = if stats.id == host_local.id() {
host_local_stat = stats.clone();
Arc::clone(&host_local)
} else if stats.id == srflx_local.id() {
srflx_local_stat = stats.clone();
Arc::clone(&srflx_local)
} else {
panic!("invalid local candidate ID");
};
assert_eq!(
stats.candidate_type,
candidate.candidate_type(),
"invalid stats CandidateType"
);
assert_eq!(
stats.priority,
candidate.priority(),
"invalid stats CandidateType"
);
assert_eq!(stats.ip, candidate.address(), "invalid stats IP");
}
assert_eq!(
host_local_stat.id,
host_local.id(),
"missing host local stat"
);
assert_eq!(
srflx_local_stat.id,
srflx_local.id(),
"missing srflx local stat"
);
a.close().await?;
Ok(())
}
#[tokio::test]
async fn test_remote_candidate_stats() -> Result<(), Error> {
let a = Agent::new(AgentConfig::default()).await?;
let relay_remote: Arc<dyn Candidate + Send + Sync> = Arc::new(
CandidateRelayConfig {
base_config: CandidateBaseConfig {
network: "udp".to_owned(),
address: "1.2.3.4".to_owned(),
port: 12340,
component: 1,
..Default::default()
},
rel_addr: "4.3.2.1".to_owned(),
rel_port: 43210,
..Default::default()
}
.new_candidate_relay(Some(Arc::clone(&a.agent_internal)))
.await?,
);
let srflx_remote: Arc<dyn Candidate + Send + Sync> = Arc::new(
CandidateServerReflexiveConfig {
base_config: CandidateBaseConfig {
network: "udp".to_owned(),
address: "10.10.10.2".to_owned(),
port: 19218,
component: 1,
..Default::default()
},
rel_addr: "4.3.2.1".to_owned(),
rel_port: 43212,
}
.new_candidate_server_reflexive(Some(Arc::clone(&a.agent_internal)))
.await?,
);
let prflx_remote: Arc<dyn Candidate + Send + Sync> = Arc::new(
CandidatePeerReflexiveConfig {
base_config: CandidateBaseConfig {
network: "udp".to_owned(),
address: "10.10.10.2".to_owned(),
port: 19217,
component: 1,
..Default::default()
},
rel_addr: "4.3.2.1".to_owned(),
rel_port: 43211,
}
.new_candidate_peer_reflexive(Some(Arc::clone(&a.agent_internal)))
.await?,
);
let host_remote: Arc<dyn Candidate + Send + Sync> = Arc::new(
CandidateHostConfig {
base_config: CandidateBaseConfig {
network: "udp".to_owned(),
address: "1.2.3.5".to_owned(),
port: 12350,
component: 1,
..Default::default()
},
..Default::default()
}
.new_candidate_host(Some(Arc::clone(&a.agent_internal)))
.await?,
);
{
let mut ai = a.agent_internal.lock().await;
ai.remote_candidates.insert(
NetworkType::Udp4,
vec![
Arc::clone(&relay_remote),
Arc::clone(&srflx_remote),
Arc::clone(&prflx_remote),
Arc::clone(&host_remote),
],
);
}
let remote_stats = a.get_remote_candidates_stats().await;
assert_eq!(
remote_stats.len(),
4,
"expected 4 remote candidates stats, got {} instead",
remote_stats.len()
);
let (mut relay_remote_stat, mut srflx_remote_stat, mut prflx_remote_stat, mut host_remote_stat) = (
CandidateStats::default(),
CandidateStats::default(),
CandidateStats::default(),
CandidateStats::default(),
);
for stats in remote_stats {
let candidate = if stats.id == relay_remote.id() {
relay_remote_stat = stats.clone();
Arc::clone(&relay_remote)
} else if stats.id == srflx_remote.id() {
srflx_remote_stat = stats.clone();
Arc::clone(&srflx_remote)
} else if stats.id == prflx_remote.id() {
prflx_remote_stat = stats.clone();
Arc::clone(&prflx_remote)
} else if stats.id == host_remote.id() {
host_remote_stat = stats.clone();
Arc::clone(&host_remote)
} else {
panic!("invalid remote candidate ID");
};
assert_eq!(
stats.candidate_type,
candidate.candidate_type(),
"invalid stats CandidateType"
);
assert_eq!(
stats.priority,
candidate.priority(),
"invalid stats CandidateType"
);
assert_eq!(stats.ip, candidate.address(), "invalid stats IP");
}
assert_eq!(
relay_remote_stat.id,
relay_remote.id(),
"missing relay remote stat"
);
assert_eq!(
srflx_remote_stat.id,
srflx_remote.id(),
"missing srflx remote stat"
);
assert_eq!(
prflx_remote_stat.id,
prflx_remote.id(),
"missing prflx remote stat"
);
assert_eq!(
host_remote_stat.id,
host_remote.id(),
"missing host remote stat"
);
a.close().await?;
Ok(())
}
#[tokio::test]
async fn test_init_ext_ip_mapping() -> Result<(), Error> {
// a.extIPMapper should be nil by default
let a = Agent::new(AgentConfig::default()).await?;
assert!(
a.ext_ip_mapper.is_none(),
"a.extIPMapper should be none by default"
);
a.close().await?;
// a.extIPMapper should be nil when NAT1To1IPs is a non-nil empty array
let a = Agent::new(AgentConfig {
nat_1to1_ips: vec![],
nat_1to1_ip_candidate_type: CandidateType::Host,
..Default::default()
})
.await?;
assert!(
a.ext_ip_mapper.is_none(),
"a.extIPMapper should be none by default"
);
a.close().await?;
// NewAgent should return an error when 1:1 NAT for host candidate is enabled
// but the candidate type does not appear in the CandidateTypes.
if let Err(err) = Agent::new(AgentConfig {
nat_1to1_ips: vec!["1.2.3.4".to_owned()],
nat_1to1_ip_candidate_type: CandidateType::Host,
candidate_types: vec![CandidateType::Relay],
..Default::default()
})
.await
{
assert_eq!(
err, *ERR_INEFFECTIVE_NAT_1TO1_IP_MAPPING_HOST,
"Unexpected error: {}",
err
);
} else {
panic!("expected error, but got ok");
}
// NewAgent should return an error when 1:1 NAT for srflx candidate is enabled
// but the candidate type does not appear in the CandidateTypes.
if let Err(err) = Agent::new(AgentConfig {
nat_1to1_ips: vec!["1.2.3.4".to_owned()],
nat_1to1_ip_candidate_type: CandidateType::ServerReflexive,
candidate_types: vec![CandidateType::Relay],
..Default::default()
})
.await
{
assert_eq!(
err, *ERR_INEFFECTIVE_NAT_1TO1_IP_MAPPING_SRFLX,
"Unexpected error: {}",
err
);
} else {
panic!("expected error, but got ok");
}
// NewAgent should return an error when 1:1 NAT for host candidate is enabled
// along with mDNS with MulticastDNSModeQueryAndGather
if let Err(err) = Agent::new(AgentConfig {
nat_1to1_ips: vec!["1.2.3.4".to_owned()],
nat_1to1_ip_candidate_type: CandidateType::Host,
multicast_dns_mode: MulticastDnsMode::QueryAndGather,
..Default::default()
})
.await
{
assert_eq!(
err, *ERR_MULTICAST_DNS_WITH_NAT_1TO1_IP_MAPPING,
"Unexpected error: {}",
err
);
} else {
panic!("expected error, but got ok");
}
// NewAgent should return if newExternalIPMapper() returns an error.
if let Err(err) = Agent::new(AgentConfig {
nat_1to1_ips: vec!["bad.2.3.4".to_owned()], // bad IP
nat_1to1_ip_candidate_type: CandidateType::Host,
..Default::default()
})
.await
{
assert_eq!(
err, *ERR_INVALID_NAT_1TO1_IP_MAPPING,
"Unexpected error: {}",
err
);
} else {
panic!("expected error, but got ok");
}
Ok(())
}
#[tokio::test]
async fn test_binding_request_timeout() -> Result<(), Error> {
const EXPECTED_REMOVAL_COUNT: usize = 2;
let a = Agent::new(AgentConfig::default()).await?;
let now = Instant::now();
{
let mut ai = a.agent_internal.lock().await;
ai.pending_binding_requests.push(BindingRequest {
timestamp: now, // valid
..Default::default()
});
ai.pending_binding_requests.push(BindingRequest {
timestamp: now.sub(Duration::from_millis(3900)), // valid
..Default::default()
});
ai.pending_binding_requests.push(BindingRequest {
timestamp: now.sub(Duration::from_millis(4100)), // invalid
..Default::default()
});
ai.pending_binding_requests.push(BindingRequest {
timestamp: now.sub(Duration::from_secs(75)), // invalid
..Default::default()
});
ai.invalidate_pending_binding_requests(now);
assert_eq!(EXPECTED_REMOVAL_COUNT, ai.pending_binding_requests.len(), "Binding invalidation due to timeout did not remove the correct number of binding requests")
}
a.close().await?;
Ok(())
}
// test_agent_credentials checks if local username fragments and passwords (if set) meet RFC standard
// and ensure it's backwards compatible with previous versions of the pion/ice
#[tokio::test]
async fn test_agent_credentials() -> Result<(), Error> {
// Agent should not require any of the usernames and password to be set
// If set, they should follow the default 16/128 bits random number generator strategy
let a = Agent::new(AgentConfig::default()).await?;
{
let ai = a.agent_internal.lock().await;
assert!(ai.local_ufrag.as_bytes().len() * 8 >= 24);
assert!(ai.local_pwd.as_bytes().len() * 8 >= 128);
}
a.close().await?;
// Should honor RFC standards
// Local values MUST be unguessable, with at least 128 bits of
// random number generator output used to generate the password, and
// at least 24 bits of output to generate the username fragment.
if let Err(err) = Agent::new(AgentConfig {
local_ufrag: "xx".to_owned(),
..Default::default()
})
.await
{
assert_eq!(err, *ERR_LOCAL_UFRAG_INSUFFICIENT_BITS);
} else {
panic!("expected error, but got ok");
}
if let Err(err) = Agent::new(AgentConfig {
local_pwd: "xxxxxx".to_owned(),
..Default::default()
})
.await
{
assert_eq!(err, *ERR_LOCAL_PWD_INSUFFICIENT_BITS);
} else {
panic!("expected error, but got ok");
}
Ok(())
}
// Assert that Agent on Failure deletes all existing candidates
// User can then do an ICE Restart to bring agent back
#[tokio::test]
async fn test_connection_state_failed_delete_all_candidates() -> Result<(), Error> {
let one_second = Duration::from_secs(1);
let keepalive_interval = Duration::from_secs(0);
let cfg0 = AgentConfig {
network_types: supported_network_types(),
disconnected_timeout: Some(one_second),
failed_timeout: Some(one_second),
keepalive_interval: Some(keepalive_interval),
..Default::default()
};
let cfg1 = AgentConfig {
network_types: supported_network_types(),
disconnected_timeout: Some(one_second),
failed_timeout: Some(one_second),
keepalive_interval: Some(keepalive_interval),
..Default::default()
};
let a_agent = Arc::new(Agent::new(cfg0).await?);
let b_agent = Arc::new(Agent::new(cfg1).await?);
let (is_failed_tx, mut is_failed_rx) = mpsc::channel::<()>(1);
let is_failed_tx = Arc::new(Mutex::new(Some(is_failed_tx)));
a_agent
.on_connection_state_change(Box::new(move |c: ConnectionState| {
let is_failed_tx_clone = Arc::clone(&is_failed_tx);
Box::pin(async move {
if c == ConnectionState::Failed {
let mut tx = is_failed_tx_clone.lock().await;
tx.take();
}
})
}))
.await;
connect_with_vnet(&a_agent, &b_agent).await?;
let _ = is_failed_rx.recv().await;
{
let ai = a_agent.agent_internal.lock().await;
assert_eq!(ai.remote_candidates.len(), 0);
assert_eq!(ai.local_candidates.len(), 0);
}
a_agent.close().await?;
b_agent.close().await?;
Ok(())
}
// Assert that the ICE Agent can go directly from Connecting -> Failed on both sides
#[tokio::test]
async fn test_connection_state_connecting_to_failed() -> Result<(), Error> {
let one_second = Duration::from_secs(1);
let keepalive_interval = Duration::from_secs(0);
let cfg0 = AgentConfig {
disconnected_timeout: Some(one_second),
failed_timeout: Some(one_second),
keepalive_interval: Some(keepalive_interval),
..Default::default()
};
let cfg1 = AgentConfig {
disconnected_timeout: Some(one_second),
failed_timeout: Some(one_second),
keepalive_interval: Some(keepalive_interval),
..Default::default()
};
let a_agent = Arc::new(Agent::new(cfg0).await?);
let b_agent = Arc::new(Agent::new(cfg1).await?);
let is_failed = WaitGroup::new();
let is_checking = WaitGroup::new();
let connection_state_check = move |wf: Worker, wc: Worker| {
let wf = Arc::new(Mutex::new(Some(wf)));
let wc = Arc::new(Mutex::new(Some(wc)));
let hdlr_fn: OnConnectionStateChangeHdlrFn = Box::new(move |c: ConnectionState| {
let wf_clone = Arc::clone(&wf);
let wc_clone = Arc::clone(&wc);
Box::pin(async move {
if c == ConnectionState::Failed {
let mut f = wf_clone.lock().await;
f.take();
} else if c == ConnectionState::Checking {
let mut c = wc_clone.lock().await;
c.take();
} else if c == ConnectionState::Connected || c == ConnectionState::Completed {
panic!("Unexpected ConnectionState: {}", c);
}
})
});
hdlr_fn
};
let (wf1, wc1) = (is_failed.worker(), is_checking.worker());
a_agent
.on_connection_state_change(connection_state_check(wf1, wc1))
.await;
let (wf2, wc2) = (is_failed.worker(), is_checking.worker());
b_agent
.on_connection_state_change(connection_state_check(wf2, wc2))
.await;
let agent_a = Arc::clone(&a_agent);
tokio::spawn(async move {
let (_cancel_tx, cancel_rx) = mpsc::channel(1);
let result = agent_a
.accept(cancel_rx, "InvalidFrag".to_owned(), "InvalidPwd".to_owned())
.await;
assert!(result.is_err());
});
let agent_b = Arc::clone(&b_agent);
tokio::spawn(async move {
let (_cancel_tx, cancel_rx) = mpsc::channel(1);
let result = agent_b
.dial(cancel_rx, "InvalidFrag".to_owned(), "InvalidPwd".to_owned())
.await;
assert!(result.is_err());
});
is_checking.wait().await;
is_failed.wait().await;
a_agent.close().await?;
b_agent.close().await?;
Ok(())
}
#[tokio::test]
async fn test_agent_restart_during_gather() -> Result<(), Error> {
//"Restart During Gather"
let agent = Agent::new(AgentConfig::default()).await?;
agent
.gathering_state
.store(GatheringState::Gathering as u8, Ordering::SeqCst);
if let Err(err) = agent.restart("".to_owned(), "".to_owned()).await {
assert_eq!(err, *ERR_RESTART_WHEN_GATHERING);
} else {
panic!("expected error, but got ok");
}
agent.close().await?;
Ok(())
}
#[tokio::test]
async fn test_agent_restart_when_closed() -> Result<(), Error> {
//"Restart When Closed"
let agent = Agent::new(AgentConfig::default()).await?;
agent.close().await?;
if let Err(err) = agent.restart("".to_owned(), "".to_owned()).await {
assert_eq!(err, *ERR_CLOSED);
} else {
panic!("expected error, but got ok");
}
Ok(())
}
#[tokio::test]
async fn test_agent_restart_one_side() -> Result<(), Error> {
let one_second = Duration::from_secs(1);
//"Restart One Side"
let (_, _, agent_a, agent_b) = pipe(
Some(AgentConfig {
disconnected_timeout: Some(one_second),
failed_timeout: Some(one_second),
..Default::default()
}),
Some(AgentConfig {
disconnected_timeout: Some(one_second),
failed_timeout: Some(one_second),
..Default::default()
}),
)
.await?;
let (cancel_tx, mut cancel_rx) = mpsc::channel::<()>(1);
let cancel_tx = Arc::new(Mutex::new(Some(cancel_tx)));
agent_b
.on_connection_state_change(Box::new(move |c: ConnectionState| {
let cancel_tx_clone = Arc::clone(&cancel_tx);
Box::pin(async move {
if c == ConnectionState::Failed || c == ConnectionState::Disconnected {
let mut tx = cancel_tx_clone.lock().await;
tx.take();
}
})
}))
.await;
agent_a.restart("".to_owned(), "".to_owned()).await?;
let _ = cancel_rx.recv().await;
agent_a.close().await?;
agent_b.close().await?;
Ok(())
}
#[tokio::test]
async fn test_agent_restart_both_side() -> Result<(), Error> {
let one_second = Duration::from_secs(1);
//"Restart Both Sides"
// Get all addresses of candidates concatenated
let generate_candidate_address_strings =
|res: Result<Vec<Arc<dyn Candidate + Send + Sync>>, Error>| -> String {
assert!(res.is_ok());
let mut out = String::new();
if let Ok(candidates) = res {
for c in candidates {
out += c.address().as_str();
out += ":";
out += c.port().to_string().as_str();
}
}
out
};
// Store the original candidates, confirm that after we reconnect we have new pairs
let (_, _, agent_a, agent_b) = pipe(
Some(AgentConfig {
disconnected_timeout: Some(one_second),
failed_timeout: Some(one_second),
..Default::default()
}),
Some(AgentConfig {
disconnected_timeout: Some(one_second),
failed_timeout: Some(one_second),
..Default::default()
}),
)
.await?;
let conn_afirst_candidates =
generate_candidate_address_strings(agent_a.get_local_candidates().await);
let conn_bfirst_candidates =
generate_candidate_address_strings(agent_b.get_local_candidates().await);
let (a_notifier, mut a_connected) = on_connected();
agent_a.on_connection_state_change(a_notifier).await;
let (b_notifier, mut b_connected) = on_connected();
agent_b.on_connection_state_change(b_notifier).await;
// Restart and Re-Signal
agent_a.restart("".to_owned(), "".to_owned()).await?;
agent_b.restart("".to_owned(), "".to_owned()).await?;
// Exchange Candidates and Credentials
let (ufrag, pwd) = agent_b.get_local_user_credentials().await;
agent_a.set_remote_credentials(ufrag, pwd).await?;
let (ufrag, pwd) = agent_a.get_local_user_credentials().await;
agent_b.set_remote_credentials(ufrag, pwd).await?;
gather_and_exchange_candidates(&agent_a, &agent_b).await?;
// Wait until both have gone back to connected
let _ = a_connected.recv().await;
let _ = b_connected.recv().await;
// Assert that we have new candiates each time
assert_ne!(
conn_afirst_candidates,
generate_candidate_address_strings(agent_a.get_local_candidates().await)
);
assert_ne!(
conn_bfirst_candidates,
generate_candidate_address_strings(agent_b.get_local_candidates().await)
);
agent_a.close().await?;
agent_b.close().await?;
Ok(())
}
#[tokio::test]
async fn test_get_remote_credentials() -> Result<(), Error> {
let a = Agent::new(AgentConfig::default()).await?;
let (remote_ufrag, remote_pwd) = {
let mut ai = a.agent_internal.lock().await;
ai.remote_ufrag = "remoteUfrag".to_owned();
ai.remote_pwd = "remotePwd".to_owned();
(ai.remote_ufrag.to_owned(), ai.remote_pwd.to_owned())
};
let (actual_ufrag, actual_pwd) = a.get_remote_user_credentials().await;
assert_eq!(actual_ufrag, remote_ufrag);
assert_eq!(actual_pwd, remote_pwd);
a.close().await?;
Ok(())
}
#[tokio::test]
async fn test_close_in_connection_state_callback() -> Result<(), Error> {
let disconnected_duration = Duration::from_secs(1);
let failed_duration = Duration::from_secs(1);
let keepalive_interval = Duration::from_secs(0);
let cfg0 = AgentConfig {
urls: vec![],
network_types: supported_network_types(),
disconnected_timeout: Some(disconnected_duration),
failed_timeout: Some(failed_duration),
keepalive_interval: Some(keepalive_interval),
check_interval: Duration::from_millis(500),
..Default::default()
};
let cfg1 = AgentConfig {
urls: vec![],
network_types: supported_network_types(),
disconnected_timeout: Some(disconnected_duration),
failed_timeout: Some(failed_duration),
keepalive_interval: Some(keepalive_interval),
check_interval: Duration::from_millis(500),
..Default::default()
};
let a_agent = Arc::new(Agent::new(cfg0).await?);
let b_agent = Arc::new(Agent::new(cfg1).await?);
let (is_closed_tx, mut is_closed_rx) = mpsc::channel::<()>(1);
let (is_connected_tx, mut is_connected_rx) = mpsc::channel::<()>(1);
let is_closed_tx = Arc::new(Mutex::new(Some(is_closed_tx)));
let is_connected_tx = Arc::new(Mutex::new(Some(is_connected_tx)));
a_agent
.on_connection_state_change(Box::new(move |c: ConnectionState| {
let is_closed_tx_clone = Arc::clone(&is_closed_tx);
let is_connected_tx_clone = Arc::clone(&is_connected_tx);
Box::pin(async move {
if c == ConnectionState::Connected {
let mut tx = is_connected_tx_clone.lock().await;
tx.take();
} else if c == ConnectionState::Closed {
let mut tx = is_closed_tx_clone.lock().await;
tx.take();
}
})
}))
.await;
connect_with_vnet(&a_agent, &b_agent).await?;
let _ = is_connected_rx.recv().await;
a_agent.close().await?;
let _ = is_closed_rx.recv().await;
b_agent.close().await?;
Ok(())
}
#[tokio::test]
async fn test_run_task_in_connection_state_callback() -> Result<(), Error> {
let one_second = Duration::from_secs(1);
let keepalive_interval = Duration::from_secs(0);
let cfg0 = AgentConfig {
urls: vec![],
network_types: supported_network_types(),
disconnected_timeout: Some(one_second),
failed_timeout: Some(one_second),
keepalive_interval: Some(keepalive_interval),
check_interval: Duration::from_millis(50),
..Default::default()
};
let cfg1 = AgentConfig {
urls: vec![],
network_types: supported_network_types(),
disconnected_timeout: Some(one_second),
failed_timeout: Some(one_second),
keepalive_interval: Some(keepalive_interval),
check_interval: Duration::from_millis(50),
..Default::default()
};
let a_agent = Arc::new(Agent::new(cfg0).await?);
let b_agent = Arc::new(Agent::new(cfg1).await?);
let (is_complete_tx, mut is_complete_rx) = mpsc::channel::<()>(1);
let is_complete_tx = Arc::new(Mutex::new(Some(is_complete_tx)));
a_agent
.on_connection_state_change(Box::new(move |c: ConnectionState| {
let is_complete_tx_clone = Arc::clone(&is_complete_tx);
Box::pin(async move {
if c == ConnectionState::Connected {
let mut tx = is_complete_tx_clone.lock().await;
tx.take();
}
})
}))
.await;
connect_with_vnet(&a_agent, &b_agent).await?;
let _ = is_complete_rx.recv().await;
let _ = a_agent.get_local_user_credentials().await;
a_agent.restart("".to_owned(), "".to_owned()).await?;
a_agent.close().await?;
b_agent.close().await?;
Ok(())
}
#[tokio::test]
async fn test_run_task_in_selected_candidate_pair_change_callback() -> Result<(), Error> {
let one_second = Duration::from_secs(1);
let keepalive_interval = Duration::from_secs(0);
let cfg0 = AgentConfig {
urls: vec![],
network_types: supported_network_types(),
disconnected_timeout: Some(one_second),
failed_timeout: Some(one_second),
keepalive_interval: Some(keepalive_interval),
check_interval: Duration::from_millis(50),
..Default::default()
};
let cfg1 = AgentConfig {
urls: vec![],
network_types: supported_network_types(),
disconnected_timeout: Some(one_second),
failed_timeout: Some(one_second),
keepalive_interval: Some(keepalive_interval),
check_interval: Duration::from_millis(50),
..Default::default()
};
let a_agent = Arc::new(Agent::new(cfg0).await?);
let b_agent = Arc::new(Agent::new(cfg1).await?);
let (is_tested_tx, mut is_tested_rx) = mpsc::channel::<()>(1);
let is_tested_tx = Arc::new(Mutex::new(Some(is_tested_tx)));
a_agent
.on_selected_candidate_pair_change(Box::new(
move |_: &(dyn Candidate + Send + Sync), _: &(dyn Candidate + Send + Sync)| {
let is_tested_tx_clone = Arc::clone(&is_tested_tx);
Box::pin(async move {
let mut tx = is_tested_tx_clone.lock().await;
tx.take();
})
},
))
.await;
let (is_complete_tx, mut is_complete_rx) = mpsc::channel::<()>(1);
let is_complete_tx = Arc::new(Mutex::new(Some(is_complete_tx)));
a_agent
.on_connection_state_change(Box::new(move |c: ConnectionState| {
let is_complete_tx_clone = Arc::clone(&is_complete_tx);
Box::pin(async move {
if c == ConnectionState::Connected {
let mut tx = is_complete_tx_clone.lock().await;
tx.take();
}
})
}))
.await;
connect_with_vnet(&a_agent, &b_agent).await?;
let _ = is_complete_rx.recv().await;
let _ = is_tested_rx.recv().await;
let _ = a_agent.get_local_user_credentials().await;
a_agent.close().await?;
b_agent.close().await?;
Ok(())
}
// Assert that a Lite agent goes to disconnected and failed
#[tokio::test]
async fn test_lite_lifecycle() -> Result<(), Error> {
let (a_notifier, mut a_connected_rx) = on_connected();
let a_agent = Arc::new(
Agent::new(AgentConfig {
network_types: supported_network_types(),
multicast_dns_mode: MulticastDnsMode::Disabled,
..Default::default()
})
.await?,
);
a_agent.on_connection_state_change(a_notifier).await;
let disconnected_duration = Duration::from_secs(1);
let failed_duration = Duration::from_secs(1);
let keepalive_interval = Duration::from_secs(0);
let b_agent = Arc::new(
Agent::new(AgentConfig {
lite: true,
candidate_types: vec![CandidateType::Host],
network_types: supported_network_types(),
multicast_dns_mode: MulticastDnsMode::Disabled,
disconnected_timeout: Some(disconnected_duration),
failed_timeout: Some(failed_duration),
keepalive_interval: Some(keepalive_interval),
check_interval: Duration::from_millis(500),
..Default::default()
})
.await?,
);
let (b_connected_tx, mut b_connected_rx) = mpsc::channel::<()>(1);
let (b_disconnected_tx, mut b_disconnected_rx) = mpsc::channel::<()>(1);
let (b_failed_tx, mut b_failed_rx) = mpsc::channel::<()>(1);
let b_connected_tx = Arc::new(Mutex::new(Some(b_connected_tx)));
let b_disconnected_tx = Arc::new(Mutex::new(Some(b_disconnected_tx)));
let b_failed_tx = Arc::new(Mutex::new(Some(b_failed_tx)));
b_agent
.on_connection_state_change(Box::new(move |c: ConnectionState| {
let b_connected_tx_clone = Arc::clone(&b_connected_tx);
let b_disconnected_tx_clone = Arc::clone(&b_disconnected_tx);
let b_failed_tx_clone = Arc::clone(&b_failed_tx);
Box::pin(async move {
if c == ConnectionState::Connected {
let mut tx = b_connected_tx_clone.lock().await;
tx.take();
} else if c == ConnectionState::Disconnected {
let mut tx = b_disconnected_tx_clone.lock().await;
tx.take();
} else if c == ConnectionState::Failed {
let mut tx = b_failed_tx_clone.lock().await;
tx.take();
}
})
}))
.await;
connect_with_vnet(&b_agent, &a_agent).await?;
let _ = a_connected_rx.recv().await;
let _ = b_connected_rx.recv().await;
a_agent.close().await?;
let _ = b_disconnected_rx.recv().await;
let _ = b_failed_rx.recv().await;
b_agent.close().await?;
Ok(())
}
|
mod callbacks;
pub mod config;
//pub struct Session { raw: *mut sp_session }
|
use sodiumoxide::crypto::box_::curve25519xsalsa20poly1305;
use std::path::Path;
/// Core errors.
#[derive(Debug, Fail)]
pub enum Error {
/// TODO(refactor): Improve error types.
#[fail(display = "CoreError::Unwrap")]
Unwrap,
/// sodiumoxide initialisation error.
#[fail(display = "SodiumoxideInit::Unwrap")]
SodiumoxideInit(()),
}
/// Public-key encryption key.
#[derive(Debug, Serialize, Deserialize)]
pub struct Key {
alg: String,
sk: Vec<u8>,
pk: Vec<u8>,
}
impl Key {
/// Create new key.
pub fn create() -> Self {
let (pk, sk) = curve25519xsalsa20poly1305::gen_keypair();
Key {
alg: "curve25519xsalsa20poly1305".to_owned(),
sk: sk.0.to_vec(),
pk: pk.0.to_vec(),
}
}
/// Return key deserialised from string reference.
pub fn from_str(input: &str) -> Result<Self, Error> {
serde_json::from_str(input).map_err(|_err| Error::Unwrap)
}
/// Read key from file at path.
pub fn read_from_file(path: &Path) -> Result<Self, Error> {
use std::fs::File;
use std::io::prelude::*;
if !path.exists() {
// File does not exist at path.
return Err(Error::Unwrap);
}
let mut file = File::open(&path).map_err(|_err| Error::Unwrap)?;
let mut data = String::new();
file.read_to_string(&mut data)
.map_err(|_err| Error::Unwrap)?;
Key::from_str(&data)
}
/// Return key serialised as string.
pub fn to_string(&self) -> Result<String, Error> {
serde_json::to_string(self).map_err(|_err| Error::Unwrap)
}
/// Write serialised key to file at path.
pub fn write_to_file(self, path: &Path) -> Result<Self, Error> {
use std::fs::File;
use std::io::prelude::*;
if path.exists() {
// File exists, do not overwrite files.
return Err(Error::Unwrap);
}
let data = self.to_string()?;
let mut file = File::create(&path).map_err(|_err| Error::Unwrap)?;
file.write_all(data.as_bytes())
.map_err(|_err| Error::Unwrap)?;
Ok(self)
}
}
/// Initialise library.
pub fn init() -> Result<(), Error> {
sodiumoxide::init().map_err(Error::SodiumoxideInit)
}
|
// Copyright (c) 2021 asisdrico <asisdrico@outlook.com>
//
// Licensed under the MIT license
// <LICENSE or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! trsh server is the server component of the tiny rust shell
//! when started without options the server listens to the
//! default server_addr.
//!
//! the follwing option are avalaible:
//! -s <ip:port> - listens on ip / port and wait for backconnects
//!
//! the following commands are available:
//!
//! <command> - executes the command an returns the result (default is "w")
//!
//! get <source file> <target dir> - transfer a file from the client to the server
//! put <source file> <target dir> - transfer a file from the server to the client
//!
//! shell <-r> - start an interactive shell on the client an forward it to server, when
//! started with <-r> the shell is set to raw mode
//!
//! the keys for encryption are set in build.rs
use io::BufReader;
use std::io;
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::os::unix::io::RawFd;
use std::os::unix::io::{AsRawFd, FromRawFd};
use std::path;
use std::process::exit;
use std::{
fs::File,
io::prelude::*,
sync::mpsc::{self, Receiver, Sender},
};
use clap::{App, Arg, SubCommand};
use terminal_size::{terminal_size, Height, Width};
use termios::*;
use cryptolib::cryptolib_salsa::Crypto;
// AES const KEY: &'static [u8; 16] = b"Fahm9Oruet8zahco";
// AES const IV: &'static [u8; 16] = b"biTh0eoYbiTh0eoY";
//const KEY: &'static [u8; 32] = b"Fahm9Oruet8zahcoFahm9Oruet8zahco";
//const IV: &'static [u8; 8] = b"biTh0eoY";
//const ID: &'static str = "ohpie2naiwoo1lah6aeteexi5beiRas7";
const ID: &'static str = env!("TRSH_ID");
const KEY: &'static [u8] = env!("TRSH_KEY").as_bytes();
const IV: &'static [u8] = env!("TRSH_IV").as_bytes();
/// starting point of the server
fn main() {
let flags = App::new("Server")
.version("1.0")
.author("asisdrico <asisdrico@outlook.com>")
.about("tiny rust shell server")
.arg(
Arg::with_name("server_addr")
.long("server_addr")
.short("s")
.value_name("ADDRESS")
.help("Sets the server address to listen to.")
.required(false)
.default_value("127.0.0.1:4444")
.takes_value(true),
)
.arg(
Arg::with_name("redirect_stderr")
.long("redirect_stderr")
.short("r")
.value_name("REDIRECT")
.help("redirects stderr")
.required(false)
.takes_value(false),
)
.arg(
Arg::with_name("COMMAND")
.help("command to execute")
.required(false)
.default_value("w")
.takes_value(true)
.index(1),
)
.subcommand(
SubCommand::with_name("get")
.help("get a file")
.arg(
Arg::with_name("SOURCE_FILE")
.required(true)
.takes_value(true)
.index(1),
)
.arg(
Arg::with_name("TARGET_DIR")
.required(true)
.takes_value(true)
.index(2),
),
)
.subcommand(
SubCommand::with_name("put")
.help("put a file")
.arg(
Arg::with_name("SOURCE_FILE")
.required(true)
.takes_value(true)
.index(1),
)
.arg(
Arg::with_name("TARGET_DIR")
.required(true)
.takes_value(true)
.index(2),
),
)
.subcommand(
SubCommand::with_name("shell").help("allocate shell").arg(
Arg::with_name("raw_mode")
.long("raw")
.short("r")
.value_name("RAW")
.help("sets terminal into raw mode")
.required(false)
.takes_value(false),
),
)
.get_matches();
let server_addr = flags.value_of("server_addr").unwrap();
let server_addr = server_addr
.parse::<SocketAddr>()
.unwrap_or_else(|e| panic!(r#"--server_addr value "{}" invalid: {}"#, server_addr, e));
let listener = TcpListener::bind(server_addr).unwrap();
let (stream, addr) = listener.accept().expect("no connection");
println!("Connection from {}", addr);
drop(listener);
handle_connection(stream, flags);
}
fn handle_connection(mut stream: TcpStream, flags: clap::ArgMatches) {
let command = flags.value_of("COMMAND").unwrap();
let redirect: &str = " 2>&1";
let mut scommand;
if flags.is_present("redirect_stderr") {
scommand = format!("{}{}", command, redirect);
} else {
scommand = format!("{}", command);
}
if let Some(flags) = flags.subcommand_matches("get") {
if flags.is_present("SOURCE_FILE") && flags.is_present("TARGET_DIR") {
println!(
"GET --> {} to {}",
flags.value_of("SOURCE_FILE").unwrap(),
flags.value_of("TARGET_DIR").unwrap()
);
scommand = format!("{}|{}", "GET", flags.value_of("SOURCE_FILE").unwrap());
send_remote_command(&mut stream, &mut scommand);
handle_get_command(
stream,
flags.value_of("SOURCE_FILE").unwrap(),
flags.value_of("TARGET_DIR").unwrap(),
);
}
} else if let Some(flags) = flags.subcommand_matches("put") {
if flags.is_present("SOURCE_FILE") && flags.is_present("TARGET_DIR") {
println!(
"PUT --> {} to {}",
flags.value_of("SOURCE_FILE").unwrap(),
flags.value_of("TARGET_DIR").unwrap()
);
let source_file = path::Path::new(flags.value_of("SOURCE_FILE").unwrap());
let filename = source_file.file_name().unwrap();
scommand = format!(
"{}|{}|{}",
"PUT",
filename.to_str().unwrap(),
flags.value_of("TARGET_DIR").unwrap()
);
send_remote_command(&mut stream, &mut scommand);
handle_put_command(
stream,
flags.value_of("SOURCE_FILE").unwrap(),
flags.value_of("TARGET_DIR").unwrap(),
);
}
} else if let Some(flags) = flags.subcommand_matches("shell") {
if let Some((Width(w), Height(h))) = terminal_size() {
scommand = format!("{}|{}|{}", "SHELL", w, h);
} else {
scommand = format!("{}|{}|{}", "SHELL", 80, 20);
}
send_remote_command(&mut stream, &mut scommand);
if flags.is_present("raw_mode") {
run_shell(stream, true);
} else {
run_shell(stream, false)
}
} else {
send_remote_command(&mut stream, &mut scommand);
handle_os_command(stream);
}
}
fn send_remote_command(mut stream: &TcpStream, command: &str) {
let mut cr = Crypto::new(KEY, IV).unwrap();
let mut buffer = [0; 1024];
let bytes_read = stream.read(&mut buffer).unwrap();
cr.read(&mut buffer[..bytes_read]).unwrap();
let remote_id = String::from_utf8_lossy(&cr.buffer()[..bytes_read]);
println!("Remote ID: {}", remote_id);
if remote_id != ID {
println!("ID not valid remote[{}] <--> [{}]", remote_id, ID);
exit(1);
}
cr.write(command.as_bytes()).unwrap();
println!("Len CR Buffer {}", cr.buffer().len());
stream.write(cr.buffer()).unwrap();
stream.flush().unwrap();
}
fn handle_os_command(mut stream: TcpStream) {
let mut cr = Crypto::new(KEY, IV).unwrap();
let stdout = io::stdout();
let mut handle = stdout.lock();
cr.copy(&mut stream, &mut handle).unwrap();
}
fn handle_get_command(mut stream: TcpStream, source_file: &str, target_dir: &str) {
println!("GET {}", source_file);
let source_path = path::Path::new(source_file);
let filename = source_path.file_name().unwrap();
let target_path = path::Path::new(target_dir).join(filename);
let mut cr = Crypto::new(KEY, IV).unwrap();
let mut output = match File::create(target_path) {
Ok(output) => output,
Err(e) => {
println!("could not create file: {}", e);
return;
}
};
//let (tx, rx) = channel();
let (tx, rx): (Sender<u64>, Receiver<u64>) = mpsc::channel();
let mut counter = 0;
::std::thread::spawn(move || loop {
counter = match rx.recv() {
Ok(counter) => counter,
Err(_e) => {
break;
}
};
if counter == 0 {
break;
}
println!("Transferred: {}\r", counter);
});
match cr.copy_buf(&mut stream, &mut output, &tx) {
Ok(cnt) => println!("{} bytes were transferred", cnt),
Err(e) => {
println!("error copying data: {}", e);
return;
}
};
tx.send(0).unwrap();
drop(output);
}
fn handle_put_command(mut stream: TcpStream, source_file: &str, target_dir: &str) {
println!("PUT {} to {}", source_file, target_dir);
let mut cr = Crypto::new(KEY, IV).unwrap();
let input = match File::open(source_file) {
Ok(input) => input,
Err(e) => {
println!("could not open source file: {}", e);
return;
}
};
let mut bufreader = BufReader::new(input);
let (tx, rx): (Sender<u64>, Receiver<u64>) = mpsc::channel();
let mut counter = 0;
::std::thread::spawn(move || loop {
counter = match rx.recv() {
Ok(counter) => counter,
Err(_e) => {
break;
}
};
if counter == 0 {
break;
}
println!("Transferred: {}\r", counter);
});
match cr.copy_buf(&mut bufreader, &mut stream, &tx) {
Ok(cnt) => println!("{} bytes were transferred", cnt),
Err(e) => {
println!("error copying data: {}", e);
return;
}
};
tx.send(0).unwrap();
drop(bufreader);
}
fn run_shell(mut s: TcpStream, raw: bool) {
let l_stdin = io::stdin().as_raw_fd();
let mut sane_termios: Termios = Termios::from_fd(l_stdin).unwrap();
if raw {
sane_termios = setup_raw(l_stdin).unwrap();
}
let mut f_stdin = unsafe { File::from_raw_fd(l_stdin) };
let mut f_stdout = unsafe { File::from_raw_fd(io::stdout().as_raw_fd()) };
println!("created local fds");
let mut in_stream = s.try_clone().unwrap();
::std::thread::spawn(move || copyio(&mut f_stdin, &mut in_stream));
let child = ::std::thread::spawn(move || copyio(&mut s, &mut f_stdout));
let _res = child.join();
if raw {
setup_sane(l_stdin, &sane_termios).unwrap();
}
}
fn copyio(rin: &mut dyn Read, rout: &mut dyn Write) {
let mut cr = Crypto::new(KEY, IV).unwrap();
let _br = &match cr.copy(rin, rout) {
Ok(b) => b,
Err(e) => {
println!("Error copy: {}", e);
return;
}
};
}
fn setup_raw(fd: RawFd) -> io::Result<termios::Termios> {
let mut termios = Termios::from_fd(fd)?;
let stermios = termios;
cfmakeraw(&mut termios);
tcsetattr(fd, TCSANOW, &mut termios)?;
Ok(stermios)
}
fn setup_sane(fd: RawFd, &termios: &termios::Termios) -> io::Result<()> {
tcsetattr(fd, TCSANOW, &termios)?;
Ok(())
}
|
mod models;
pub use self::models::{ChecklistModel, ChecklistHierarchy};
|
use super::*;
use std::str::from_utf8;
use std::io::Read;
pub struct ImportSection<'a>(pub &'a [u8], pub usize);
pub struct ImportEntryIterator<'a>(&'a [u8], usize);
pub struct ImportEntry<'a> {
pub module: &'a str,
pub field: &'a str,
pub contents: ImportEntryContents,
}
pub enum ImportEntryContents {
Function(u32),
Table {
element_type: u8,
limits: ResizableLimits
},
Memory(ResizableLimits),
Global {
ty: ValueType,
mutable: bool
},
}
pub struct ResizableLimits {
pub initial: u32,
pub maximum: Option<u32>,
}
impl<'a> ImportSection<'a> {
pub fn entries(&self) -> ImportEntryIterator<'a> {
ImportEntryIterator(self.0, self.1)
}
}
impl<'a> Iterator for ImportEntryIterator<'a> {
type Item = Result<ImportEntry<'a>, Error>;
fn next(&mut self) -> Option<Result<ImportEntry<'a>, Error>> {
if self.1 == 0 {
return None
}
self.1 -= 1;
let mlen = try_opt!(read_varuint(&mut self.0));
let module = {
let res = &self.0[..mlen as usize];
self.0 = &self.0[mlen as usize..];
try_opt!(from_utf8(res))
};
let flen = try_opt!(read_varuint(&mut self.0));
let field = {
let res = &self.0[..flen as usize];
self.0 = &self.0[flen as usize..];
try_opt!(from_utf8(res))
};
let mut kind = [0; 1];
try_opt!((&mut self.0).read_exact(&mut kind));
let kind = try_opt!(ExternalKind::from_int(kind[0]).ok_or(Error::UnknownVariant("external kind")));
let contents = match kind {
ExternalKind::Function => ImportEntryContents::Function(try_opt!(
read_varuint(&mut self.0)) as u32
),
ExternalKind::Table => ImportEntryContents::Table {
element_type: {
let mut ty = [0; 1];
try_opt!((&mut self.0).read_exact(&mut ty));
ty[0]
},
limits: try_opt!(ResizableLimits::parse(&mut self.0)),
},
ExternalKind::Memory => ImportEntryContents::Memory(
try_opt!(ResizableLimits::parse(&mut self.0))
),
ExternalKind::Global => ImportEntryContents::Global {
ty: {
let mut ty = [0; 1];
try_opt!((&mut self.0).read_exact(&mut ty));
try_opt!(ValueType::from_int(ty[0]).ok_or(Error::UnknownVariant("value type")))
},
mutable: try_opt!(read_varuint(&mut self.0)) != 0,
},
};
Some(Ok(ImportEntry {
module: module,
field: field,
contents: contents,
}))
}
}
impl ResizableLimits {
pub fn parse(mut iter: &mut &[u8]) -> Result<ResizableLimits, Error> {
let flags = try!(read_varuint(iter));
let initial = try!(read_varuint(iter));
let maximum = if flags & 0x1 != 0 {
Some(try!(read_varuint(iter)))
} else {
None
};
Ok(ResizableLimits {
initial: initial as u32,
maximum: maximum.map(|x| x as u32),
})
}
}
|
use crate::day9::{intcode_computer, parse_program};
use std::collections::HashMap;
#[aoc_generator(day13)]
fn day13_gen(input: &str) -> Vec<i64> {
parse_program(input)
}
#[aoc(day13, part1)]
fn solve_p1(tape: &[i64]) -> usize {
let mut tape = tape.to_owned();
let mut screen = HashMap::new();
let mut i = 0;
let mut relative_base = 0;
loop {
let x = intcode_computer(&mut tape, &mut i, &mut relative_base, || 0);
if x == -1 {
break;
}
let y = intcode_computer(&mut tape, &mut i, &mut relative_base, || 0);
let tile_type = intcode_computer(&mut tape, &mut i, &mut relative_base, || 0);
screen
.entry(tile_type)
.or_insert_with(Vec::new)
.push((x, y));
}
screen.get(&2).unwrap().len()
}
#[aoc(day13, part2)]
fn solve_p2(tape: &[i64]) -> i64 {
let mut tape = tape.to_owned();
tape[0] = 2;
let mut screen = HashMap::new();
fn get_move(screen: &HashMap<(i64, i64), i64>) -> i64 {
let mut paddle_pos = 0;
let mut ball_pos = 0;
// We only need to print out the screen when it asks for input, because that's when it's finished drawing
// Clear the terminal
//print!("{}[2J", 27 as char);
if cfg!(show_game) {
for y in 0..20 {
for x in 0..50 {
let tile_type = *screen.get(&(x, y)).unwrap_or(&0);
let c = match tile_type {
0 => " ",
1 => "โ",
2 => "โฃ",
3 => {
paddle_pos = x;
"โ"
}
4 => {
ball_pos = x;
"โ"
}
_ => panic!("Unrecognized tiletype"),
};
print!("{}", c);
}
println!();
}
}
(ball_pos - paddle_pos).signum()
}
let mut i = 0;
let mut relative_base = 0;
let mut answer = 0;
loop {
let x = intcode_computer(&mut tape, &mut i, &mut relative_base, || get_move(&screen));
let y = intcode_computer(&mut tape, &mut i, &mut relative_base, || get_move(&screen));
let tile_type =
intcode_computer(&mut tape, &mut i, &mut relative_base, || get_move(&screen));
if x == -1 && y == 0 {
answer = tile_type;
}
if tile_type == -1 {
break;
}
screen.insert((x, y), tile_type);
}
answer
}
|
use crate::mt19937::{B, C, L, S, T, U};
use std::u32;
// The following were cribbed from https://jazzy.id.au/2010/09/22/cracking_random_number_generators_part_3.html
// I managed the xor parts on my own, but TBH I still don't completely understand how the mask stuff works
fn unbitshift_right_xor(v: u64, shift: usize) -> u64 {
let mut i = 0;
let mut result: u64 = 0;
let mut value: u64 = v;
while i * shift < 32 {
let partmask: u64 = ((u32::MAX << (32 - shift)) >> (shift * i) as u64).into();
let part: u64 = value & partmask;
value ^= part >> shift;
result |= part;
i += 1;
}
result
}
fn unbitshift_left_xor(v: u64, shift: usize, mask: u64) -> u64 {
let mut i = 0;
let mut result: u64 = 0;
let mut value: u64 = v;
while i * shift < 32 {
let partmask: u64 = ((u32::MAX >> (32 - shift)) << (shift * i) as u64).into();
let part: u64 = value & partmask;
value ^= (part << shift) & mask;
result |= part;
i += 1;
}
result
}
fn untemper(value: u32) -> u64 {
let mut result = unbitshift_right_xor(u64::from(value), L);
result = unbitshift_left_xor(result, T, C);
result = unbitshift_left_xor(result, S, B);
result = unbitshift_right_xor(result, U);
result as u64
}
#[cfg(test)]
mod tests {
use crate::challenges::set_3::challenge23::{
unbitshift_left_xor, unbitshift_right_xor, untemper,
};
use crate::mt19937::{temper, MarsenneTwister, B, C, L, S, T, U};
use rand::RngCore;
#[test]
fn test_unbitshift_left_xor() {
let mut original: u64 = rand::random::<u32>() as u64;
let mut value = original ^ ((original << S) & B);
assert_eq!(original, unbitshift_left_xor(value, S, B));
original = rand::random::<u32>() as u64;
value = original ^ ((original << T) & C);
assert_eq!(original, unbitshift_left_xor(value, T, C));
}
#[test]
fn test_unbitshift_right_xor() {
let mut original: u64 = rand::random::<u32>() as u64;
let mut value = original ^ (original >> L);
assert_eq!(original, unbitshift_right_xor(value, L));
original = rand::random::<u32>() as u64;
value = original ^ (original >> U);
assert_eq!(original, unbitshift_right_xor(value, U));
}
#[test]
fn test_untemper() {
let original: u64 = rand::random::<u32>() as u64;
let result: u32 = temper(original);
let untempered = untemper(result);
println!("original = {:x}, untempered = {:x}", original, untempered);
assert_eq!(original, untempered);
}
#[test]
// Twenty-Third cryptopals challenge - https://cryptopals.com/sets/3/challenges/23
fn challenge23() {
let mut mt = MarsenneTwister::from_seed(rand::random::<u32>());
let mut values = vec![];
for _ in 0..624 {
values.push(mt.next_u32());
}
let mut generator = vec![];
for index in 0..624 {
generator.push(untemper(values[index]));
}
let mut mt2 = MarsenneTwister::from_splice(&generator);
for index in 0..624 {
println!("Index = {}", index);
assert_eq!(values[index], mt2.next_u32());
}
}
}
|
use num::integer::lcm;
use util::*;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let timer = Timer::new();
let buses: Vec<Option<usize>> = input::lines::<String>(&std::env::args().nth(1).unwrap())[1]
.split(',')
.map(|n| n.parse::<usize>().ok())
.collect();
let mut offsets: Vec<usize> = vec![];
for (i, bus) in buses.iter().enumerate() {
if bus.is_some() {
offsets.push(i);
}
}
let buses: Vec<usize> = buses.into_iter().filter_map(|b| b).collect();
let mut departures = vec![0usize; buses.len()];
for i in 1..buses.len() {
let lcm = buses[0..i].iter().fold(1, |a, n| lcm(a, *n));
while departures[i] != departures[0] + offsets[i] {
if departures[i] < departures[0] + offsets[i] {
departures[i] +=
((departures[0] + offsets[i] - departures[i]) / buses[i]) * buses[i];
while departures[i] < departures[0] + offsets[i] {
departures[i] += buses[i];
}
} else {
for j in 0..i {
departures[j] += lcm;
}
}
}
}
timer.print();
println!("{}", departures[0]);
Ok(())
}
|
use crate::glsl::Glsl;
use std::convert::{TryFrom, TryInto};
use syn::spanned::Spanned;
use syn::{Error, Result};
#[derive(Debug, Clone)]
pub enum YaslScalarType {
Int,
UInt,
Float32,
Float64,
Bool,
}
impl TryFrom<syn::Type> for YaslScalarType {
type Error = Error;
fn try_from(ty: syn::Type) -> Result<Self> {
Ok(match ty {
syn::Type::Path(p) => {
if let Some(i) = p.path.get_ident() {
use YaslScalarType::*;
match i.to_string().as_str() {
"i32" => Int,
"u32" => UInt,
"f32" => Float32,
"f64" => Float64,
"bool" => Bool,
_ => return Err(Error::new(i.span(), "Unknown Type")),
}
} else {
return Err(Error::new(p.span(), "Unknown Type"));
}
}
_ => return Err(Error::new(ty.span(), "Unknown Type")),
})
}
}
impl TryFrom<&syn::GenericArgument> for YaslScalarType {
type Error = Error;
fn try_from(ty: &syn::GenericArgument) -> Result<Self> {
match ty {
syn::GenericArgument::Type(t) => Ok(t.to_owned().try_into()?),
_ => Err(Error::new(ty.span(), "Unknown Type")),
}
}
}
impl From<&YaslScalarType> for Glsl {
fn from(ty: &YaslScalarType) -> Glsl {
use YaslScalarType::*;
Glsl::Expr(
match ty {
Int => "int",
UInt => "uint",
Float32 => "float",
Float64 => "double",
Bool => "bool",
}
.into(),
)
}
}
|
#[derive(Serialize, Deserialize, Debug)]
pub struct Stats {
pub read: String,
pub network: Network,
pub memory_stats: MemoryStats,
pub cpu_stats: CpuStats,
pub blkio_stats: BlkioStats,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Network {
pub rx_dropped: u64,
pub rx_bytes: u64,
pub rx_errors: u64,
pub tx_packets: u64,
pub tx_dropped: u64,
pub rx_packets: u64,
pub tx_errors: u64,
pub tx_bytes: u64,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct MemoryStats {
pub max_usage: u64,
pub usage: u64,
pub failcnt: u64,
pub limit: u64,
pub stats: MemoryStat,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct MemoryStat {
pub total_pgmajfault: u64,
pub cache: u64,
pub mapped_file: u64,
pub total_inactive_file: u64,
pub pgpgout: u64,
pub rss: u64,
pub total_mapped_file: u64,
pub writeback: u64,
pub unevictable: u64,
pub pgpgin: u64,
pub total_unevictable: u64,
pub pgmajfault: u64,
pub total_rss: u64,
pub total_rss_huge: u64,
pub total_writeback: u64,
pub total_inactive_anon: u64,
pub rss_huge: u64,
pub hierarchical_memory_limit: u64,
pub hierarchical_memsw_limit: u64,
pub total_pgfault: u64,
pub total_active_file: u64,
pub active_anon: u64,
pub total_active_anon: u64,
pub total_pgpgout: u64,
pub total_cache: u64,
pub inactive_anon: u64,
pub active_file: u64,
pub pgfault: u64,
pub inactive_file: u64,
pub total_pgpgin: u64,
pub swap: u64,
pub total_swap: u64,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct CpuStats {
pub cpu_usage: CpuUsage,
pub system_cpu_usage: u64,
pub throttling_data: ThrottlingData,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct CpuUsage {
pub percpu_usage: Vec<u64>,
pub usage_in_usermode: u64,
pub total_usage: u64,
pub usage_in_kernelmode: u64,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ThrottlingData {
pub periods: u64,
pub throttled_periods: u64,
pub throttled_time: u64,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct BlkioStats {
pub io_service_bytes_recursive: Vec<BlkioStat>,
pub io_serviced_recursive: Vec<BlkioStat>,
pub io_queue_recursive: Vec<BlkioStat>,
pub io_service_time_recursive: Vec<BlkioStat>,
pub io_wait_time_recursive: Vec<BlkioStat>,
pub io_merged_recursive: Vec<BlkioStat>,
pub io_time_recursive: Vec<BlkioStat>,
pub sectors_recursive: Vec<BlkioStat>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct BlkioStat {
pub major: u64,
pub minor: u64,
pub op: String,
pub value: u64,
}
impl Clone for Stats {
fn clone(&self) -> Stats {
Stats {
read: self.read.clone(),
network: self.network.clone(),
memory_stats: self.memory_stats.clone(),
cpu_stats: self.cpu_stats.clone(),
blkio_stats: self.blkio_stats.clone(),
}
}
}
impl Clone for Network {
fn clone(&self) -> Self {
Network {
rx_dropped: self.rx_dropped,
rx_bytes: self.rx_bytes,
rx_errors: self.rx_errors,
tx_packets: self.tx_packets,
tx_dropped: self.tx_dropped,
rx_packets: self.rx_packets,
tx_errors: self.tx_errors,
tx_bytes: self.tx_bytes,
}
}
}
impl Clone for MemoryStats {
fn clone(&self) -> Self {
MemoryStats {
max_usage: self.max_usage,
usage: self.usage,
failcnt: self.failcnt,
limit: self.limit,
stats: self.stats.clone(),
}
}
}
impl Clone for MemoryStat {
fn clone(&self) -> Self {
MemoryStat {
total_pgmajfault: self.total_pgmajfault,
cache: self.cache,
mapped_file: self.mapped_file,
total_inactive_file: self.total_inactive_file,
pgpgout: self.pgpgout,
rss: self.rss,
total_mapped_file: self.total_mapped_file,
writeback: self.writeback,
unevictable: self.unevictable,
pgpgin: self.pgpgin,
total_unevictable: self.total_unevictable,
pgmajfault: self.pgmajfault,
total_rss: self.total_rss,
total_rss_huge: self.total_rss_huge,
total_writeback: self.total_writeback,
total_inactive_anon: self.total_inactive_anon,
rss_huge: self.rss_huge,
hierarchical_memory_limit: self.hierarchical_memory_limit,
hierarchical_memsw_limit: self.hierarchical_memsw_limit,
total_pgfault: self.total_pgfault,
total_active_file: self.total_active_file,
active_anon: self.active_anon,
total_active_anon: self.total_active_anon,
total_pgpgout: self.total_pgpgout,
total_cache: self.total_cache,
inactive_anon: self.inactive_anon,
active_file: self.active_file,
pgfault: self.pgfault,
inactive_file: self.inactive_file,
total_pgpgin: self.total_pgpgin,
swap: self.swap,
total_swap: self.total_swap,
}
}
}
impl Clone for CpuStats {
fn clone(&self) -> Self {
CpuStats {
cpu_usage: self.cpu_usage.clone(),
system_cpu_usage: self.system_cpu_usage,
throttling_data: self.throttling_data.clone(),
}
}
}
impl Clone for CpuUsage {
fn clone(&self) -> Self {
CpuUsage {
percpu_usage: self.percpu_usage.clone(),
usage_in_usermode: self.usage_in_usermode,
total_usage: self.total_usage,
usage_in_kernelmode: self.usage_in_kernelmode,
}
}
}
impl Clone for ThrottlingData {
fn clone(&self) -> Self {
ThrottlingData {
periods: self.periods,
throttled_periods: self.throttled_periods,
throttled_time: self.throttled_time,
}
}
}
impl Clone for BlkioStats {
fn clone(&self) -> Self {
BlkioStats {
io_service_bytes_recursive: self.io_service_bytes_recursive.clone(),
io_serviced_recursive: self.io_serviced_recursive.clone(),
io_queue_recursive: self.io_queue_recursive.clone(),
io_service_time_recursive: self.io_service_time_recursive.clone(),
io_wait_time_recursive: self.io_wait_time_recursive.clone(),
io_merged_recursive: self.io_merged_recursive.clone(),
io_time_recursive: self.io_time_recursive.clone(),
sectors_recursive: self.sectors_recursive.clone(),
}
}
}
impl Clone for BlkioStat {
fn clone(&self) -> Self {
BlkioStat {
major: self.major,
minor: self.minor,
op: self.op.clone(),
value: self.value,
}
}
}
|
use crate::command_prelude::*;
use cargo::ops;
pub fn cli() -> App {
subcommand("login")
.about(
"Save an api token from the registry locally. \
If token is not specified, it will be read from stdin.",
)
.arg(opt("quiet", "No output printed to stdout").short("q"))
.arg(Arg::with_name("token"))
// --host is deprecated (use --registry instead)
.arg(
opt("host", "Host to set the token for")
.value_name("HOST")
.hidden(true),
)
.arg(opt("registry", "Registry to use").value_name("REGISTRY"))
.after_help("Run `cargo help login` for more detailed information.\n")
}
pub fn exec(config: &mut Config, args: &ArgMatches<'_>) -> CliResult {
ops::registry_login(
config,
args.value_of("token").map(String::from),
args.value_of("registry").map(String::from),
)?;
Ok(())
}
|
use crate::error::Error;
use async_trait::async_trait;
use futures::TryStreamExt;
const NAME_PREFIX: &str = "emu.";
#[derive(Debug, Clone)]
pub struct Network {
name: String,
index: u32,
}
#[derive(Debug, Clone)]
pub struct Interface {
name: String,
peer_name: String,
index: u32,
id: u32,
}
#[async_trait]
pub trait NetworkManager {
async fn create_network(&self, name: &str) -> Result<Network, Error>;
async fn delete_network(&self, network: &Network) -> Result<(), Error>;
async fn exists_network(&self, network: &Network) -> Result<bool, Error>;
async fn create_interface(&self, network: &Network, id: u32) -> Result<Interface, Error>;
async fn delete_interface(&self, interface: &Interface) -> Result<(), Error>;
async fn exists_interface(&self, interface: &Interface) -> Result<bool, Error>;
async fn bind(&self, network: &Network, interface: &Interface) -> Result<(), Error>;
async fn unbind(&self, interface: &Interface) -> Result<(), Error>;
}
pub struct BridgeManager {}
#[async_trait]
impl NetworkManager for BridgeManager {
async fn create_network(&self, name: &str) -> Result<Network, Error> {
match rtnetlink::new_connection() {
Ok(connection) => {
let (c, handle, r) = connection;
tokio::spawn(c);
let bridge_name = String::from(NAME_PREFIX) + name;
let resp = handle
.link()
.add()
.bridge(bridge_name.clone())
.execute()
.await;
match resp {
Ok(_) => {
let resp = handle
.link()
.get()
.set_name_filter(bridge_name.clone())
.execute()
.try_next()
.await;
drop(r);
match resp {
Ok(Some(resp)) => Ok(Network {
name: bridge_name.clone(),
index: resp.header.index,
}),
Err(e) => Err(Error::from(e)),
Ok(None) => {
Err(Error::new("could not retrieve network after creating it"))
}
}
}
Err(e) => {
drop(r);
Err(Error::from(e))
}
}
}
Err(e) => Err(Error::from(e)),
}
}
async fn delete_network(&self, network: &Network) -> Result<(), Error> {
match rtnetlink::new_connection() {
Ok(connection) => {
let (c, handle, r) = connection;
tokio::spawn(c);
let resp = handle.link().del(network.index).execute().await;
drop(r);
match resp {
Ok(_) => Ok(()),
Err(e) => Err(Error::from(e)),
}
}
Err(e) => Err(Error::from(e)),
}
}
async fn exists_network(&self, network: &Network) -> Result<bool, Error> {
match rtnetlink::new_connection() {
Ok(connection) => {
let (c, handle, r) = connection;
tokio::spawn(c);
let resp = handle
.link()
.get()
.match_index(network.index)
.set_name_filter(network.name.clone())
.execute()
.try_next()
.await;
drop(r);
match resp {
Ok(_) => Ok(true),
Err(e) => match e.clone() {
rtnetlink::Error::NetlinkError(ne) => match ne.code {
-19 => Ok(false), // no such device
_ => Err(Error::from(e)),
},
_ => Err(Error::from(e)),
},
}
}
Err(e) => Err(Error::from(e)),
}
}
async fn create_interface(&self, network: &Network, id: u32) -> Result<Interface, Error> {
match rtnetlink::new_connection() {
Ok(connection) => {
let (c, handle, r) = connection;
tokio::spawn(c);
let if_name = network.name.clone() + &format!("-{}", id);
let peer_name = network.name.clone() + &format!("-{}-peer", id);
let resp = handle
.link()
.add()
.veth(if_name.clone(), peer_name.clone())
.execute()
.await;
match resp {
Ok(_) => {
let resp = handle
.link()
.get()
.set_name_filter(if_name.clone())
.execute()
.try_next()
.await;
drop(r);
match resp {
Ok(Some(resp)) => Ok(Interface {
name: if_name,
peer_name: peer_name.clone(),
index: resp.header.index,
id,
}),
Err(e) => Err(Error::from(e)),
Ok(None) => {
Err(Error::new("could not retrieve interface after creating it"))
}
}
}
Err(e) => {
drop(r);
Err(Error::from(e))
}
}
}
Err(e) => Err(Error::from(e)),
}
}
async fn delete_interface(&self, interface: &Interface) -> Result<(), Error> {
match rtnetlink::new_connection() {
Ok(connection) => {
let (c, handle, r) = connection;
tokio::spawn(c);
let resp = handle.link().del(interface.index).execute().await;
drop(r);
match resp {
Ok(_) => Ok(()),
Err(e) => Err(Error::from(e)),
}
}
Err(e) => Err(Error::from(e)),
}
}
async fn exists_interface(&self, interface: &Interface) -> Result<bool, Error> {
match rtnetlink::new_connection() {
Ok(connection) => {
let (c, handle, r) = connection;
tokio::spawn(c);
let resp = handle
.link()
.get()
.set_name_filter(interface.name.clone())
.match_index(interface.index)
.execute()
.try_next()
.await;
drop(r);
match resp {
Ok(_) => Ok(true),
Err(e) => match e.clone() {
rtnetlink::Error::NetlinkError(ne) => match ne.code {
-19 => Ok(false), // no such device
_ => Err(Error::from(e)),
},
_ => Err(Error::from(e)),
},
}
}
Err(e) => Err(Error::from(e)),
}
}
async fn bind(&self, network: &Network, interface: &Interface) -> Result<(), Error> {
match rtnetlink::new_connection() {
Ok(connection) => {
let (c, handle, r) = connection;
tokio::spawn(c);
let resp = handle
.link()
.set(interface.index)
.master(network.index)
.execute()
.await;
drop(r);
match resp {
Ok(_) => Ok(()),
Err(e) => Err(Error::from(e)),
}
}
Err(e) => Err(Error::from(e)),
}
}
async fn unbind(&self, interface: &Interface) -> Result<(), Error> {
match rtnetlink::new_connection() {
Ok(connection) => {
let (c, handle, r) = connection;
tokio::spawn(c);
let resp = handle.link().set(interface.index).master(0).execute().await;
drop(r);
match resp {
Ok(_) => Ok(()),
Err(e) => Err(Error::from(e)),
}
}
Err(e) => Err(Error::from(e)),
}
}
}
|
/**
* Authors: Jorge Martins && Diogo Lopes
* This example is from Vasconcelos, V.T. (and several others):
* "Behavioral Types in Programming Languages" (figures 2.4, 2.5 and 2.6)
*/
//Messages to be traded
use crate::customer;
use chrono::prelude::*;
use std::fmt::{self, Display, Formatter};
pub enum Decision {
ACCEPT,
REJECT,
}
//simple function to print the Decision type
impl Display for Decision {
// `f` is a buffer, and this method must write the formatted string into it
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Decision::ACCEPT => write!(f, "ACCEPT"),
Decision::REJECT => write!(f, "REJECT"),
}
}
}
pub enum Message {
JourneyPreference(String),
JourneyDate(Date<Utc>),
JourneyPrice(f64),
CustomerAddress(customer::Address),
CustomerDecision(Decision),
}
|
#![no_main]
#![no_std]
extern crate cortex_m_rt;
extern crate panic_halt;
use cortex_m_rt::entry;
#[entry]
fn foo() {}
//~^ ERROR `#[entry]` function must have signature `[unsafe] fn() -> !`
|
#![cfg(feature = "use-hyper")]
use crate::error::Error;
use crate::client::Client;
use hyper::rt::{Future, Stream};
use hyper_tls::HttpsConnector;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug)]
pub struct HyperClient {
node: String,
}
impl HyperClient {
pub fn new(node: &str) -> Self {
Self {
node: node.to_owned(),
}
}
}
impl Client for HyperClient {
fn node(&self) -> &str {
&self.node
}
fn fetch<T>(&self, path: impl AsRef<str>, params: impl Serialize) -> crate::Result<T>
where T: 'static + for<'b> Deserialize<'b> + Send + Sync
{
let https = HttpsConnector::new(4).map_err(|tls_err| Error::HyperTlsError{tls_err})?;
let client = hyper::Client::builder().build::<_, hyper::Body>(https);
let url = self.node.to_string() + path.as_ref();
let url: hyper::Uri = url.parse().map_err(|invalid_uri| Error::InvalidUri {invalid_uri})?;
let json = serde_json::to_string(¶ms)?;
let mut req = hyper::Request::new(hyper::Body::from(json));
*req.method_mut() = hyper::Method::POST;
*req.uri_mut() = url;
req.headers_mut().insert(
hyper::header::CONTENT_TYPE,
hyper::header::HeaderValue::from_static("application/json"),
);
req.headers_mut().insert(
hyper::header::ACCEPT,
hyper::header::HeaderValue::from_static("application/json"),
);
let fut = client
.request(req)
.and_then(|res| res.into_body().concat2())
.from_err::<Error>();
// get returned body
let resp_body = tokio::runtime::Runtime::new()
.map_err(|tokio_err| Error::TokioError {tokio_err})?
.block_on(fut)?;
let body_bytes = resp_body.into_bytes();
//try to parse error information if request is illegal
let block_err = serde_json::from_slice(&body_bytes);
if block_err.is_ok() {
// return eos request error information
return Err(Error::EosError{ eos_err: block_err.unwrap() })?;
}
// returned the correct request http body and parse it.
let block: T = serde_json::from_slice(&body_bytes)?;
Ok(block)
}
}
|
//! Various state of the authenticator.
//!
//! Needs cleanup.
use ctap_types::{
cose::EcdhEsHkdf256PublicKey as CoseEcdhEsHkdf256PublicKey,
// 2022-02-27: 10 credentials
sizes::MAX_CREDENTIAL_COUNT_IN_LIST, // U8 currently
Bytes,
Error,
String,
};
use trussed::{
client, syscall, try_syscall,
types::{self, KeyId, Location, Mechanism, PathBuf},
Client as TrussedClient,
};
use heapless::binary_heap::{BinaryHeap, Max};
use crate::{cbor_serialize_message, credential::Credential, Result};
#[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct CachedCredential {
pub timestamp: u32,
// PathBuf has length 255 + 1, we only need 36 + 1
// with `rk/<16B rp_id>/<16B cred_id>` = 4 + 2*32
pub path: String<37>,
}
impl PartialOrd for CachedCredential {
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for CachedCredential {
fn cmp(&self, other: &Self) -> core::cmp::Ordering {
self.timestamp.cmp(&other.timestamp)
}
}
#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct CredentialCacheGeneric<const N: usize>(BinaryHeap<CachedCredential, Max, N>);
impl<const N: usize> CredentialCacheGeneric<N> {
pub fn push(&mut self, item: CachedCredential) {
if self.0.len() == self.0.capacity() {
self.0.pop();
}
// self.0.push(item).ok();
self.0.push(item).map_err(drop).unwrap();
}
pub fn pop(&mut self) -> Option<CachedCredential> {
self.0.pop()
}
pub fn len(&self) -> u32 {
self.0.len() as u32
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn clear(&mut self) {
self.0.clear()
}
}
pub type CredentialCache = CredentialCacheGeneric<MAX_CREDENTIAL_COUNT_IN_LIST>;
#[derive(Clone, Debug, /*uDebug, Eq, PartialEq,*/ serde::Deserialize, serde::Serialize)]
pub struct State {
/// Batch device identity (aaguid, certificate, key).
pub identity: Identity,
pub persistent: PersistentState,
pub runtime: RuntimeState,
}
impl Default for State {
fn default() -> Self {
Self::new()
}
}
impl State {
// pub fn new(trussed: &mut TrussedClient) -> Self {
pub fn new() -> Self {
// let identity = Identity::get(trussed);
let identity = Default::default();
let runtime: RuntimeState = Default::default();
// let persistent = PersistentState::load_or_reset(trussed);
let persistent = Default::default();
Self {
identity,
persistent,
runtime,
}
}
pub fn decrement_retries<T: TrussedClient>(&mut self, trussed: &mut T) -> Result<()> {
self.persistent.decrement_retries(trussed)?;
self.runtime.decrement_retries();
Ok(())
}
pub fn reset_retries<T: TrussedClient>(&mut self, trussed: &mut T) -> Result<()> {
self.persistent.reset_retries(trussed)?;
self.runtime.reset_retries();
Ok(())
}
pub fn pin_blocked(&self) -> Result<()> {
if self.persistent.pin_blocked() {
return Err(Error::PinBlocked);
}
if self.runtime.pin_blocked() {
return Err(Error::PinAuthBlocked);
}
Ok(())
}
}
/// Batch device identity (aaguid, certificate, key).
#[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct Identity {
// can this be [u8; 16] or need Bytes for serialization?
// aaguid: Option<Bytes<consts::U16>>,
attestation_key: Option<KeyId>,
}
pub type Aaguid = [u8; 16];
pub type Certificate = trussed::types::Message;
impl Identity {
// Attempt to yank out the aaguid of a certificate.
fn yank_aaguid(&mut self, der: &[u8]) -> Option<[u8; 16]> {
let aaguid_start_sequence = [
// OBJECT IDENTIFIER 1.3.6.1.4.1.45724.1.1.4 (AAGUID)
0x06u8, 0x0B, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0xE5, 0x1C, 0x01, 0x01, 0x04,
// Sequence, 16 bytes
0x04, 0x12, 0x04, 0x10,
];
// Scan for the beginning sequence for AAGUID.
let mut cert_reader = der;
while !cert_reader.is_empty() {
if cert_reader.starts_with(&aaguid_start_sequence) {
info_now!("found aaguid");
break;
}
cert_reader = &cert_reader[1..];
}
if cert_reader.is_empty() {
return None;
}
cert_reader = &cert_reader[aaguid_start_sequence.len()..];
let mut aaguid = [0u8; 16];
aaguid[..16].clone_from_slice(&cert_reader[..16]);
Some(aaguid)
}
/// Lookup batch key and certificate, together with AAUGID.
pub fn attestation<T: TrussedClient>(
&mut self,
trussed: &mut T,
) -> (Option<(KeyId, Certificate)>, Aaguid) {
let key = crate::constants::ATTESTATION_KEY_ID;
let attestation_key_exists = syscall!(trussed.exists(Mechanism::P256, key)).exists;
if attestation_key_exists {
// Will panic if certificate does not exist.
let cert =
syscall!(trussed.read_certificate(crate::constants::ATTESTATION_CERT_ID)).der;
let mut aaguid = self.yank_aaguid(cert.as_slice());
if aaguid.is_none() {
// Provide a default
aaguid = Some(*b"AAGUID0123456789");
}
(Some((key, cert)), aaguid.unwrap())
} else {
info_now!("attestation key does not exist");
(None, *b"AAGUID0123456789")
}
}
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct CredentialManagementEnumerateRps {
pub remaining: u32,
pub rp_id_hash: Bytes<32>,
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct CredentialManagementEnumerateCredentials {
pub remaining: u32,
pub rp_dir: PathBuf,
pub prev_filename: PathBuf,
}
#[derive(
Clone, Debug, /*uDebug,*/ Default, /*PartialEq,*/ serde::Deserialize, serde::Serialize,
)]
pub struct ActiveGetAssertionData {
pub rp_id_hash: [u8; 32],
pub client_data_hash: [u8; 32],
pub uv_performed: bool,
pub up_performed: bool,
pub multiple_credentials: bool,
pub extensions: Option<ctap_types::ctap2::get_assertion::ExtensionsInput>,
}
#[derive(
Clone, Debug, /*uDebug,*/ Default, /*PartialEq,*/ serde::Deserialize, serde::Serialize,
)]
pub struct RuntimeState {
key_agreement_key: Option<KeyId>,
pin_token: Option<KeyId>,
// TODO: why is this field not used?
shared_secret: Option<KeyId>,
consecutive_pin_mismatches: u8,
// both of these are a cache for previous Get{Next,}Assertion call
cached_credentials: CredentialCache,
pub active_get_assertion: Option<ActiveGetAssertionData>,
channel: Option<u32>,
pub cached_rp: Option<CredentialManagementEnumerateRps>,
pub cached_rk: Option<CredentialManagementEnumerateCredentials>,
}
// TODO: Plan towards future extensibility
//
// - if we set all fields as optional, and annotate with `skip_serializing if None`,
// then, missing fields in older fw versions should not cause problems with newer fw
// versions that potentially add new fields.
//
// - empirically, the implementation of Deserialize doesn't seem to mind moving around
// the order of fields, which is already nice
//
// - adding new non-optional fields definitely doesn't parse (but maybe it could?)
// - same for removing a field
// Currently, this causes the entire authnr to reset state. Maybe it should even reformat disk
//
// - An alternative would be `heapless::Map`, but I'd prefer something more typed.
#[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct PersistentState {
#[serde(skip)]
// TODO: there has to be a better way than.. this
// Pro-tip: it should involve types ^^
//
// We could alternatively make all methods take a TrussedClient as parameter
initialised: bool,
key_encryption_key: Option<KeyId>,
key_wrapping_key: Option<KeyId>,
consecutive_pin_mismatches: u8,
pin_hash: Option<[u8; 16]>,
// Ideally, we'd dogfood a "Monotonic Counter" from trussed.
// TODO: Add per-key counters for resident keys.
// counter: Option<CounterId>,
timestamp: u32,
}
impl PersistentState {
const RESET_RETRIES: u8 = 8;
const FILENAME: &'static [u8] = b"persistent-state.cbor";
pub fn load<T: client::Client + client::Chacha8Poly1305>(trussed: &mut T) -> Result<Self> {
// TODO: add "exists_file" method instead?
let result =
try_syscall!(trussed.read_file(Location::Internal, PathBuf::from(Self::FILENAME),))
.map_err(|_| Error::Other);
if result.is_err() {
info!("err loading: {:?}", result.err().unwrap());
return Err(Error::Other);
}
let data = result.unwrap().data;
let result = trussed::cbor_deserialize(&data);
if result.is_err() {
info!("err deser'ing: {:?}", result.err().unwrap());
info!("{}", hex_str!(&data));
return Err(Error::Other);
}
result.map_err(|_| Error::Other)
}
pub fn save<T: TrussedClient>(&self, trussed: &mut T) -> Result<()> {
let data = crate::cbor_serialize_message(self).unwrap();
syscall!(trussed.write_file(
Location::Internal,
PathBuf::from(Self::FILENAME),
data,
None,
));
Ok(())
}
pub fn reset<T: TrussedClient>(&mut self, trussed: &mut T) -> Result<()> {
if let Some(key) = self.key_encryption_key {
syscall!(trussed.delete(key));
}
if let Some(key) = self.key_wrapping_key {
syscall!(trussed.delete(key));
}
self.key_encryption_key = None;
self.key_wrapping_key = None;
self.consecutive_pin_mismatches = 0;
self.pin_hash = None;
self.timestamp = 0;
self.save(trussed)
}
pub fn load_if_not_initialised<T: client::Client + client::Chacha8Poly1305>(
&mut self,
trussed: &mut T,
) {
if !self.initialised {
match Self::load(trussed) {
Ok(previous_self) => {
info!("loaded previous state!");
*self = previous_self
}
Err(_err) => {
info!("error with previous state! {:?}", _err);
}
}
self.initialised = true;
}
}
pub fn timestamp<T: TrussedClient>(&mut self, trussed: &mut T) -> Result<u32> {
let now = self.timestamp;
self.timestamp += 1;
self.save(trussed)?;
Ok(now)
}
pub fn key_encryption_key<T: client::Client + client::Chacha8Poly1305>(
&mut self,
trussed: &mut T,
) -> Result<KeyId> {
match self.key_encryption_key {
Some(key) => Ok(key),
None => self.rotate_key_encryption_key(trussed),
}
}
pub fn rotate_key_encryption_key<T: client::Client + client::Chacha8Poly1305>(
&mut self,
trussed: &mut T,
) -> Result<KeyId> {
if let Some(key) = self.key_encryption_key {
syscall!(trussed.delete(key));
}
let key = syscall!(trussed.generate_chacha8poly1305_key(Location::Internal)).key;
self.key_encryption_key = Some(key);
self.save(trussed)?;
Ok(key)
}
pub fn key_wrapping_key<T: client::Client + client::Chacha8Poly1305>(
&mut self,
trussed: &mut T,
) -> Result<KeyId> {
match self.key_wrapping_key {
Some(key) => Ok(key),
None => self.rotate_key_wrapping_key(trussed),
}
}
pub fn rotate_key_wrapping_key<T: client::Client + client::Chacha8Poly1305>(
&mut self,
trussed: &mut T,
) -> Result<KeyId> {
self.load_if_not_initialised(trussed);
if let Some(key) = self.key_wrapping_key {
syscall!(trussed.delete(key));
}
let key = syscall!(trussed.generate_chacha8poly1305_key(Location::Internal)).key;
self.key_wrapping_key = Some(key);
self.save(trussed)?;
Ok(key)
}
pub fn pin_is_set(&self) -> bool {
self.pin_hash.is_some()
}
pub fn retries(&self) -> u8 {
Self::RESET_RETRIES - self.consecutive_pin_mismatches
}
pub fn pin_blocked(&self) -> bool {
self.consecutive_pin_mismatches >= Self::RESET_RETRIES
}
fn reset_retries<T: TrussedClient>(&mut self, trussed: &mut T) -> Result<()> {
if self.consecutive_pin_mismatches > 0 {
self.consecutive_pin_mismatches = 0;
self.save(trussed)?;
}
Ok(())
}
fn decrement_retries<T: TrussedClient>(&mut self, trussed: &mut T) -> Result<()> {
// error to call before initialization
if self.consecutive_pin_mismatches < Self::RESET_RETRIES {
self.consecutive_pin_mismatches += 1;
self.save(trussed)?;
if self.consecutive_pin_mismatches == 0 {
return Err(Error::PinBlocked);
}
}
Ok(())
}
pub fn pin_hash(&self) -> Option<[u8; 16]> {
self.pin_hash
}
pub fn set_pin_hash<T: TrussedClient>(
&mut self,
trussed: &mut T,
pin_hash: [u8; 16],
) -> Result<()> {
self.pin_hash = Some(pin_hash);
self.save(trussed)?;
Ok(())
}
}
impl RuntimeState {
const POWERCYCLE_RETRIES: u8 = 3;
fn decrement_retries(&mut self) {
if self.consecutive_pin_mismatches < Self::POWERCYCLE_RETRIES {
self.consecutive_pin_mismatches += 1;
}
}
fn reset_retries(&mut self) {
self.consecutive_pin_mismatches = 0;
}
pub fn pin_blocked(&self) -> bool {
self.consecutive_pin_mismatches >= Self::POWERCYCLE_RETRIES
}
// pub fn cached_credentials(&mut self) -> &mut CredentialCache {
// &mut self.cached_credentials
// // if let Some(cache) = self.cached_credentials.as_mut() {
// // return cache
// // }
// // self.cached_credentials.insert(CredentialCache::new())
// }
pub fn clear_credential_cache(&mut self) {
self.cached_credentials.clear()
}
pub fn push_credential(&mut self, credential: CachedCredential) {
self.cached_credentials.push(credential);
}
pub fn pop_credential<T: client::FilesystemClient>(
&mut self,
trussed: &mut T,
) -> Option<Credential> {
let cached_credential = self.cached_credentials.pop()?;
let credential_data = syscall!(trussed.read_file(
Location::Internal,
PathBuf::from(cached_credential.path.as_str()),
))
.data;
Credential::deserialize(&credential_data).ok()
}
pub fn remaining_credentials(&self) -> u32 {
self.cached_credentials.len() as _
}
pub fn key_agreement_key<T: client::P256>(&mut self, trussed: &mut T) -> KeyId {
match self.key_agreement_key {
Some(key) => key,
None => self.rotate_key_agreement_key(trussed),
}
}
pub fn rotate_key_agreement_key<T: client::P256>(&mut self, trussed: &mut T) -> KeyId {
// TODO: need to rotate pin token?
if let Some(key) = self.key_agreement_key {
syscall!(trussed.delete(key));
}
if let Some(previous_shared_secret) = self.shared_secret {
syscall!(trussed.delete(previous_shared_secret));
}
let key = syscall!(trussed.generate_p256_private_key(Location::Volatile)).key;
self.key_agreement_key = Some(key);
self.shared_secret = None;
key
}
pub fn pin_token(&mut self, trussed: &mut impl client::HmacSha256) -> KeyId {
match self.pin_token {
Some(token) => token,
None => self.rotate_pin_token(trussed),
}
}
pub fn rotate_pin_token<T: client::HmacSha256>(&mut self, trussed: &mut T) -> KeyId {
// TODO: need to rotate key agreement key?
if let Some(token) = self.pin_token {
syscall!(trussed.delete(token));
}
let token = syscall!(trussed.generate_secret_key(16, Location::Volatile)).key;
self.pin_token = Some(token);
token
}
pub fn reset<T: client::HmacSha256 + client::P256 + client::FilesystemClient>(
&mut self,
trussed: &mut T,
) {
// Could use `free_credential_heap`, but since we're deleting everything here, this is quicker.
syscall!(trussed.delete_all(Location::Volatile));
self.clear_credential_cache();
self.active_get_assertion = None;
self.rotate_pin_token(trussed);
self.rotate_key_agreement_key(trussed);
}
pub fn generate_shared_secret<T: client::P256>(
&mut self,
trussed: &mut T,
platform_key_agreement_key: &CoseEcdhEsHkdf256PublicKey,
) -> Result<KeyId> {
let private_key = self.key_agreement_key(trussed);
let serialized_pkak = cbor_serialize_message(platform_key_agreement_key)
.map_err(|_| Error::InvalidParameter)?;
let platform_kak = try_syscall!(trussed.deserialize_p256_key(
&serialized_pkak,
types::KeySerialization::EcdhEsHkdf256,
types::StorageAttributes::new().set_persistence(types::Location::Volatile)
))
.map_err(|_| Error::InvalidParameter)?
.key;
let pre_shared_secret = syscall!(trussed.agree(
types::Mechanism::P256,
private_key,
platform_kak,
types::StorageAttributes::new().set_persistence(types::Location::Volatile),
))
.shared_secret;
syscall!(trussed.delete(platform_kak));
if let Some(previous_shared_secret) = self.shared_secret {
syscall!(trussed.delete(previous_shared_secret));
}
let shared_secret = syscall!(trussed.derive_key(
types::Mechanism::Sha256,
pre_shared_secret,
None,
types::StorageAttributes::new().set_persistence(types::Location::Volatile)
))
.key;
self.shared_secret = Some(shared_secret);
syscall!(trussed.delete(pre_shared_secret));
Ok(shared_secret)
}
}
|
// q0028_implement_strstr
struct Solution;
impl Solution {
pub fn str_str(haystack: String, needle: String) -> i32 {
match haystack.find(needle.as_str()) {
Some(n) => n as i32,
None => -1,
}
}
}
#[cfg(test)]
mod tests {
use super::Solution;
#[test]
fn it_works() {
assert_eq!(2, Solution::str_str("hello".to_string(), "ll".to_string()));
assert_eq!(
-1,
Solution::str_str("aaaaa".to_string(), "bba".to_string())
);
}
}
|
#![allow(non_snake_case)]
//! Mailbox Module
use core::ffi::c_void;
use std::ffi::CString;
use std::io::{Error, ErrorKind};
use std::mem::size_of;
// use std::fs::OpenOptions;
// use std::{io, ptr};
use libc;
pub mod ioctl;
/* from https://github.com/raspberrypi/firmware/wiki/Mailbox-property-interface */
pub const MEM_FLAG_DISCARDABLE: usize = 1 << 0; /* can be resized to 0 at any time. Use for cached data */
pub const MEM_FLAG_NORMAL: usize = 0 << 2; /* normal allocating alias. Don't use from ARM */
pub const MEM_FLAG_DIRECT: usize = 1 << 2; /* 0xC alias uncached */
pub const MEM_FLAG_COHERENT: usize = 2 << 2; /* 0x8 alias. Non-allocating in L2 but coherent */
pub const MEM_FLAG_L1_NONALLOCATING: usize = MEM_FLAG_DIRECT | MEM_FLAG_COHERENT; /* Allocating in L2 */
pub const MEM_FLAG_ZERO: usize = 1 << 4; /* initialise buffer to all zeros */
pub const MEM_FLAG_NO_INIT: usize = 1 << 5; /* don't initialise (default is initialise to all ones */
pub const MEM_FLAG_HINT_PERMALOCK: usize = 1 << 6; /* Likely to be locked for long periods of time. */
// pointer size is 4 bytes for 32-bit machine a.k.a. rpi
const PTR_SIZE: usize = 4;
pub const MAJOR_NUM: usize = 100;
const PAGE_SIZE: usize = PTR_SIZE*1024;
pub fn mapmem(base: usize, size: usize) -> Result<usize, Error> {
let offset = base % PAGE_SIZE;
let base = base - offset;
// open /dev/mem
let dev_mem = CString::new("/dev/mem").unwrap().into_bytes_with_nul();
let mem_fd = match unsafe { libc::open(dev_mem.as_ptr(), libc::O_RDWR|libc::O_SYNC) }{
fd if fd < 0 => {
error!("can't open /dev/mem\nThis program should be run as root. Try prefixing command with: sudo");
return Err(Error::new(ErrorKind::PermissionDenied, "can't open /dev/mem\nThis program should be run as root. Try prefixing command with: sudo"))
},
fd => fd
};
#[cfg(target_arch = "aarch64")]
let mem = unsafe {
libc::mmap(
0 as *mut c_void,
size,
libc::PROT_READ | libc::PROT_WRITE,
libc::MAP_SHARED,
mem_fd,
base as i64
) as usize
};
#[cfg(target_arch = "arm")]
let mem = unsafe {
libc::mmap(
0 as *mut c_void,
size,
libc::PROT_READ | libc::PROT_WRITE,
libc::MAP_SHARED,
mem_fd,
base as i32
) as usize
};
#[cfg(feature = "debug")]
{
trace!("base={:#010x}, mem={:#010x}", base, mem);
}
if mem == libc::MAP_FAILED as usize {
error!("map error {:?}\n", mem);
return Err(Error::new(ErrorKind::Other, format!("map error {:?}\n", mem)))
}
unsafe {
libc::close(mem_fd);
};
Ok(mem + offset)
}
pub fn unmapmem(addr: *mut c_void, size: usize) -> Result<(), Error> {
match unsafe{ libc::munmap(addr, size) } {
0 => Ok(()),
s => {
error!("munmap error: {:?}\n", s);
Err(Error::new(ErrorKind::Other, format!("munmap error: {:?}\n", s)))
},
}
}
pub fn mbox_property(file_desc: i32, buf: &mut [usize; 32], _len: usize) -> Result<usize, Error> {
#[cfg(feature = "debug")]
{
trace!("Mbox request:");
for i in 0.._len {
trace!("{:#04x}: {:#010x}", i*size_of::<u8>(), buf[i]);
}
trace!("\n");
}
// the third parameter is the size of a pointer
// in c code, this is passed in as "char *"
// so sizeof(char *) is 4 for a 32-bit machine a.k.a. rpi
let IOCTL_MBOX_PROPERTY: usize = ioctl::_IOWR(MAJOR_NUM, 0, PTR_SIZE);
#[cfg(target_arch = "aarch64")]
let ret_val = match unsafe{ libc::ioctl(file_desc, IOCTL_MBOX_PROPERTY as u64, buf.as_mut_ptr() as *mut c_void) }{
x if x < 0 => {
error!("ioctl_set_msg failed: {:?}", x);
return Err(Error::new(ErrorKind::Other, format!("ioctl_set_msg failed: {:?}", x)))
},
x => x as usize
};
#[cfg(target_arch = "arm")]
let ret_val = match unsafe{ libc::ioctl(file_desc, IOCTL_MBOX_PROPERTY as u32, buf.as_mut_ptr() as *mut c_void) }{
x if x < 0 => {
error!("ioctl_set_msg failed: {:?}", x);
return Err(Error::new(ErrorKind::Other, format!("ioctl_set_msg failed: {:?}", x)))
},
x => x as usize
};
#[cfg(feature = "debug")]
{
trace!("Mbox responses:");
for i in 0.._len {
trace!("{:#04x}: {:#010x}", i*size_of::<u8>(), buf[i]);
}
trace!("\n");
}
Ok(ret_val)
}
pub fn mem_alloc(file_desc: i32, size: usize, align: usize, flags: usize) -> Result<usize, Error> {
let mut p: [usize;32] = [0; 32];
#[cfg(feature = "debug")]
{
trace!("mem_alloc");
trace!("Requesting {} bytes", size);
trace!("Alignment {} bytes", align);
trace!("mem_alloc flags: {:#010x} \n", flags);
}
p[1] = 0x00000000; // process request
p[2] = 0x3000c; // (the tag id)
p[3] = 12; // (size of the buffer)
p[4] = 12; // (size of the data)
p[5] = size; // (num bytes? or pages?)
p[6] = align; // (alignment)
p[7] = flags; // (MEM_FLAG_L!_NOMALLOCATING)
p[8] = 0x00000000; // end tag
p[0] = 9*size_of::<usize>();
match mbox_property(file_desc, &mut p, 9){
Ok(_) => Ok(p[5]),
Err(e) => Err(e),
}
}
pub fn mem_free(file_desc: i32, handle: usize) -> Result<usize, Error> {
#[cfg(feature = "debug")]
{
trace!("mem_free");
}
let mut p: [usize;32] = [0; 32];
p[1] = 0x00000000; // process request
p[2] = 0x3000f; // (the tag id)
p[3] = 4; // (size of the buffer)
p[4] = 4; // (size of the data)
p[5] = handle;
p[6] = 0x00000000; // end tag
p[0] = 7*size_of::<usize>();
match mbox_property(file_desc, &mut p, 7){
Ok(_) => Ok(p[5]),
Err(e) => Err(e),
}
}
pub fn mem_lock(file_desc: i32, handle: usize) -> Result<usize, Error> {
#[cfg(feature = "debug")]
{
trace!("mem_lock");
}
let mut p: [usize;32] = [0; 32];
p[1] = 0x00000000; // process request
p[2] = 0x3000d; // (the tag id)
p[3] = 4; // (size of the buffer)
p[4] = 4; // (size of the data)
p[5] = handle;
p[6] = 0x00000000; // end tag
p[0] = 7*size_of::<usize>();
match mbox_property(file_desc, &mut p, 7){
Ok(_) => Ok(p[5]),
Err(e) => Err(e),
}
}
pub fn mem_unlock(file_desc: i32, handle: usize) -> Result<usize, Error> {
#[cfg(feature = "debug")]
{
trace!("mem_unlock");
}
let mut p: [usize;32] = [0; 32];
p[1] = 0x00000000; // process request
p[2] = 0x3000e; // (the tag id)
p[3] = 4; // (size of the buffer)
p[4] = 4; // (size of the data)
p[5] = handle;
p[6] = 0x00000000; // end tag
p[0] = 7*size_of::<usize>();
match mbox_property(file_desc, &mut p, 7){
Ok(_) => Ok(p[5]),
Err(e) => Err(e),
}
}
pub fn execute_code(file_desc: i32, code: usize, r0: usize, r1: usize, r2: usize, r3: usize, r4: usize, r5: usize) -> Result<usize, Error> {
#[cfg(feature = "debug")]
{
trace!("execute_code");
}
let mut p: [usize;32] = [0; 32];
p[1] = 0x00000000; // process request
p[2] = 0x30010; // (the tag id)
p[3] = 28; // (size of the buffer)
p[4] = 28; // (size of the data)
p[5] = code;
p[6] = r0;
p[7] = r1;
p[8] = r2;
p[9] = r3;
p[10] = r4;
p[11] = r5;
p[12] = 0x00000000; // end tag
p[0] = 13*size_of::<usize>();
match mbox_property(file_desc, &mut p, 13){
Ok(_) => Ok(p[5]),
Err(e) => Err(e),
}
}
pub fn qpu_enable(file_desc: i32, enable: usize) -> Result<usize, Error> {
#[cfg(feature = "debug")]
{
trace!("qpu_enable");
}
let mut p: [usize;32] = [0; 32];
p[1] = 0x00000000; // process request
p[2] = 0x30012; // (the tag id)
p[3] = 4; // (size of the buffer)
p[4] = 4; // (size of the data)
p[5] = enable;
p[6] = 0x00000000; // end tag
p[0] = 7*size_of::<usize>();
match mbox_property(file_desc, &mut p, 7){
Ok(_) => Ok(p[5]),
Err(e) => Err(e),
}
}
pub fn execute_qpu(file_desc: i32, num_qpus: usize, control: usize, noflush: usize, timeout: usize) -> Result<usize, Error> {
#[cfg(feature = "debug")]
{
trace!("execute_qpu");
}
let mut p: [usize;32] = [0; 32];
p[1] = 0x00000000; // process request
p[2] = 0x30011; // (the tag id)
p[3] = 16; // (size of the buffer)
p[4] = 16; // (size of the data)
p[5] = num_qpus;
p[6] = control;
p[7] = noflush;
p[8] = timeout; // ms
p[9] = 0x00000000; // end tag
p[0] = 10*size_of::<usize>();
match mbox_property(file_desc, &mut p, 10){
Ok(_) => Ok(p[5]),
Err(e) => Err(e),
}
}
pub fn get_firmware_revision(file_desc: i32) -> Result<usize, Error> {
#[cfg(feature = "debug")]
{
trace!("get_firmware_revision");
}
let mut p: [usize;32] = [0; 32];
p[1] = 0x00000000; // process request
p[2] = 0x10000; // (the tag id)
p[3] = 4; // (size of the buffer)
p[4] = 0; // (size of the data)
p[5] = 0;
p[6] = 0x00000000; // end tag
p[0] = 7*size_of::<usize>();
match mbox_property(file_desc, &mut p, 7){
Ok(_) => Ok(p[5]),
Err(e) => Err(e),
}
}
pub fn get_board_model(file_desc: i32) -> Result<usize, Error> {
#[cfg(feature = "debug")]
{
trace!("get_board_model");
}
let mut p: [usize;32] = [0; 32];
p[1] = 0x00000000; // process request
p[2] = 0x10001; // (the tag id)
p[3] = 4; // (size of the buffer)
p[4] = 0; // (size of the data)
p[5] = 0;
p[6] = 0x00000000; // end tag
p[0] = 7*size_of::<usize>();
match mbox_property(file_desc, &mut p, 7){
Ok(_) => Ok(p[5]),
Err(e) => Err(e),
}
}
pub fn get_board_revision(file_desc: i32) -> Result<usize, Error> {
#[cfg(feature = "debug")]
{
trace!("get_board_revision");
}
let mut p: [usize;32] = [0; 32];
p[1] = 0x00000000; // process request
p[2] = 0x10002; // (the tag id)
p[3] = 4; // (size of the buffer)
p[4] = 0; // (size of the data)
p[5] = 0;
p[6] = 0x00000000; // end tag
p[0] = 7*size_of::<usize>();
match mbox_property(file_desc, &mut p, 7){
Ok(_) => Ok(p[5]),
Err(e) => Err(e),
}
}
pub fn get_dma_channels(file_desc: i32) -> Result<usize, Error> {
#[cfg(feature = "debug")]
{
trace!("get_dma_channels");
}
let mut p: [usize;32] = [0; 32];
p[1] = 0x00000000; // process request
p[2] = 0x60001; // (the tag id)
p[3] = 4; // (size of the buffer)
p[4] = 0; // (size of the data)
p[5] = 0;
p[6] = 0x00000000; // end tag
p[0] = 7*size_of::<usize>();
match mbox_property(file_desc, &mut p, 7){
Ok(_) => Ok(p[5]),
Err(e) => Err(e),
}
}
|
pub mod error;
mod expressions;
mod ident;
mod items;
mod path;
mod patterns;
mod types;
use crate::{db::HirDatabase, ids::HirTables, lower::error::LoweringError};
use valis_source::File;
pub struct LoweringCtx<'a, DB> {
pub db: &'a DB,
pub source_file: File,
}
impl<'a, DB: HirDatabase> LoweringCtx<'a, DB> {
#[inline]
pub fn tables(&self) -> HirTables<DB> {
self.db.into()
}
}
pub trait Lower<A>: Sized {
fn lower<'a, DB: HirDatabase>(
syntax: A,
ctx: &mut LoweringCtx<'a, DB>,
) -> Result<Self, LoweringError>;
}
// NOTE(hir lowering handling errors):
//
// Some of the errors that are discovered while lowering the AST to the HIR are
// recoverable, in fact most errors fall into this category. However, we have to
// decide at what point the information that is recovered is too messed-up to
// use, and displaying/handling/routing errors in those cases is a waste of
// time. I arbitrarily decided that for expressions, types, and patterns the
// cost of maintaining a "Invalid" or "Malformed" variant was unnecessary.
// However, items occur infrequently enough that they would be a good candidate
// for retaining this partial or error information.
//
// However, how should items retain this information? Should they have lists of
// errors as part of their structure? Should they simply not acknowledge the
// existence of errored structures they contain? For example if the body of a
// function is missing components, the entire function body will fail to lower.
// Should the function data definition simply make the body optional?
//
// If we consider items as the boundary structures, are there any pieces of data
// that an item does require? For example, most (all for now) items have names.
// Should an item fail to parse if it doesn't have a name? These questions need
// to be answered with a concrete design that encompasses the varying use cases
// of the HIR (unfortunately there will be many such use cases as the HIR is the
// starting point for most analysis and execution).
//
// For now we will have the HIR be all-or-nothing with respect to lowering. This
// will require adjusting the tests, luckily (or perhaps not) we don't have many
// lowering failure tests to change.
|
use crate::queue::DrawQueue;
use crate::shared_res::SharedResources;
use glium::glutin::dpi::PhysicalPosition;
use glium::glutin::event_loop::EventLoop;
use glium::glutin::window::WindowId;
use rtk::event::Event;
use rtk::toplevel::{TopLevel, WindowAttributes};
use rtk_winit::{make_win_builder, BackendWindow};
use std::fmt;
pub struct GliumWindow<T> {
display: glium::Display,
cur_attr: WindowAttributes,
window: T,
}
impl<T: fmt::Debug> fmt::Debug for GliumWindow<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("GliumWindow")
.field("display", &format_args!("..."))
.field("cur_attr", &self.cur_attr)
.field("window", &self.window)
.finish()
}
}
impl<T: TopLevel> GliumWindow<T> {
pub fn new(window: T, event_loop: &EventLoop<()>, shared_res: &SharedResources) -> Self {
let win_attr = window.get_attr();
let win_builder = make_win_builder(win_attr);
let shared_win = shared_res.display.gl_window();
let ctx_builder = SharedResources::ctx_params()
.with_shared_lists(shared_win.context())
.with_double_buffer(Some(true));
let display = glium::Display::new(win_builder, ctx_builder, event_loop).unwrap();
drop(shared_win);
if let Some(pos) = win_attr.position {
display.gl_window().window().set_outer_position(PhysicalPosition::new(pos.x, pos.y));
}
Self {
cur_attr: win_attr.clone(),
window,
display,
}
}
}
impl<T: TopLevel> BackendWindow<SharedResources> for GliumWindow<T> {
fn get_id(&self) -> WindowId {
self.display.gl_window().window().id()
}
fn update(&mut self, resources: &mut SharedResources) {
if self.cur_attr.size.is_zero_area() {
let size: [u32; 2] = self.display.gl_window().window().inner_size().into();
self.cur_attr.set_size(size);
}
self.window.update_layout(resources);
//TODO: compare `self.cur_attr` with `self.window.get_window_attributes()` to make changes to real window
}
fn draw(&mut self, resources: &mut SharedResources) {
let mut draw_queue = DrawQueue::new(resources);
self.window.draw(&mut draw_queue);
draw_queue.render(&self.display, self.window.get_attr().background);
}
fn request_redraw(&self) {
self.display.gl_window().window().request_redraw();
}
fn push_event(&mut self, event: Event) -> bool {
match event {
Event::Resized(size) => {
self.cur_attr.set_size(size);
self.window.get_attr_mut().set_size(size);
}
Event::Moved(pos) => {
self.cur_attr.set_position(pos);
self.window.get_attr_mut().set_position(pos);
}
_ => (),
}
self.window.push_event(event)
}
}
|
use crate::grid::{Cell, Grid};
use terminal::util::Point;
pub fn fill(grid: &mut Grid, point: Point, first_cell: Cell, fill_cell: Cell) {
let cell = grid.get_mut_cell(point);
// We want to fill multiple measured cells as one, regardless of the index
let measured_cell =
matches!(*cell, Cell::Measured(_)) && matches!(first_cell, Cell::Measured(_));
if *cell == first_cell || measured_cell {
*cell = fill_cell;
} else {
return;
}
if point.y != 0 {
fill(
grid,
Point {
y: point.y - 1,
..point
},
first_cell,
fill_cell,
);
}
if point.y < grid.size.height - 1 {
fill(
grid,
Point {
y: point.y + 1,
..point
},
first_cell,
fill_cell,
);
}
if point.x != 0 {
fill(
grid,
Point {
x: point.x - 1,
..point
},
first_cell,
fill_cell,
);
}
if point.x < grid.size.width - 1 {
fill(
grid,
Point {
x: point.x + 1,
..point
},
first_cell,
fill_cell,
);
}
}
|
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
pub struct JrpcMessage {
pub jsonrpc: String,
pub method: String,
#[serde(default)]
pub id: Option<usize>,
pub params: serde_json::Value,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct JrpcResponse {
pub jsonrpc: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub id: Option<usize>,
#[serde(flatten, with = "InternalUsageJrpcResult")]
pub payload: Result<serde_json::Value, JrpcError>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(remote = "Result::<serde_json::Value, JrpcError>")]
enum InternalUsageJrpcResult {
#[serde(rename = "result")]
Ok(serde_json::Value),
#[serde(rename = "error")]
Err(JrpcError),
}
#[derive(Debug, Serialize, Deserialize)]
pub struct JrpcError {
pub code: i32,
pub message: String,
pub data: Option<serde_json::Value>,
}
|
use core::marker::PhantomData;
use crate::pac;
use crate::pac::common::{Reg, RW};
use crate::pac::SIO;
use crate::peripherals;
use embassy::util::Unborrow;
use embassy_extras::{unborrow, unsafe_impl_unborrow};
use embedded_hal::digital::v2 as digital;
/// Represents a digital input or output level.
#[derive(Debug, Eq, PartialEq)]
pub enum Level {
Low,
High,
}
/// Represents a pull setting for an input.
#[derive(Debug, Eq, PartialEq)]
pub enum Pull {
None,
Up,
Down,
}
/// A GPIO bank with up to 32 pins.
#[derive(Debug, Eq, PartialEq)]
pub enum Bank {
Bank0 = 0,
Qspi = 1,
}
pub struct Input<'d, T: Pin> {
pin: T,
phantom: PhantomData<&'d mut T>,
}
impl<'d, T: Pin> Input<'d, T> {
pub fn new(pin: impl Unborrow<Target = T> + 'd, pull: Pull) -> Self {
unborrow!(pin);
unsafe {
pin.pad_ctrl().write(|w| {
w.set_ie(true);
match pull {
Pull::Up => w.set_pue(true),
Pull::Down => w.set_pde(true),
Pull::None => {}
}
});
// disable output in SIO, to use it as input
pin.sio_oe().value_clr().write_value(1 << pin.pin());
pin.io().ctrl().write(|w| {
w.set_funcsel(pac::io::vals::Gpio0CtrlFuncsel::SIO_0.0);
});
}
Self {
pin,
phantom: PhantomData,
}
}
pub fn is_high(&self) -> bool {
!self.is_low()
}
pub fn is_low(&self) -> bool {
let val = 1 << self.pin.pin();
unsafe { self.pin.sio_in().read() & val == 0 }
}
}
impl<'d, T: Pin> Drop for Input<'d, T> {
fn drop(&mut self) {
// todo
}
}
impl<'d, T: Pin> digital::InputPin for Input<'d, T> {
type Error = !;
fn is_high(&self) -> Result<bool, Self::Error> {
Ok(self.is_high())
}
fn is_low(&self) -> Result<bool, Self::Error> {
Ok(self.is_low())
}
}
pub struct Output<'d, T: Pin> {
pin: T,
phantom: PhantomData<&'d mut T>,
}
impl<'d, T: Pin> Output<'d, T> {
// TODO opendrain
pub fn new(pin: impl Unborrow<Target = T> + 'd, initial_output: Level) -> Self {
unborrow!(pin);
unsafe {
match initial_output {
Level::High => pin.sio_out().value_set().write_value(1 << pin.pin()),
Level::Low => pin.sio_out().value_clr().write_value(1 << pin.pin()),
}
pin.sio_oe().value_set().write_value(1 << pin.pin());
pin.io().ctrl().write(|w| {
w.set_funcsel(pac::io::vals::Gpio0CtrlFuncsel::SIO_0.0);
});
}
Self {
pin,
phantom: PhantomData,
}
}
/// Set the output as high.
pub fn set_high(&mut self) {
let val = 1 << self.pin.pin();
unsafe { self.pin.sio_out().value_set().write_value(val) };
}
/// Set the output as low.
pub fn set_low(&mut self) {
let val = 1 << self.pin.pin();
unsafe { self.pin.sio_out().value_clr().write_value(val) };
}
/// Is the output pin set as high?
pub fn is_set_high(&self) -> bool {
!self.is_set_low()
}
/// Is the output pin set as low?
pub fn is_set_low(&self) -> bool {
// todo
true
}
}
impl<'d, T: Pin> Drop for Output<'d, T> {
fn drop(&mut self) {
// todo
}
}
impl<'d, T: Pin> digital::OutputPin for Output<'d, T> {
type Error = !;
/// Set the output as high.
fn set_high(&mut self) -> Result<(), Self::Error> {
self.set_high();
Ok(())
}
/// Set the output as low.
fn set_low(&mut self) -> Result<(), Self::Error> {
self.set_low();
Ok(())
}
}
impl<'d, T: Pin> digital::StatefulOutputPin for Output<'d, T> {
/// Is the output pin set as high?
fn is_set_high(&self) -> Result<bool, Self::Error> {
Ok(self.is_set_high())
}
/// Is the output pin set as low?
fn is_set_low(&self) -> Result<bool, Self::Error> {
Ok(self.is_set_low())
}
}
pub(crate) mod sealed {
use super::*;
pub trait Pin: Sized {
fn pin_bank(&self) -> u8;
#[inline]
fn pin(&self) -> u8 {
self.pin_bank() & 0x1f
}
#[inline]
fn bank(&self) -> Bank {
if self.pin_bank() & 0x20 == 0 {
Bank::Bank0
} else {
Bank::Qspi
}
}
fn io(&self) -> pac::io::Gpio {
let block = match self.bank() {
Bank::Bank0 => crate::pac::IO_BANK0,
Bank::Qspi => crate::pac::IO_QSPI,
};
block.gpio(self.pin() as _)
}
fn pad_ctrl(&self) -> Reg<pac::pads::regs::GpioCtrl, RW> {
let block = match self.bank() {
Bank::Bank0 => crate::pac::PADS_BANK0,
Bank::Qspi => crate::pac::PADS_QSPI,
};
block.gpio(self.pin() as _)
}
fn sio_out(&self) -> pac::sio::Gpio {
SIO.gpio_out(self.bank() as _)
}
fn sio_oe(&self) -> pac::sio::Gpio {
SIO.gpio_oe(self.bank() as _)
}
fn sio_in(&self) -> Reg<u32, RW> {
SIO.gpio_in(self.bank() as _)
}
}
}
pub trait Pin: sealed::Pin {
/// Degrade to a generic pin struct
fn degrade(self) -> AnyPin {
AnyPin {
pin_bank: self.pin_bank(),
}
}
}
pub struct AnyPin {
pin_bank: u8,
}
unsafe_impl_unborrow!(AnyPin);
impl Pin for AnyPin {}
impl sealed::Pin for AnyPin {
fn pin_bank(&self) -> u8 {
self.pin_bank
}
}
macro_rules! impl_pin {
($name:ident, $bank:expr, $pin_num:expr) => {
impl Pin for peripherals::$name {}
impl sealed::Pin for peripherals::$name {
fn pin_bank(&self) -> u8 {
($bank as u8) * 32 + $pin_num
}
}
};
}
impl_pin!(PIN_0, Bank::Bank0, 0);
impl_pin!(PIN_1, Bank::Bank0, 1);
impl_pin!(PIN_2, Bank::Bank0, 2);
impl_pin!(PIN_3, Bank::Bank0, 3);
impl_pin!(PIN_4, Bank::Bank0, 4);
impl_pin!(PIN_5, Bank::Bank0, 5);
impl_pin!(PIN_6, Bank::Bank0, 6);
impl_pin!(PIN_7, Bank::Bank0, 7);
impl_pin!(PIN_8, Bank::Bank0, 8);
impl_pin!(PIN_9, Bank::Bank0, 9);
impl_pin!(PIN_10, Bank::Bank0, 10);
impl_pin!(PIN_11, Bank::Bank0, 11);
impl_pin!(PIN_12, Bank::Bank0, 12);
impl_pin!(PIN_13, Bank::Bank0, 13);
impl_pin!(PIN_14, Bank::Bank0, 14);
impl_pin!(PIN_15, Bank::Bank0, 15);
impl_pin!(PIN_16, Bank::Bank0, 16);
impl_pin!(PIN_17, Bank::Bank0, 17);
impl_pin!(PIN_18, Bank::Bank0, 18);
impl_pin!(PIN_19, Bank::Bank0, 19);
impl_pin!(PIN_20, Bank::Bank0, 20);
impl_pin!(PIN_21, Bank::Bank0, 21);
impl_pin!(PIN_22, Bank::Bank0, 22);
impl_pin!(PIN_23, Bank::Bank0, 23);
impl_pin!(PIN_24, Bank::Bank0, 24);
impl_pin!(PIN_25, Bank::Bank0, 25);
impl_pin!(PIN_26, Bank::Bank0, 26);
impl_pin!(PIN_27, Bank::Bank0, 27);
impl_pin!(PIN_28, Bank::Bank0, 28);
impl_pin!(PIN_29, Bank::Bank0, 29);
impl_pin!(PIN_QSPI_SCLK, Bank::Qspi, 0);
impl_pin!(PIN_QSPI_SS, Bank::Qspi, 1);
impl_pin!(PIN_QSPI_SD0, Bank::Qspi, 2);
impl_pin!(PIN_QSPI_SD1, Bank::Qspi, 3);
impl_pin!(PIN_QSPI_SD2, Bank::Qspi, 4);
impl_pin!(PIN_QSPI_SD3, Bank::Qspi, 5);
|
use diesel::prelude::{QueryDsl, RunQueryDsl};
use sl_lib::*; // delete it later and use filter for tera with rocket later instead
use sl_lib::custom::{str_from_stdin};
use console::Style;
// // delete all in SQL -> DELETE FROM users;
pub fn delete() {
let yellow = Style::new().yellow();
let bold = Style::new().bold();
use schema::users::dsl::*;
let connection = init_pool().get().unwrap();
// println!("{}", "What is author_id?");
println!("{}", bold.apply_to("Type user_id to delete."));
let user_id = str_from_stdin().parse::<i32>().expect("Invalid ID");
println!(
"Are you sure you want to delete user with id {} type [y] to delete or [n] to cancel?",
user_id
);
let decision = str_from_stdin()
.chars()
.next() // equals to .nth(0)
.expect("string is empty");;
match decision {
'y' => {
let user = diesel::delete(users.find(user_id))
.execute(&*connection)
.expect(&format!("Error deleting a user with id {}", user_id));
println!(
"{}",
yellow.apply_to(format!(
"Deleted {} User ", user
))
);
}
'n' => {
println!("You canceled delete process.");
}
_ => {
println!("You should type either [y] or [n]");
}
}
}
|
///! An item is line of text that read from `find` command or stdin together with
///! the internal states, such as selected or not
use std::cmp::min;
use std::default::Default;
use std::ops::Deref;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use crate::spinlock::{SpinLock, SpinLockGuard};
use crate::{MatchRange, Rank, SkimItem};
//------------------------------------------------------------------------------
#[derive(Debug)]
pub struct RankBuilder {
criterion: Vec<RankCriteria>,
}
impl Default for RankBuilder {
fn default() -> Self {
Self {
criterion: vec![RankCriteria::Score, RankCriteria::Begin, RankCriteria::End],
}
}
}
impl RankBuilder {
pub fn new(mut criterion: Vec<RankCriteria>) -> Self {
if !criterion.contains(&RankCriteria::Score) && !criterion.contains(&RankCriteria::NegScore) {
criterion.insert(0, RankCriteria::Score);
}
criterion.dedup();
Self { criterion }
}
/// score: the greater the better
pub fn build_rank(&self, score: i32, begin: usize, end: usize, length: usize) -> Rank {
let mut rank = [0; 4];
let begin = begin as i32;
let end = end as i32;
let length = length as i32;
for (index, criteria) in self.criterion.iter().take(4).enumerate() {
let value = match criteria {
RankCriteria::Score => -score,
RankCriteria::Begin => begin,
RankCriteria::End => end,
RankCriteria::NegScore => score,
RankCriteria::NegBegin => -begin,
RankCriteria::NegEnd => -end,
RankCriteria::Length => length,
RankCriteria::NegLength => -length,
};
rank[index] = value;
}
rank
}
}
//------------------------------------------------------------------------------
#[derive(Clone)]
pub struct MatchedItem {
pub item: Arc<dyn SkimItem>,
pub rank: Rank,
pub matched_range: Option<MatchRange>, // range of chars that matched the pattern
pub item_idx: u32,
}
impl MatchedItem {}
use std::cmp::Ordering as CmpOrd;
impl PartialEq for MatchedItem {
fn eq(&self, other: &Self) -> bool {
self.rank.eq(&other.rank)
}
}
impl std::cmp::Eq for MatchedItem {}
impl PartialOrd for MatchedItem {
fn partial_cmp(&self, other: &Self) -> Option<CmpOrd> {
self.rank.partial_cmp(&other.rank)
}
}
impl Ord for MatchedItem {
fn cmp(&self, other: &Self) -> CmpOrd {
self.rank.cmp(&other.rank)
}
}
//------------------------------------------------------------------------------
const ITEM_POOL_CAPACITY: usize = 1024;
pub struct ItemPool {
length: AtomicUsize,
pool: SpinLock<Vec<Arc<dyn SkimItem>>>,
/// number of items that was `take`n
taken: AtomicUsize,
/// reverse first N lines as header
reserved_items: SpinLock<Vec<Arc<dyn SkimItem>>>,
lines_to_reserve: usize,
}
impl ItemPool {
pub fn new() -> Self {
Self {
length: AtomicUsize::new(0),
pool: SpinLock::new(Vec::with_capacity(ITEM_POOL_CAPACITY)),
taken: AtomicUsize::new(0),
reserved_items: SpinLock::new(Vec::new()),
lines_to_reserve: 0,
}
}
pub fn lines_to_reserve(mut self, lines_to_reserve: usize) -> Self {
self.lines_to_reserve = lines_to_reserve;
self
}
pub fn len(&self) -> usize {
self.length.load(Ordering::SeqCst)
}
pub fn num_not_taken(&self) -> usize {
self.length.load(Ordering::SeqCst) - self.taken.load(Ordering::SeqCst)
}
pub fn num_taken(&self) -> usize {
self.taken.load(Ordering::SeqCst)
}
pub fn clear(&self) {
let mut items = self.pool.lock();
items.clear();
let mut header_items = self.reserved_items.lock();
header_items.clear();
self.taken.store(0, Ordering::SeqCst);
self.length.store(0, Ordering::SeqCst);
}
pub fn reset(&self) {
// lock to ensure consistency
let _items = self.pool.lock();
self.taken.store(0, Ordering::SeqCst);
}
/// append the items and return the new_size of the pool
pub fn append(&self, mut items: Vec<Arc<dyn SkimItem>>) -> usize {
let len = items.len();
trace!("item pool, append {} items", len);
let mut pool = self.pool.lock();
let mut header_items = self.reserved_items.lock();
let to_reserve = self.lines_to_reserve - header_items.len();
if to_reserve > 0 {
let to_reserve = min(to_reserve, items.len());
header_items.extend_from_slice(&items[..to_reserve]);
pool.extend_from_slice(&items[to_reserve..]);
} else {
pool.append(&mut items);
}
self.length.store(pool.len(), Ordering::SeqCst);
trace!("item pool, done append {} items", len);
pool.len()
}
pub fn take(&self) -> ItemPoolGuard<Arc<dyn SkimItem>> {
let guard = self.pool.lock();
let taken = self.taken.swap(guard.len(), Ordering::SeqCst);
ItemPoolGuard { guard, start: taken }
}
pub fn reserved(&self) -> ItemPoolGuard<Arc<dyn SkimItem>> {
let guard = self.reserved_items.lock();
ItemPoolGuard { guard, start: 0 }
}
}
pub struct ItemPoolGuard<'a, T: Sized + 'a> {
guard: SpinLockGuard<'a, Vec<T>>,
start: usize,
}
impl<'mutex, T: Sized> Deref for ItemPoolGuard<'mutex, T> {
type Target = [T];
fn deref(&self) -> &[T] {
&self.guard[self.start..]
}
}
//------------------------------------------------------------------------------
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum RankCriteria {
Score,
Begin,
End,
NegScore,
NegBegin,
NegEnd,
Length,
NegLength,
}
pub fn parse_criteria(text: &str) -> Option<RankCriteria> {
match text.to_lowercase().as_ref() {
"score" => Some(RankCriteria::Score),
"begin" => Some(RankCriteria::Begin),
"end" => Some(RankCriteria::End),
"-score" => Some(RankCriteria::NegScore),
"-begin" => Some(RankCriteria::NegBegin),
"-end" => Some(RankCriteria::NegEnd),
"length" => Some(RankCriteria::Length),
"-length" => Some(RankCriteria::NegLength),
_ => None,
}
}
|
/*
* Datadog API V1 Collection
*
* Collection of all Datadog Public endpoints.
*
* The version of the OpenAPI document: 1.0
* Contact: support@datadoghq.com
* Generated by: https://openapi-generator.tech
*/
/// UsageAttributionAggregatesBody : The object containing the aggregates.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UsageAttributionAggregatesBody {
/// The aggregate type.
#[serde(rename = "agg_type", skip_serializing_if = "Option::is_none")]
pub agg_type: Option<String>,
/// The field.
#[serde(rename = "field", skip_serializing_if = "Option::is_none")]
pub field: Option<String>,
/// The value for a given field.
#[serde(rename = "value", skip_serializing_if = "Option::is_none")]
pub value: Option<f64>,
}
impl UsageAttributionAggregatesBody {
/// The object containing the aggregates.
pub fn new() -> UsageAttributionAggregatesBody {
UsageAttributionAggregatesBody {
agg_type: None,
field: None,
value: None,
}
}
}
|
extern crate bincode;
extern crate solana_program_interface;
use bincode::deserialize;
use solana_program_interface::account::KeyedAccount;
#[no_mangle]
pub extern "C" fn process(keyed_accounts: &mut Vec<KeyedAccount>, data: &[u8]) -> bool {
let tokens: i64 = deserialize(data).unwrap();
if keyed_accounts[0].account.tokens >= tokens {
keyed_accounts[0].account.tokens -= tokens;
keyed_accounts[1].account.tokens += tokens;
true
} else {
println!(
"Insufficient funds, asked {}, only had {}",
tokens, keyed_accounts[0].account.tokens
);
false
}
}
#[cfg(test)]
mod tests {
use super::*;
use bincode::serialize;
use solana_program_interface::account::Account;
use solana_program_interface::pubkey::Pubkey;
#[test]
fn test_move_funds() {
let tokens: i64 = 100;
let data: Vec<u8> = serialize(&tokens).unwrap();
let keys = vec![Pubkey::default(); 2];
let mut accounts = vec![Account::default(), Account::default()];
accounts[0].tokens = 100;
accounts[1].tokens = 1;
{
let mut keyed_accounts: Vec<KeyedAccount> = Vec::new();
for (key, account) in keys.iter().zip(&mut accounts).collect::<Vec<_>>() {
infos.push(KeyedAccount { key, account });
}
process(&mut keyed_accounts, &data);
}
assert_eq!(0, accounts[0].tokens);
assert_eq!(101, accounts[1].tokens);
}
}
|
extern crate dotenv;
extern crate iron;
extern crate mount;
extern crate router;
extern crate iron_sessionstorage;
extern crate urlencoded;
extern crate serde_json;
extern crate iron_test;
mod utils;
mod routes;
use dotenv::dotenv;
use iron::prelude::{Iron, Chain};
use iron_sessionstorage::SessionStorage;
use iron_sessionstorage::backends::SignedCookieBackend;
use routes::Routes;
use utils::get_env;
fn main() {
dotenv().ok();
let port = get_env("PORT");
let cookie_secret = get_env("COOKIE_SECRET");
let router = Routes::new();
let mut chain = Chain::new(router);
let session = SessionStorage::new(SignedCookieBackend::new(cookie_secret.into_bytes()));
chain.link_around(session);
let server = Iron::new(chain).http(format!("0.0.0.0:{}", port));
match server {
Ok(listen) => println!("Server starting -> {:?}", listen.socket),
Err(err) => println!("Server failed start because {}...", err),
}
}
|
use std::collections::{HashMap, HashSet};
fn parse_rule(r: &str) -> (String, String, i32) {
let mut parts = r.split(' ');
let name = parts.next().unwrap().to_owned();
parts.next();
let change = parts.next().unwrap();
let delta: i32 = parts.next().unwrap().parse().unwrap();
let delta = if change == "gain" { delta } else { -delta };
let other = parts.last().unwrap().trim_end_matches('.').to_owned();
(name, other, delta)
}
fn parse_input(input: &str) -> (HashSet<String>, HashMap<(String, String), i32>) {
let mut names = HashSet::new();
let mut rules = HashMap::new();
for (name, other, delta) in input.lines().map(|l| parse_rule(l)) {
names.insert(name.clone());
rules.insert((name, other), delta);
}
(names, rules)
}
fn total_delta(table: &[String], rules: &HashMap<(String, String), i32>) -> i32 {
let n = table.len();
let mut sum = 0;
for i in 0..n {
let left = if i == 0 { n - 1 } else { i - 1 };
let left = table[left].clone();
let right = (i + 1) % n;
let right = table[right].clone();
sum += rules.get(&(table[i].clone(), left)).unwrap();
sum += rules.get(&(table[i].clone(), right)).unwrap();
}
sum
}
fn arrange(table: &mut Vec<String>, names: &HashSet<String>, rules: &HashMap<(String, String), i32>) -> i32 {
if table.len() == names.len() {
return total_delta(table, rules);
}
let mut max_delta = i32::MIN;
for name in names.iter() {
if table.contains(name) {
continue;
}
table.push(name.clone());
let delta = arrange(table, names, rules);
table.pop();
if delta > max_delta {
max_delta = delta;
}
}
max_delta
}
fn main() {
let (names, rules) = parse_input(&std::fs::read_to_string("input").unwrap());
part1(&names, &rules);
part2(names, rules);
}
fn part1(names: &HashSet<String>, rules: &HashMap<(String, String), i32>) {
let max_delta = arrange(&mut Vec::new(), names, rules);
println!("{}", max_delta);
}
fn part2(mut names: HashSet<String>, mut rules: HashMap<(String, String), i32>) {
for name in names.iter() {
rules.insert(("You".to_owned(), name.clone()), 0);
rules.insert((name.clone(), "You".to_owned()), 0);
}
names.insert("You".to_owned());
let max_delta = arrange(&mut Vec::new(), &names, &rules);
println!("{}", max_delta);
}
#[cfg(test)]
mod tests {
use super::*;
fn gen_input() -> (HashSet<String>, HashMap<(String, String), i32>) {
parse_input("Alice would gain 54 happiness units by sitting next to Bob.
Alice would lose 79 happiness units by sitting next to Carol.
Alice would lose 2 happiness units by sitting next to David.
Bob would gain 83 happiness units by sitting next to Alice.
Bob would lose 7 happiness units by sitting next to Carol.
Bob would lose 63 happiness units by sitting next to David.
Carol would lose 62 happiness units by sitting next to Alice.
Carol would gain 60 happiness units by sitting next to Bob.
Carol would gain 55 happiness units by sitting next to David.
David would gain 46 happiness units by sitting next to Alice.
David would lose 7 happiness units by sitting next to Bob.
David would gain 41 happiness units by sitting next to Carol.")
}
#[test]
fn test_total_delta() {
let (_names, rules) = gen_input();
let table = ["Alice".to_owned(), "Bob".to_owned(), "Carol".to_owned(), "David".to_owned()];
assert_eq!(total_delta(&table, &rules), 330);
}
#[test]
fn test_arrange() {
let (names, rules) = gen_input();
assert_eq!(arrange(&mut Vec::new(), &names, &rules), 330);
}
}
|
// Implemented outside of windows-service as it's somewhat special-case
//
// TODO: check a lot of careless stuff in here, I didn't understand absolute vs.
// self-relative Security Descriptors at the time I wrote it. Probably a number
// of double-frees around.
use std::ffi::OsStr;
use std::ptr::{null, null_mut};
use widestring::WideCString;
use winapi::shared::lmcons::{DNLEN, UNLEN};
use winapi::shared::minwindef::{DWORD, FALSE, LPDWORD, TRUE};
use winapi::um::minwinbase::LPTR;
use winapi::um::winnt::{PACL, PSECURITY_DESCRIPTOR, SECURITY_DESCRIPTOR, WELL_KNOWN_SID_TYPE};
use util::*;
use {ErrorKind, Result};
fn get_last_error() -> DWORD {
use winapi::um::errhandlingapi::GetLastError;
unsafe { GetLastError() }
}
/// Grant start and stop access to a service to all local users (TODO check what WinBuiltinUsersSid exactly means).
pub fn grant_service_access<T: AsRef<OsStr>>(service_name: T) -> Result<()> {
let service_manager = open_service_manager()?;
let service = open_service(&service_manager, service_name)?;
let sd = read_service_dacl(&service)?;
set_user_permissions(&service, &sd.pacl)?;
Ok(())
}
/// Create security descriptor for read and write access for all local users
pub fn users_access() -> Result<SECURITY_DESCRIPTOR> {
use winapi::um::winnt::{WinBuiltinUsersSid, GENERIC_READ, GENERIC_WRITE};
update_acl(
&null_mut(),
&mut well_known_account_name(WinBuiltinUsersSid)?,
GENERIC_READ | GENERIC_WRITE,
)
}
fn open_service_manager() -> Result<SCHolder> {
use winapi::um::winsvc::OpenSCManagerW;
// Open the service manager
let service_manager = SCHolder(unsafe {
OpenSCManagerW(
null(), // local computer
null(), // active database
0, // no special permissions needed
)
});
if service_manager.valid() {
Ok(service_manager)
} else {
os_error!("OpenSCManagerW")
}
}
fn open_service<T: AsRef<OsStr>>(service_manager: &SCHolder, service_name: T) -> Result<SCHolder> {
use winapi::um::winnt::{READ_CONTROL, WRITE_DAC};
use winapi::um::winsvc::OpenServiceW;
let service_name = WideCString::from_str(service_name).unwrap();
let service = SCHolder(unsafe {
OpenServiceW(
**service_manager,
service_name.as_ptr(),
READ_CONTROL | WRITE_DAC,
)
});
if service.valid() {
Ok(service)
} else {
os_error!("OpenServiceW")
}
}
// These are kept together to avoid pacl from outliving psd
// TODO: find a proper way to do this with lifetimes?
struct SD {
_psd: LAHolder,
pacl: PACL,
}
fn read_service_dacl(service: &SCHolder) -> Result<SD> {
use winapi::shared::minwindef::LPBOOL;
use winapi::shared::winerror::ERROR_INSUFFICIENT_BUFFER;
use winapi::um::securitybaseapi::GetSecurityDescriptorDacl;
use winapi::um::winbase::LocalAlloc;
use winapi::um::winnt::DACL_SECURITY_INFORMATION;
use winapi::um::winsvc::QueryServiceObjectSecurity;
// Find size needed
let mut bytes_needed: DWORD = 0;
let rc = unsafe {
QueryServiceObjectSecurity(
**service,
DACL_SECURITY_INFORMATION,
null_mut(), // lpSecurityDescriptor
0, // cbBufSize
&mut bytes_needed as LPDWORD,
)
};
if rc != 0 || get_last_error() != ERROR_INSUFFICIENT_BUFFER {
return os_error!("QueryServiceObjectSecurity for size");
}
let psd = LAHolder(unsafe { LocalAlloc(LPTR, bytes_needed as usize) });
if !psd.valid() {
return os_error!("LocalAlloc for security descriptor");
}
let mut temp_bytes_needed: DWORD = 0;
let rc = unsafe {
QueryServiceObjectSecurity(
**service,
DACL_SECURITY_INFORMATION,
*psd, // lpSecurityDescriptor
bytes_needed, // cbBufSize
&mut temp_bytes_needed as LPDWORD,
)
};
if rc == 0 {
return os_error!("QueryServiceObjectSecurity for DACL");
}
// NOTE: we don't ever want to free this pointer, it points into psd
let mut pacl = null_mut();
let mut dacl_present = FALSE;
let mut dacl_defaulted = FALSE;
let rc = unsafe {
GetSecurityDescriptorDacl(
*psd,
&mut dacl_present as LPBOOL,
&mut pacl,
&mut dacl_defaulted as LPBOOL,
)
};
if rc == 0 {
return os_error!("GetSecurityDescriptorDacl");
}
Ok(SD { _psd: psd, pacl })
}
fn set_user_permissions(service: &SCHolder, pacl: &PACL) -> Result<()> {
use winapi::um::winnt::{WinBuiltinUsersSid, DACL_SECURITY_INFORMATION, GENERIC_READ};
use winapi::um::winsvc::{SetServiceObjectSecurity, SERVICE_START, SERVICE_STOP};
// Update ACL with permission for Users
let mut account_name = well_known_account_name(WinBuiltinUsersSid)?;
let permissions = SERVICE_START | SERVICE_STOP | GENERIC_READ;
let mut sd = update_acl(&pacl, &mut account_name, permissions)?;
let rc = unsafe {
SetServiceObjectSecurity(
**service,
DACL_SECURITY_INFORMATION,
&mut sd as *mut SECURITY_DESCRIPTOR as PSECURITY_DESCRIPTOR,
)
};
if rc == 0 {
os_error!("SetServiceObjectSecurity")
} else {
Ok(())
}
}
type AccountName = [u16; UNLEN as usize + 1];
fn well_known_account_name(sid_type: WELL_KNOWN_SID_TYPE) -> Result<AccountName> {
use winapi::shared::minwindef::BOOL;
use winapi::um::minwinbase::LMEM_FIXED;
use winapi::um::securitybaseapi::CreateWellKnownSid;
use winapi::um::winbase::LocalAlloc;
use winapi::um::winnt::{LPCWSTR, LPWSTR, PSID, PSID_NAME_USE, SECURITY_MAX_SID_SIZE};
let mut sid_size = SECURITY_MAX_SID_SIZE as DWORD;
let psid = LAHolder(unsafe { LocalAlloc(LMEM_FIXED, sid_size as usize) });
if psid.is_null() {
return os_error!("LocalAlloc for SID");
}
let rc = unsafe {
CreateWellKnownSid(
sid_type, // WellKnownSidType
null_mut(), // DomainSid
*psid, // pSid
&mut sid_size, // cbSid
)
};
if rc == 0 {
return os_error!("CreateWellKnownSid");
}
let mut account_name = [0; UNLEN as usize + 1];
let mut account_name_len = account_name.len() as DWORD;
// We don't use domain name but it is supposedly needed despite being marked
// _Out_opt_ in MSDN
let mut domain_name = [0; DNLEN as usize + 1];
let mut domain_name_len = domain_name.len() as DWORD;
let mut account_type = 0u32;
extern "system" {
pub fn LookupAccountSidW(
lpSystemName: LPCWSTR,
lpSid: PSID,
lpName: LPWSTR,
cchName: LPDWORD,
lpReferencedDomainName: LPWSTR,
cchReferencedDomainName: LPDWORD,
peUse: PSID_NAME_USE,
) -> BOOL;
}
let rc = unsafe {
LookupAccountSidW(
null(), // lpSystemName, local system
*psid,
account_name.as_mut_ptr(),
&mut account_name_len as LPDWORD,
domain_name.as_mut_ptr(),
&mut domain_name_len as LPDWORD,
&mut account_type as PSID_NAME_USE,
)
};
if rc == 0 {
return os_error!("LookupAccountSidW");
}
Ok(account_name)
}
fn update_acl(
pacl: &PACL,
account_name: &mut AccountName,
permissions: DWORD,
) -> Result<SECURITY_DESCRIPTOR> {
use winapi::shared::winerror::ERROR_SUCCESS;
use winapi::um::accctrl::{EXPLICIT_ACCESS_W, NO_INHERITANCE, SET_ACCESS, TRUSTEE_W};
use winapi::um::aclapi::{BuildExplicitAccessWithNameW, SetEntriesInAclW};
use winapi::um::securitybaseapi::{InitializeSecurityDescriptor, SetSecurityDescriptorDacl};
use winapi::um::winnt::SECURITY_DESCRIPTOR_REVISION;
let mut ea = EXPLICIT_ACCESS_W {
grfAccessPermissions: 0,
grfAccessMode: 0,
grfInheritance: 0,
Trustee: TRUSTEE_W {
pMultipleTrustee: null_mut(),
MultipleTrusteeOperation: 0,
TrusteeForm: 0,
TrusteeType: 0,
ptstrName: null_mut(),
},
};
unsafe {
BuildExplicitAccessWithNameW(
&mut ea,
account_name.as_mut_ptr(),
permissions,
SET_ACCESS,
NO_INHERITANCE,
)
};
let mut new_pacl = null_mut();
let rc = unsafe {
SetEntriesInAclW(
1, // cCountOfExplicitEntries
&mut ea, // pListOfExplicitEntries
*pacl, // OldAcl
&mut new_pacl as *mut PACL, // NewAcl
)
};
if rc != ERROR_SUCCESS {
return os_error!("SetEntriesInAclW");
}
let mut sd = SECURITY_DESCRIPTOR {
Revision: 0,
Sbz1: 0,
Control: 0,
Owner: null_mut(),
Group: null_mut(),
Sacl: null_mut(),
Dacl: null_mut(),
};
let rc = unsafe {
InitializeSecurityDescriptor(
&mut sd as *mut SECURITY_DESCRIPTOR as PSECURITY_DESCRIPTOR,
SECURITY_DESCRIPTOR_REVISION,
)
};
if rc == 0 {
return os_error!("InitializeSecurityDescriptor");
}
let rc = unsafe {
SetSecurityDescriptorDacl(
&mut sd as *mut SECURITY_DESCRIPTOR as PSECURITY_DESCRIPTOR,
TRUE, // bDaclPresent
new_pacl,
FALSE, // bDaclDefaulted
)
};
if rc == 0 {
return os_error!("SetSecurityDescriptorDacl");
}
Ok(sd)
}
|
use crate::{PieceType, PlayerColor};
use super::DenseBoard;
use rand::distributions::{Distribution, Standard};
use rand::seq::SliceRandom;
use rand::Rng;
/// Defines a random generator for Paco ลako games that are not over yet.
/// I.e. where both kings are still free. This works by placing the pieces
/// randomly on the board.
impl Distribution<DenseBoard> for Standard {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> DenseBoard {
let mut board = DenseBoard::new();
// Shuffle white and black pieces around
board.white.shuffle(rng);
board.black.shuffle(rng);
// Check all positions for violations
// No pawns on the enemy home row
for i in 0..64 {
if i < 8 && board.black[i] == Some(PieceType::Pawn) {
let free_index = loop {
let candidate = random_position_without_black(&board, rng);
if candidate >= 8 {
break candidate;
}
};
board.black.swap(i, free_index);
}
if i >= 56 && board.white[i] == Some(PieceType::Pawn) {
let free_index = loop {
let candidate = random_position_without_white(&board, rng);
if candidate < 56 {
break candidate;
}
};
board.white.swap(i, free_index);
}
}
// No single pawns on the own home row
for i in 0..64 {
if i < 8
&& board.white[i] == Some(PieceType::Pawn)
&& (board.black[i].is_none() || board.black[i] == Some(PieceType::King))
{
let free_index = loop {
let candidate = random_position_without_white(&board, rng);
if (8..56).contains(&candidate) {
break candidate;
}
};
board.white.swap(i, free_index);
}
if i >= 56
&& board.black[i] == Some(PieceType::Pawn)
&& (board.white[i].is_none() || board.white[i] == Some(PieceType::King))
{
let free_index = loop {
let candidate = random_position_without_black(&board, rng);
if (8..56).contains(&candidate) {
break candidate;
}
};
board.black.swap(i, free_index);
}
}
// Ensure, that the king is single. (Done after all other pieces are moved).
for i in 0..64 {
if board.white[i] == Some(PieceType::King) && board.black[i].is_some() {
let free_index = random_empty_position(&board, rng);
board.white.swap(i, free_index);
}
if board.black[i] == Some(PieceType::King) && board.white[i].is_some() {
let free_index = random_empty_position(&board, rng);
board.black.swap(i, free_index);
}
}
// Randomize current player
board.controlling_player = if rng.gen() {
PlayerColor::White
} else {
PlayerColor::Black
};
// Figure out if any castling permissions remain
let white_king_in_position = board.white[4] == Some(PieceType::King);
let black_king_in_position = board.black[60] == Some(PieceType::King);
board.castling.white_queen_side =
white_king_in_position && board.white[0] == Some(PieceType::Rook);
board.castling.white_king_side =
white_king_in_position && board.white[7] == Some(PieceType::Rook);
board.castling.black_queen_side =
black_king_in_position && board.black[56] == Some(PieceType::Rook);
board.castling.black_king_side =
black_king_in_position && board.black[63] == Some(PieceType::Rook);
board
}
}
/// This will not terminate if the board is full.
/// The runtime of this function is not deterministic. (Geometric distribution)
fn random_empty_position<R: Rng + ?Sized>(board: &DenseBoard, rng: &mut R) -> usize {
loop {
let candidate = rng.gen_range(0..64);
if board.white[candidate].is_none() && board.black[candidate].is_none() {
return candidate;
}
}
}
/// This will not terminate if the board is full.
/// The runtime of this function is not deterministic. (Geometric distribution)
fn random_position_without_white<R: Rng + ?Sized>(board: &DenseBoard, rng: &mut R) -> usize {
loop {
let candidate = rng.gen_range(0..64);
if board.white[candidate].is_none() {
return candidate;
}
}
}
/// This will not terminate if the board is full.
/// The runtime of this function is not deterministic. (Geometric distribution)
fn random_position_without_black<R: Rng + ?Sized>(board: &DenseBoard, rng: &mut R) -> usize {
loop {
let candidate = rng.gen_range(0..64);
if board.black[candidate].is_none() {
return candidate;
}
}
}
#[cfg(test)]
mod tests {
use crate::{DenseBoard, PieceType};
#[test]
fn random_dense_board_consistent() {
use rand::{thread_rng, Rng};
let mut rng = thread_rng();
for _ in 0..1000 {
let board: DenseBoard = rng.gen();
let mut whites_found = 0;
let mut blacks_found = 0;
// Check all positions for violations
for i in 0..64 {
// Count pieces
if board.white[i].is_some() {
whites_found += 1;
}
if board.black[i].is_some() {
blacks_found += 1;
}
// The king should be single
if board.white[i] == Some(PieceType::King) {
assert_eq!(
board.black[i], None,
"The white king is united.\n{:?}",
board
);
}
if board.black[i] == Some(PieceType::King) {
assert_eq!(
board.white[i], None,
"The black king is united.\n{:?}",
board
);
}
// No pawns on the enemy home row
// No single pawns on the own home row
if i < 8 {
assert_ne!(
board.black[i],
Some(PieceType::Pawn),
"There is a black pawn on the white home row\n{:?}",
board
);
if board.black[i].is_none() {
assert_ne!(
board.white[i],
Some(PieceType::Pawn),
"There is a single white pawn on the white home row\n{:?}",
board
);
}
}
if i >= 56 {
assert_ne!(
board.white[i],
Some(PieceType::Pawn),
"There is a white pawn on the black home row\n{:?}",
board
);
if board.white[i].is_none() {
assert_ne!(
board.black[i],
Some(PieceType::Pawn),
"There is a single black pawn on the black home row\n{:?}",
board
);
}
}
}
assert_eq!(whites_found, 16);
assert_eq!(blacks_found, 16);
}
}
}
|
extern crate crc;
extern crate memmap;
extern crate byteorder;
pub mod storage;
fn main() {}
|
use amethyst::{
assets::PrefabData,
derive::PrefabData,
ecs::{Component, DenseVecStorage, Entity, WriteStorage},
Error,
};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub enum LogicModule {
SillyRun,
EngineRunner(String),
}
#[derive(Clone, Debug, Serialize, Deserialize, PrefabData)]
#[prefab(Component)]
pub struct Robot {
pub logic_module: LogicModule,
}
impl Default for Robot {
fn default() -> Self {
Robot {
logic_module: LogicModule::EngineRunner("basic".to_string()),
}
}
}
impl Component for Robot {
type Storage = DenseVecStorage<Self>;
}
|
use super::*;
#[test]
fn test_decode_sb_immediate() {
let predicted_imm = decode_sb_immediate(&[0x63,0x2,0x0,0x0]);
println!("Decoded: {:032b}\n Actual: {:032b}", predicted_imm, 4);
assert_eq!(predicted_imm, 4);
let predicted_imm = decode_sb_immediate(&[0xe3, 0x0e, 0x00, 0xfe]);
println!("Decoded: {:032b}\n Actual: {:032b}", predicted_imm, -4);
assert_eq!(predicted_imm, -4);
}
#[test]
fn test_decode_u_immediate() {
let predicted_imm = decode_u_type_immediate(&[0xb7, 0xf2, 0xff, 0xff]);
println!("Decoded: {:032b}\n Actual: {:032b}", predicted_imm, 0xFFFFF000);
assert_eq!(predicted_imm, 0xFFFFF000);
let predicted_imm = decode_u_type_immediate(&[0xb7, 0x02, 0x0f, 0x0f]);
println!("Decoded: {:032b}\n Actual: {:032b}", predicted_imm, 0x0F0F0000);
assert_eq!(predicted_imm, 0x0F0F0000);
}
#[test]
fn test_decode_i_immediate() {
let predicted_imm = decode_i_type_immediate(&[0x93, 0x02, 0xf0, 0x7f]);
println!("Decoded: {:032b}\n Actual: {:032b}", predicted_imm, 0x7FF);
assert_eq!(predicted_imm, 0x7FF);
let predicted_imm = decode_i_type_immediate(&[0x93, 0x02, 0x10, 0x80]);
println!("Decoded: {:032b}\n Actual: {:032b}", predicted_imm, -0x7FF);
assert_eq!(predicted_imm, -0x7FF);
}
#[test]
fn test_decode_s_immediate() {
let predicted_imm = decode_s_type_immediate(&[0xa3, 0xaf, 0x52, 0x02]);
println!("Decoded: {:032b}\n Actual: {:032b}", predicted_imm, 0x3F);
assert_eq!(predicted_imm, 0x3F);
let predicted_imm = decode_s_type_immediate(&[0xa3, 0xa0, 0x52, 0xfc]);
println!("Decoded: {:032b}\n Actual: {:032b}", predicted_imm, -0x3F);
assert_eq!(predicted_imm, -0x3F);
}
#[test]
fn test_decode_uj_immediate() {
let predicted_imm = decode_uj_type_immediate(&[0x6f, 0x00, 0x40, 0x08]);
println!("Decoded: {:032b}\n Actual: {:032b}", predicted_imm, 0x84);
assert_eq!(predicted_imm, 0x84);
let predicted_imm = decode_uj_type_immediate(&[0x6f, 0xf0, 0xdf, 0xf7]);
println!("Decoded: {:032b}\n Actual: {:032b}", predicted_imm, -0x84);
assert_eq!(predicted_imm, -0x84);
} |
#[doc = "Register `DDRCTRL_DRAMTMG5` reader"]
pub type R = crate::R<DDRCTRL_DRAMTMG5_SPEC>;
#[doc = "Register `DDRCTRL_DRAMTMG5` writer"]
pub type W = crate::W<DDRCTRL_DRAMTMG5_SPEC>;
#[doc = "Field `T_CKE` reader - T_CKE"]
pub type T_CKE_R = crate::FieldReader;
#[doc = "Field `T_CKE` writer - T_CKE"]
pub type T_CKE_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 5, O>;
#[doc = "Field `T_CKESR` reader - T_CKESR"]
pub type T_CKESR_R = crate::FieldReader;
#[doc = "Field `T_CKESR` writer - T_CKESR"]
pub type T_CKESR_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 6, O>;
#[doc = "Field `T_CKSRE` reader - T_CKSRE"]
pub type T_CKSRE_R = crate::FieldReader;
#[doc = "Field `T_CKSRE` writer - T_CKSRE"]
pub type T_CKSRE_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>;
#[doc = "Field `T_CKSRX` reader - T_CKSRX"]
pub type T_CKSRX_R = crate::FieldReader;
#[doc = "Field `T_CKSRX` writer - T_CKSRX"]
pub type T_CKSRX_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>;
impl R {
#[doc = "Bits 0:4 - T_CKE"]
#[inline(always)]
pub fn t_cke(&self) -> T_CKE_R {
T_CKE_R::new((self.bits & 0x1f) as u8)
}
#[doc = "Bits 8:13 - T_CKESR"]
#[inline(always)]
pub fn t_ckesr(&self) -> T_CKESR_R {
T_CKESR_R::new(((self.bits >> 8) & 0x3f) as u8)
}
#[doc = "Bits 16:19 - T_CKSRE"]
#[inline(always)]
pub fn t_cksre(&self) -> T_CKSRE_R {
T_CKSRE_R::new(((self.bits >> 16) & 0x0f) as u8)
}
#[doc = "Bits 24:27 - T_CKSRX"]
#[inline(always)]
pub fn t_cksrx(&self) -> T_CKSRX_R {
T_CKSRX_R::new(((self.bits >> 24) & 0x0f) as u8)
}
}
impl W {
#[doc = "Bits 0:4 - T_CKE"]
#[inline(always)]
#[must_use]
pub fn t_cke(&mut self) -> T_CKE_W<DDRCTRL_DRAMTMG5_SPEC, 0> {
T_CKE_W::new(self)
}
#[doc = "Bits 8:13 - T_CKESR"]
#[inline(always)]
#[must_use]
pub fn t_ckesr(&mut self) -> T_CKESR_W<DDRCTRL_DRAMTMG5_SPEC, 8> {
T_CKESR_W::new(self)
}
#[doc = "Bits 16:19 - T_CKSRE"]
#[inline(always)]
#[must_use]
pub fn t_cksre(&mut self) -> T_CKSRE_W<DDRCTRL_DRAMTMG5_SPEC, 16> {
T_CKSRE_W::new(self)
}
#[doc = "Bits 24:27 - T_CKSRX"]
#[inline(always)]
#[must_use]
pub fn t_cksrx(&mut self) -> T_CKSRX_W<DDRCTRL_DRAMTMG5_SPEC, 24> {
T_CKSRX_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 = "DDRCTRL SDRAM timing register 5\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ddrctrl_dramtmg5::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 [`ddrctrl_dramtmg5::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct DDRCTRL_DRAMTMG5_SPEC;
impl crate::RegisterSpec for DDRCTRL_DRAMTMG5_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`ddrctrl_dramtmg5::R`](R) reader structure"]
impl crate::Readable for DDRCTRL_DRAMTMG5_SPEC {}
#[doc = "`write(|w| ..)` method takes [`ddrctrl_dramtmg5::W`](W) writer structure"]
impl crate::Writable for DDRCTRL_DRAMTMG5_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets DDRCTRL_DRAMTMG5 to value 0x0505_0403"]
impl crate::Resettable for DDRCTRL_DRAMTMG5_SPEC {
const RESET_VALUE: Self::Ux = 0x0505_0403;
}
|
// q0114_flatten_binary_tree_to_linked_list
struct Solution;
use crate::util::TreeNode;
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
pub fn flatten(root: &mut Option<Rc<RefCell<TreeNode>>>) {
Solution::flatten_tree(root.clone());
}
fn flatten_tree(
tree: Option<Rc<RefCell<TreeNode>>>,
) -> (Option<Rc<RefCell<TreeNode>>>, Option<Rc<RefCell<TreeNode>>>) {
if let Some(rcc_t) = tree {
let mut tn = rcc_t.borrow_mut();
match (&tn.left, &tn.right) {
(Some(ln), Some(rn)) => {
let (nlt, llast_node) = Solution::flatten_tree(Some(Rc::clone(ln)));
let (nrt, rlast_node) = Solution::flatten_tree(Some(Rc::clone(rn)));
tn.right = nlt;
tn.left = None;
llast_node.as_ref().unwrap().borrow_mut().right = nrt;
return (Some(Rc::clone(&rcc_t)), rlast_node);
}
(Some(ln), None) => {
let (nlt, last_node) = Solution::flatten_tree(Some(Rc::clone(ln)));
tn.right = nlt;
tn.left = None;
return (Some(Rc::clone(&rcc_t)), last_node);
}
(None, Some(rn)) => {
let (_, last_node) = Solution::flatten_tree(Some(Rc::clone(rn)));
return (Some(Rc::clone(&rcc_t)), last_node);
}
(None, None) => return (Some(Rc::clone(&rcc_t)), Some(Rc::clone(&rcc_t))),
}
} else {
return (None, None);
}
}
}
#[cfg(test)]
mod tests {
use super::Solution;
use crate::util::TreeNode;
#[test]
fn it_works() {
let mut input = TreeNode::build_with_str("[1,2,5,3,4,null,6]");
Solution::flatten(&mut input);
assert_eq!(
TreeNode::build_with_str("[1,null,2,null,3,null,4,null,5,null,6]"),
input
);
let mut input = TreeNode::build_with_str("[1,2,3]");
Solution::flatten(&mut input);
assert_eq!(TreeNode::build_with_str("[1,null,2,null,3]"), input);
}
}
|
/// An enum to represent all characters in the Manichaean block.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum Manichaean {
/// \u{10ac0}: '๐ซ'
LetterAleph,
/// \u{10ac1}: '๐ซ'
LetterBeth,
/// \u{10ac2}: '๐ซ'
LetterBheth,
/// \u{10ac3}: '๐ซ'
LetterGimel,
/// \u{10ac4}: '๐ซ'
LetterGhimel,
/// \u{10ac5}: '๐ซ
'
LetterDaleth,
/// \u{10ac6}: '๐ซ'
LetterHe,
/// \u{10ac7}: '๐ซ'
LetterWaw,
/// \u{10ac8}: '๐ซ'
SignUd,
/// \u{10ac9}: '๐ซ'
LetterZayin,
/// \u{10aca}: '๐ซ'
LetterZhayin,
/// \u{10acb}: '๐ซ'
LetterJayin,
/// \u{10acc}: '๐ซ'
LetterJhayin,
/// \u{10acd}: '๐ซ'
LetterHeth,
/// \u{10ace}: '๐ซ'
LetterTeth,
/// \u{10acf}: '๐ซ'
LetterYodh,
/// \u{10ad0}: '๐ซ'
LetterKaph,
/// \u{10ad1}: '๐ซ'
LetterXaph,
/// \u{10ad2}: '๐ซ'
LetterKhaph,
/// \u{10ad3}: '๐ซ'
LetterLamedh,
/// \u{10ad4}: '๐ซ'
LetterDhamedh,
/// \u{10ad5}: '๐ซ'
LetterThamedh,
/// \u{10ad6}: '๐ซ'
LetterMem,
/// \u{10ad7}: '๐ซ'
LetterNun,
/// \u{10ad8}: '๐ซ'
LetterSamekh,
/// \u{10ad9}: '๐ซ'
LetterAyin,
/// \u{10ada}: '๐ซ'
LetterAayin,
/// \u{10adb}: '๐ซ'
LetterPe,
/// \u{10adc}: '๐ซ'
LetterFe,
/// \u{10add}: '๐ซ'
LetterSadhe,
/// \u{10ade}: '๐ซ'
LetterQoph,
/// \u{10adf}: '๐ซ'
LetterXoph,
/// \u{10ae0}: '๐ซ '
LetterQhoph,
/// \u{10ae1}: '๐ซก'
LetterResh,
/// \u{10ae2}: '๐ซข'
LetterShin,
/// \u{10ae3}: '๐ซฃ'
LetterSshin,
/// \u{10ae4}: '๐ซค'
LetterTaw,
/// \u{10ae5}: '๐ซฅ'
AbbreviationMarkAbove,
/// \u{10ae6}: '๐ซฆ'
AbbreviationMarkBelow,
/// \u{10aeb}: '๐ซซ'
NumberOne,
/// \u{10aec}: '๐ซฌ'
NumberFive,
/// \u{10aed}: '๐ซญ'
NumberTen,
/// \u{10aee}: '๐ซฎ'
NumberTwenty,
/// \u{10aef}: '๐ซฏ'
NumberOneHundred,
/// \u{10af0}: '๐ซฐ'
PunctuationStar,
/// \u{10af1}: '๐ซฑ'
PunctuationFleuron,
/// \u{10af2}: '๐ซฒ'
PunctuationDoubleDotWithinDot,
/// \u{10af3}: '๐ซณ'
PunctuationDotWithinDot,
/// \u{10af4}: '๐ซด'
PunctuationDot,
/// \u{10af5}: '๐ซต'
PunctuationTwoDots,
/// \u{10af6}: '๐ซถ'
PunctuationLineFiller,
}
impl Into<char> for Manichaean {
fn into(self) -> char {
match self {
Manichaean::LetterAleph => '๐ซ',
Manichaean::LetterBeth => '๐ซ',
Manichaean::LetterBheth => '๐ซ',
Manichaean::LetterGimel => '๐ซ',
Manichaean::LetterGhimel => '๐ซ',
Manichaean::LetterDaleth => '๐ซ
',
Manichaean::LetterHe => '๐ซ',
Manichaean::LetterWaw => '๐ซ',
Manichaean::SignUd => '๐ซ',
Manichaean::LetterZayin => '๐ซ',
Manichaean::LetterZhayin => '๐ซ',
Manichaean::LetterJayin => '๐ซ',
Manichaean::LetterJhayin => '๐ซ',
Manichaean::LetterHeth => '๐ซ',
Manichaean::LetterTeth => '๐ซ',
Manichaean::LetterYodh => '๐ซ',
Manichaean::LetterKaph => '๐ซ',
Manichaean::LetterXaph => '๐ซ',
Manichaean::LetterKhaph => '๐ซ',
Manichaean::LetterLamedh => '๐ซ',
Manichaean::LetterDhamedh => '๐ซ',
Manichaean::LetterThamedh => '๐ซ',
Manichaean::LetterMem => '๐ซ',
Manichaean::LetterNun => '๐ซ',
Manichaean::LetterSamekh => '๐ซ',
Manichaean::LetterAyin => '๐ซ',
Manichaean::LetterAayin => '๐ซ',
Manichaean::LetterPe => '๐ซ',
Manichaean::LetterFe => '๐ซ',
Manichaean::LetterSadhe => '๐ซ',
Manichaean::LetterQoph => '๐ซ',
Manichaean::LetterXoph => '๐ซ',
Manichaean::LetterQhoph => '๐ซ ',
Manichaean::LetterResh => '๐ซก',
Manichaean::LetterShin => '๐ซข',
Manichaean::LetterSshin => '๐ซฃ',
Manichaean::LetterTaw => '๐ซค',
Manichaean::AbbreviationMarkAbove => '๐ซฅ',
Manichaean::AbbreviationMarkBelow => '๐ซฆ',
Manichaean::NumberOne => '๐ซซ',
Manichaean::NumberFive => '๐ซฌ',
Manichaean::NumberTen => '๐ซญ',
Manichaean::NumberTwenty => '๐ซฎ',
Manichaean::NumberOneHundred => '๐ซฏ',
Manichaean::PunctuationStar => '๐ซฐ',
Manichaean::PunctuationFleuron => '๐ซฑ',
Manichaean::PunctuationDoubleDotWithinDot => '๐ซฒ',
Manichaean::PunctuationDotWithinDot => '๐ซณ',
Manichaean::PunctuationDot => '๐ซด',
Manichaean::PunctuationTwoDots => '๐ซต',
Manichaean::PunctuationLineFiller => '๐ซถ',
}
}
}
impl std::convert::TryFrom<char> for Manichaean {
type Error = ();
fn try_from(c: char) -> Result<Self, Self::Error> {
match c {
'๐ซ' => Ok(Manichaean::LetterAleph),
'๐ซ' => Ok(Manichaean::LetterBeth),
'๐ซ' => Ok(Manichaean::LetterBheth),
'๐ซ' => Ok(Manichaean::LetterGimel),
'๐ซ' => Ok(Manichaean::LetterGhimel),
'๐ซ
' => Ok(Manichaean::LetterDaleth),
'๐ซ' => Ok(Manichaean::LetterHe),
'๐ซ' => Ok(Manichaean::LetterWaw),
'๐ซ' => Ok(Manichaean::SignUd),
'๐ซ' => Ok(Manichaean::LetterZayin),
'๐ซ' => Ok(Manichaean::LetterZhayin),
'๐ซ' => Ok(Manichaean::LetterJayin),
'๐ซ' => Ok(Manichaean::LetterJhayin),
'๐ซ' => Ok(Manichaean::LetterHeth),
'๐ซ' => Ok(Manichaean::LetterTeth),
'๐ซ' => Ok(Manichaean::LetterYodh),
'๐ซ' => Ok(Manichaean::LetterKaph),
'๐ซ' => Ok(Manichaean::LetterXaph),
'๐ซ' => Ok(Manichaean::LetterKhaph),
'๐ซ' => Ok(Manichaean::LetterLamedh),
'๐ซ' => Ok(Manichaean::LetterDhamedh),
'๐ซ' => Ok(Manichaean::LetterThamedh),
'๐ซ' => Ok(Manichaean::LetterMem),
'๐ซ' => Ok(Manichaean::LetterNun),
'๐ซ' => Ok(Manichaean::LetterSamekh),
'๐ซ' => Ok(Manichaean::LetterAyin),
'๐ซ' => Ok(Manichaean::LetterAayin),
'๐ซ' => Ok(Manichaean::LetterPe),
'๐ซ' => Ok(Manichaean::LetterFe),
'๐ซ' => Ok(Manichaean::LetterSadhe),
'๐ซ' => Ok(Manichaean::LetterQoph),
'๐ซ' => Ok(Manichaean::LetterXoph),
'๐ซ ' => Ok(Manichaean::LetterQhoph),
'๐ซก' => Ok(Manichaean::LetterResh),
'๐ซข' => Ok(Manichaean::LetterShin),
'๐ซฃ' => Ok(Manichaean::LetterSshin),
'๐ซค' => Ok(Manichaean::LetterTaw),
'๐ซฅ' => Ok(Manichaean::AbbreviationMarkAbove),
'๐ซฆ' => Ok(Manichaean::AbbreviationMarkBelow),
'๐ซซ' => Ok(Manichaean::NumberOne),
'๐ซฌ' => Ok(Manichaean::NumberFive),
'๐ซญ' => Ok(Manichaean::NumberTen),
'๐ซฎ' => Ok(Manichaean::NumberTwenty),
'๐ซฏ' => Ok(Manichaean::NumberOneHundred),
'๐ซฐ' => Ok(Manichaean::PunctuationStar),
'๐ซฑ' => Ok(Manichaean::PunctuationFleuron),
'๐ซฒ' => Ok(Manichaean::PunctuationDoubleDotWithinDot),
'๐ซณ' => Ok(Manichaean::PunctuationDotWithinDot),
'๐ซด' => Ok(Manichaean::PunctuationDot),
'๐ซต' => Ok(Manichaean::PunctuationTwoDots),
'๐ซถ' => Ok(Manichaean::PunctuationLineFiller),
_ => Err(()),
}
}
}
impl Into<u32> for Manichaean {
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 Manichaean {
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 Manichaean {
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 Manichaean {
/// The character with the lowest index in this unicode block
pub fn new() -> Self {
Manichaean::LetterAleph
}
/// The character's name, in sentence case
pub fn name(&self) -> String {
let s = std::format!("Manichaean{:#?}", self);
string_morph::to_sentence_case(&s)
}
}
|
use super::base::*;
use super::super::hw::HW;
impl CPU
{
pub fn io_inb(&mut self, port: u16, hw: &mut HW) -> u8
{
match port
{
0x60 =>
{
match hw.keyboard.io_get_scancode()
{
Some(scancode) => scancode,
None => 0x0
}
}
0x61 => hw.keyboard.get_ppi_a(),
0x3da =>
{
hw.display.get_status_reg()
}
0x3f8 => hw.com1.read_rtd(),
0x3f9 => hw.com1.read_ier(),
0x3fa => hw.com1.read_iir(),
0x3fb => hw.com1.read_lc(),
0x3fc => hw.com1.read_mc(),
0x3fd => hw.com1.read_lsr(),
_ =>
{
cpu_print!("Warning: byte input from unknown IO port {:04x}", port);
0x0
}
}
}
pub fn io_inw(&mut self, port: u16, _hw: &mut HW) -> u16
{
match port
{
_ =>
{
cpu_print!("Warning: word input from unknown IO port {:04x}", port);
0x0
}
}
}
pub fn io_outb(&mut self, port: u16, value: u8, hw: &mut HW)
{
match port
{
0x61 => hw.keyboard.set_ppi_a(value),
0x3f8 => hw.com1.write_rtd(value),
0x3f9 => hw.com1.write_ier(value),
0x3fb => hw.com1.write_lc(value),
0x3fc => hw.com1.write_mc(value),
_ =>
{
cpu_print!("Warning: byte output {:04x} to unknown IO port {:04x}", value, port);
}
}
}
pub fn io_outw(&mut self, port: u16, _value: u16, _hw: &mut HW)
{
match port
{
_ =>
{
cpu_print!("Warning: word output {:04x} to unknown IO port {:04x}", _value, port);
}
}
}
} |
// Copyright 2021 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under the MIT license <LICENSE-MIT
// https://opensource.org/licenses/MIT> or the Modified BSD license <LICENSE-BSD
// https://opensource.org/licenses/BSD-3-Clause>, at your option. This file may not be copied,
// modified, or distributed except according to those terms. Please review the Licences for the
// specific language governing permissions and limitations relating to use of the SAFE Network
// Software.
use super::metadata::Entries;
use super::metadata::{Address, Entry, Index, Perm};
use crate::Signature;
use crate::{utils, Error, PublicKey, Result};
pub use crdts::list::Op;
use crdts::{list::List, CmRDT};
use serde::{Deserialize, Serialize};
use std::{
fmt::{self, Debug, Display},
hash::Hash,
};
/// CRDT Data operation applicable to other Sequence replica.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CrdtOperation<A: Ord, T> {
/// Address of a Sequence object on the network.
pub address: Address,
/// The data operation to apply.
pub crdt_op: Op<T, A>,
/// The PublicKey of the entity that generated the operation
pub source: PublicKey,
/// The signature of source on the crdt_top, required to apply the op
pub signature: Option<Signature>,
}
/// Sequence data type as a CRDT with Access Control
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub struct SequenceCrdt<A: Ord, P> {
/// Actor of this piece of data
pub(crate) actor: A,
/// Address on the network of this piece of data
address: Address,
/// CRDT to store the actual data, i.e. the items of the Sequence.
data: List<Entry, A>,
/// The Policy matrix containing ownership and users permissions.
policy: P,
}
impl<A, P> Display for SequenceCrdt<A, P>
where
A: Ord + Clone + Display + Debug + Serialize,
P: Perm + Hash + Clone + Serialize,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[")?;
for (i, entry) in self.data.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
write!(f, "<{}>", String::from_utf8_lossy(&entry),)?;
}
write!(f, "]")
}
}
impl<A, P> SequenceCrdt<A, P>
where
A: Ord + Clone + Debug + Serialize,
P: Serialize,
{
/// Constructs a new 'SequenceCrdt'.
pub fn new(actor: A, address: Address, policy: P) -> Self {
Self {
actor,
address,
data: List::new(),
policy,
}
}
/// Returns the address.
pub fn address(&self) -> &Address {
&self.address
}
/// Returns the length of the sequence.
pub fn len(&self) -> u64 {
self.data.len() as u64
}
/// Create crdt op to append a new item to the SequenceCrdt
pub fn create_append_op(
&self,
entry: Entry,
source: PublicKey,
) -> Result<CrdtOperation<A, Entry>> {
let address = *self.address();
// Append the entry to the LSeq
let crdt_op = self.data.append(entry, self.actor.clone());
// We return the operation as it may need to be broadcasted to other replicas
Ok(CrdtOperation {
address,
crdt_op,
source,
signature: None,
})
}
/// Apply a remote data CRDT operation to this replica of the Sequence.
pub fn apply_op(&mut self, op: CrdtOperation<A, Entry>) -> Result<()> {
// Let's first check the op is validly signed.
// Note: Perms for the op are checked at the upper Sequence layer.
let sig = op.signature.ok_or(Error::CrdtMissingOpSignature)?;
let bytes_to_verify = utils::serialise(&op.crdt_op).map_err(|err| {
Error::Serialisation(format!(
"Could not serialise CRDT operation to verify signature: {}",
err
))
})?;
op.source.verify(&sig, &bytes_to_verify)?;
// Apply the CRDT operation to the LSeq data
self.data.apply(op.crdt_op);
Ok(())
}
/// Gets the entry at `index` if it exists.
pub fn get(&self, index: Index) -> Option<&Entry> {
let i = to_absolute_index(index, self.len() as usize)?;
self.data.position(i)
}
/// Gets the last entry.
pub fn last_entry(&self) -> Option<&Entry> {
self.data.last()
}
/// Gets the Policy of the object.
pub fn policy(&self) -> &P {
&self.policy
}
/// Gets a list of items which are within the given indices.
/// Note the range of items is [start, end), i.e. the end index is not inclusive.
pub fn in_range(&self, start: Index, end: Index) -> Option<Entries> {
let count = self.len() as usize;
let start_index = to_absolute_index(start, count)?;
if start_index >= count {
return None;
}
let end_index = to_absolute_index(end, count)?;
let items_to_take = end_index - start_index;
let entries = self
.data
.iter()
.skip(start_index)
.take(items_to_take)
.cloned()
.collect::<Entries>();
Some(entries)
}
}
// Private helpers
fn to_absolute_index(index: Index, count: usize) -> Option<usize> {
match index {
Index::FromStart(index) if (index as usize) <= count => Some(index as usize),
Index::FromStart(_) => None,
Index::FromEnd(index) => count.checked_sub(index as usize),
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.