text
stringlengths
8
4.13M
// Copyright 2020-Present (c) Raja Lehtihet & Wael El Oraiby // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // #![no_std] #![no_main] #[link(name="m")] extern "C" {} use rs_ctypes::*; use rs_glfw3::bindings::*; use rs_gles2::bindings::*; use rs_streams::*; use rs_alloc::*; use rs_math3d::*; mod renderer; mod objloader; mod gles2_renderer; use objloader::*; use renderer::*; use gles2_renderer::*; #[cfg(not(test))] #[panic_handler] fn alt_std_panic(_info: &core::panic::PanicInfo) -> ! { unsafe { libc::exit(1) } } static VERTEX_SHADER : &'static str = " attribute highp vec4 aPosition; attribute highp vec3 aNormal; uniform highp mat4 uPVM; varying highp vec3 vNormal; void main() { gl_Position = uPVM * aPosition; vNormal = aNormal; }\0"; static FRAGMENT_SHADER : &'static str = " precision mediump float; varying highp vec3 vNormal; void main() { gl_FragColor = vec4(vNormal.xyz, 1.0); }\0"; #[cfg(target_arch = "wasm32")] type EmArgCallbackFunc = extern "C" fn(*mut c_void); #[cfg(target_arch = "wasm32")] extern "C" { fn emscripten_set_main_loop_arg(func: EmArgCallbackFunc, arg: *mut c_void, fps: c_int, simulate_infinite_loop: c_int); } pub struct State { program : Option<Box<dyn Program>>, monkey_vb : StaticVertexBuffer, monkey_ib : StaticIndexBuffer, angle : f32, } struct Uniforms { pvm : Mat4f, } impl UniformBlock for Uniforms { fn descriptors() -> Vec<UniformDataDesc> { let mut v = Vec::new(); v.push(UniformDataDesc::new(String::from("uPVM"), UniformDataType::Float4x4, 0, 0)); v } } extern "C" fn main_loop(win_: *mut c_void) { unsafe { let win = win_ as *mut GLFWwindow; let state = glfwGetWindowUserPointer(win) as *mut State; let mut width = 0; let mut height = 0; glfwGetWindowSize(win, &mut width, &mut height); glViewport(0, 0, width, height); glScissor(0, 0, width, height); glClearColor(0.0, 0.0, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); glEnable(GL_DEPTH_TEST); let proj = rs_math3d::perspective(3.141516/4.0, width as f32 / height as f32, 1.0, 100.0); let view = rs_math3d::lookat(&Vec3f::new(0.0, 1.0, 5.0), &Vec3f::new(0.0, 0.0, 0.0), &Vec3f::new(0.0, 1.0, 0.0)); let model = Quatf::of_axis_angle(&Vec3f::new(0.0, 1.0, 0.0), (*state).angle); (*state).angle += 0.01; let u = Uniforms { pvm: proj * view * model.mat4() }; match &(*state).program { Some(p) => { glEnable(GL_CULL_FACE); draw_indexed(p, &(*state).monkey_vb, &(*state).monkey_ib, &u); }, None => () } glfwSwapBuffers(win); glfwPollEvents(); } } #[cfg(target_arch = "wasm32")] fn run_main_loop(win: *mut GLFWwindow) { unsafe { emscripten_set_main_loop_arg(main_loop, win as *mut c_void, 0, 1) }; } #[cfg(not(target_arch = "wasm32"))] fn run_main_loop(win: *mut GLFWwindow) { unsafe { while glfwWindowShouldClose(win) == GLFW_FALSE as c_int && glfwGetKey(win, GLFW_KEY_ESCAPE as c_int) == 0 { main_loop(win as *mut c_void); } } } #[link(name="c")] #[no_mangle] pub extern "C" fn main(_argc: isize, _argv: *const *const u8) -> isize { unsafe { if glfwInit() == GLFW_FALSE as c_int { return 1; } glfwWindowHint(GLFW_CONTEXT_CREATION_API as c_int, GLFW_EGL_CONTEXT_API as c_int); glfwWindowHint(GLFW_CLIENT_API as c_int, GLFW_OPENGL_ES_API as c_int); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR as c_int, 2); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR as c_int, 0); glfwWindowHint(GLFW_SAMPLES as c_int, 8); glfwWindowHint(GLFW_ALPHA_BITS as c_int, 0); let win = glfwCreateWindow(1024, 900, "App\0".as_bytes().as_ptr() as *const u8 as *const i8, core::ptr::null::<GLFWmonitor>() as *mut GLFWmonitor, core::ptr::null::<GLFWwindow>() as *mut GLFWwindow); glfwMakeContextCurrent(win); let attribs = [ VertexAttributeDesc::new(String::from("aPosition"), VertexFormat::Float3, 0), VertexAttributeDesc::new(String::from("aNormal"), VertexFormat::Float3, 12), ]; let uniforms = [ UniformDesc::new(String::from("uPVM"), UniformDataType::Float4x4, 0) ]; let program = GLProgram::load_program(&VERTEX_SHADER, &FRAGMENT_SHADER, &attribs, &uniforms); let m = match Mesh::read_obj("suzane.obj") { Ok(m) => { println!("verts : {}\nuvws : {}\ntris : {}\nquads : {}", m.verts().len(), m.uvws().len(), m.tris().len(), m.quads().len()); GPUMesh::from(&m) }, _ => panic!("Error reading file") }; let monkey_vb = StaticVertexBuffer::new(m.verts()); let monkey_ib = StaticIndexBuffer::new(m.tris()); let state = Box::new(State { program : program, monkey_vb: monkey_vb, monkey_ib: monkey_ib, angle: 0.0 }); glfwSetWindowUserPointer(win, state.as_ref() as *const State as *mut ::core::ffi::c_void); run_main_loop(win); glfwDestroyWindow(win); glfwTerminate(); } 0 }
pub mod linked_list { pub struct LinkedList { pub val: i32, } } pub fn testshit() { let x = linked_list::LinkedList { val: 10 }; }
#![allow(non_upper_case_globals)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(dead_code)] #![allow(unused_variables)] #![allow(unused_imports)] #![feature(const_transmute)] #[macro_use] extern crate bitflags; #[path = "util.rs"] pub mod util_; pub use ad_hoc_sys as sys; pub mod org { pub mod company { pub mod Client { use std::str; use std::mem::transmute; use crate::util_; /** *Device version reply */ pub mod DeviceVersion { use crate::org::company::Client as packs; use crate::sys; pub static meta_: &sys::Meta = unsafe { ::std::mem::transmute(&crate::util_::DeviceVersion) }; pub struct Pack_(pub *mut sys::Pack); impl Pack_ { pub fn data(&self) -> Data_ { Data_(unsafe { (*self.0).bytes.as_mut_ptr() }) } } pub struct Data_(pub *mut u8); impl Data_ { pub fn DevID(&mut self) -> u16 { let src = &mut self.0; let dst = sys::get_bytes(self.0, 0, 2 as usize) as u16; (dst) as u16 } pub fn Ver(&mut self) -> u16 { let src = &mut self.0; let dst = sys::get_bytes(self.0, 2, 2 as usize) as u16; (dst) as u16 } } pub fn push_<DST: DST_>(src: &mut Data_, dst: &mut DST) { dst.DevID(src.DevID()); dst.Ver(src.Ver()); } pub trait DST_ { fn DevID(&mut self, src: u16); fn Ver(&mut self, src: u16); } } /** *Stop device command * It's stop I2C sensors data request timer. Only listen PC commands */ pub mod Stop { use super::*; use crate::sys; pub static meta_: &sys::Meta = unsafe { transmute(&crate::util_::Stop) }; } /** *Prepare and start I2C sensors data request timer. */ pub mod Start { use super::*; use crate::sys; pub static meta_: &sys::Meta = unsafe { transmute(&crate::util_::Start) }; } /** *Device vertion request. */ pub mod GetDeviceVersion { use super::*; use crate::sys; pub static meta_: &sys::Meta = unsafe { transmute(&crate::util_::GetDeviceVersion) }; } /** *Request current device configuration, PC should be prepare receive two DeviceConfiguration packs * First pack - Sensors configuration * Second - Sensor Reading configuration */ pub mod GetConfiguration { use super::*; use crate::sys; pub static meta_: &sys::Meta = unsafe { transmute(&crate::util_::GetConfiguration) }; } /** *Set device configuration, PC will send two DeviceConfiguration packs * First pack - Sensors configuration * Second - Sensor Reading configuration */ pub mod SetConfiguration { use super::*; use crate::sys; pub static meta_: &sys::Meta = unsafe { transmute(&crate::util_::SetConfiguration) }; } /** *Device configuration. Sending from device as reply on PC request, sending from PC as new device configuration */ pub mod BusConfiguration { use crate::org::company::Client as packs; use crate::sys; pub static meta_: &sys::Meta = unsafe { ::std::mem::transmute(&crate::util_::BusConfiguration) }; pub struct Pack_(pub *mut sys::Pack); impl Pack_ { pub fn data(&self) -> Data_ { Data_(unsafe { (*self.0).bytes.as_mut_ptr() }) } } pub struct Data_(pub *mut u8); impl Data_ { pub fn multiplier(&mut self) -> crate::util_::Item_V { crate::util_::Item_V(self.0) } pub fn time(&mut self) -> crate::util_::Item_f { crate::util_::Item_f(self.0) } pub fn clk_khz(&mut self) -> crate::util_::Item_l { crate::util_::Item_l(self.0) } } impl crate::org::company::Communication::ITransmittable::Pack for Pack_ { fn pack(self) -> *mut sys::Pack { self.0 } } pub fn push_<DST: DST_>(src: &mut Data_, dst: &mut DST) { dst.multiplier(src.multiplier().get()); dst.time(src.time().get()); dst.clk_khz(src.clk_khz().get()); } pub trait DST_ { fn multiplier(&mut self, src: u8); fn time(&mut self, src: u16); fn clk_khz(&mut self, src: u16); } pub trait SRC_ { fn multiplier(&mut self) -> u8; fn time(&mut self) -> u16; fn clk_khz(&mut self) -> u16; } pub fn pull_<SRC: SRC_>(src: &mut SRC, dst: &mut Data_) { dst.multiplier().set(src.multiplier()); dst.time().set(src.time()); dst.clk_khz().set(src.clk_khz()); } } /** *Mini assembler instructions buffer starts with a * RW-instruction byte, it switch device in the Read/Write mode and hold the number of Readings/Writings I2C Bus. * . * every Read instruction consume 2 bytes * address * register * . * every Write instruction consume 4 bytes * address * writing_value - 2 bytes * register * . * so InstructionsPack can hold maximum 127 Readings or 64 Writings * . * if RW- < 128 - it contains number of rest Readings from I2C * if 128 < RW - it contains (RW - 128) number of rest Writings into I2C * . * If this pack is not following after RequestConfiguration: * . * if it contains read Sensor data instructions * it will be proceeded many times until fill all SensorsData, and then SensorsData send * . * if it contains any write Sensors registers instructions * it will be proceeded only once */ pub mod InstructionsPack { use crate::org::company::Client as packs; use crate::sys; pub static meta_: &sys::Meta = unsafe { ::std::mem::transmute(&crate::util_::InstructionsPack) }; pub struct Pack_(pub *mut sys::Pack); impl Pack_ { pub fn data(&self) -> Data_ { Data_(unsafe { (*self.0).bytes.as_mut_ptr() }) } } pub struct Data_(pub *mut u8); impl Data_ { pub fn Length(&mut self) -> crate::util_::Item_A { crate::util_::Item_A(self.0) } pub fn Instructions(&mut self, src: Option<&mut dyn Iterator<Item = u8>>) -> crate::util_::ItemArray_C { let dst = self.0; let len = 256 as usize; let offset = 1; let bytes = dst; let mut array = crate::util_::ItemArray_C { bytes, len, offset, index: !0 }; if let Some(src) = src { for i in 0..len { if let Some(val) = src.next() { array.set(i, val); } else { break; } } } array } } impl crate::org::company::Communication::ITransmittable::Pack for Pack_ { fn pack(self) -> *mut sys::Pack { self.0 } } pub fn push_<DST: DST_>(src: &mut Data_, dst: &mut DST) { dst.Length(src.Length().get()); dst.Instructions(&mut src.Instructions(None)); } pub trait DST_ { fn Length(&mut self, src: u8); fn Instructions(&mut self, src: &mut crate::util_::ItemArray_C); } pub trait SRC_ { fn Length(&mut self) -> u8; fn Instructions(&mut self, dst: &mut crate::util_::ItemArray_C); } pub fn pull_<SRC: SRC_>(src: &mut SRC, dst: &mut Data_) { dst.Length().set(src.Length()); src.Instructions(&mut dst.Instructions(None)); } pub mod Instructions { pub const len: usize = 256usize; } pub const RW_mode: i16 = 128i16; //128 } /** *Device Error information */ pub mod DeviceError { use crate::org::company::Client as packs; use crate::sys; pub static meta_: &sys::Meta = unsafe { ::std::mem::transmute(&crate::util_::DeviceError) }; pub struct Pack_(pub *mut sys::Pack); impl Pack_ { pub fn data(&self) -> Data_ { Data_(unsafe { (*self.0).bytes.as_mut_ptr() }) } } pub struct Data_(pub *mut u8); impl Data_ { pub fn param1(&mut self) -> u16 { let src = &mut self.0; let dst = sys::get_bytes(self.0, 0, 2 as usize) as u16; (dst) as u16 } pub fn error_id(&mut self) -> packs::Errors { let src = &mut self.0; packs::Errors::from_bits((sys::get_bits(self.0, 16, 1)) as i8).unwrap() } } pub fn push_<DST: DST_>(src: &mut Data_, dst: &mut DST) { dst.param1(src.param1()); dst.error_id(src.error_id()); } pub trait DST_ { fn param1(&mut self, src: u16); fn error_id(&mut self, src: packs::Errors); } } /** *Bulk sensors data. Sequentially ordered by address sensors data reading */ pub mod SensorsData { use crate::org::company::Client as packs; use crate::sys; pub static meta_: &sys::Meta = unsafe { ::std::mem::transmute(&crate::util_::SensorsData) }; pub struct Pack_(pub *mut sys::Pack); impl Pack_ { pub fn data(&self) -> Data_ { Data_(unsafe { (*self.0).bytes.as_mut_ptr() }) } } pub struct Data_(pub *mut u8); impl Data_ { pub fn values(&mut self) -> crate::util_::ItemArray_Z { let src = self.0; let len = 1000 as usize; let offset = 0; let bytes = src; crate::util_::ItemArray_Z { bytes, len, offset, index: !0 } } } pub fn push_<DST: DST_>(src: &mut Data_, dst: &mut DST) { dst.values(&mut src.values()); } pub trait DST_ { fn values(&mut self, src: &mut crate::util_::ItemArray_Z); } pub mod values { pub const len: usize = 1000usize; } } #[derive(PartialEq, Debug)] #[repr(i8)] pub enum Errors { SensorsDataOverflow = 0, CannotReadSensor = 1, } impl Errors { pub fn from_bits(src: i8) -> Option<Errors> { match src { 0 => Some(Errors::SensorsDataOverflow), 1 => Some(Errors::CannotReadSensor), _ => None, } } pub fn bits(self) -> i8 { self as i8 } } } pub mod Communication { use crate::org::company::Client as packs; use crate::sys; use std::mem::transmute; pub trait IReceiver { /** * Getting reference to customer receiver by reference to sys::Receiver inside it. Mostly used self_by_field_ptr! macros **/ unsafe fn into_self<'a>(receiver: *mut sys::Receiver) -> &'a mut Self; /** * Get internal sys::Receiver from Customer receiver **/ fn get_receiver(&mut self) -> &mut sys::Receiver; /** * Received packs handler functions **/ fn on_DeviceVersion(&mut self, pack: *mut sys::Pack); fn on_BusConfiguration(&mut self, pack: *mut sys::Pack); fn on_InstructionsPack(&mut self, pack: *mut sys::Pack); fn on_DeviceError(&mut self, pack: *mut sys::Pack); fn on_SensorsData(&mut self, pack: *mut sys::Pack); /** * Translate received byte(s) into pack(s) **/ #[inline(always)] fn bytes_into_packs(&mut self, src: &[u8]) -> Result<usize, ::std::io::Error> { unsafe { sys::receive(src.as_ptr(), src.len(), self.get_receiver()); } Ok(src.len() as usize) } /** *Convenient sys::Receiver constructor **/ fn new() -> sys::Receiver { sys::Receiver::new(Self::dispatch) } /** *Received packs to packs handler functions dispatcher **/ unsafe extern "C" fn dispatch(receiver: *mut sys::Receiver, id: usize, pack: *mut sys::Pack) -> *const sys::Meta { let self_ = Self::into_self(receiver); match id { 0 => { if pack.is_null() { return packs::DeviceVersion::meta_; } Self::on_DeviceVersion(self_, pack); } 6 => { if pack.is_null() { return packs::BusConfiguration::meta_; } Self::on_BusConfiguration(self_, pack); } 7 => { if pack.is_null() { return packs::InstructionsPack::meta_; } Self::on_InstructionsPack(self_, pack); } 8 => { if pack.is_null() { return packs::DeviceError::meta_; } Self::on_DeviceError(self_, pack); } 9 => { if pack.is_null() { return packs::SensorsData::meta_; } Self::on_SensorsData(self_, pack); } _ => panic!("unknown ID"), } ::std::ptr::null_mut() } } pub trait ITransmitter { /** *Function that fetch next pack from sending queue to send it **/ unsafe extern "C" fn dequeue(dst: *mut sys::Transmitter) -> *const sys::Pack; /** *Add pack to the sending queue **/ fn queue(&mut self, pack: *mut sys::Pack) -> Result<(), *mut sys::Pack>; /** * Get reference to transmitter by customer transmitter **/ fn get_transmitter(&mut self) -> &mut sys::Transmitter; #[inline(always)] fn send_Stop(&mut self) -> bool { self.queue(sys::Pack::new(packs::Stop::meta_)).is_ok() } #[inline(always)] fn send_Start(&mut self) -> bool { self.queue(sys::Pack::new(packs::Start::meta_)).is_ok() } #[inline(always)] fn send_GetDeviceVersion(&mut self) -> bool { self.queue(sys::Pack::new(packs::GetDeviceVersion::meta_)).is_ok() } #[inline(always)] fn send_GetConfiguration(&mut self) -> bool { self.queue(sys::Pack::new(packs::GetConfiguration::meta_)).is_ok() } #[inline(always)] fn send_SetConfiguration(&mut self) -> bool { self.queue(sys::Pack::new(packs::SetConfiguration::meta_)).is_ok() } fn send<SRC: ITransmittable::Pack>(&mut self, src: SRC) -> Result<(), *mut sys::Pack> { self.queue(src.pack()) } /** *Request to translate packs in sending queue into provided bytes buffer **/ #[inline(always)] fn packs_into_bytes(&mut self, dst: &mut [u8]) -> Result<usize, ::std::io::Error> { unsafe { Ok(sys::transmit(self.get_transmitter(), dst.as_mut_ptr(), dst.len()) as usize) } } fn new() -> sys::Transmitter { sys::Transmitter::new(Self::dequeue) } } pub mod ITransmittable { use crate::org::company::Client as packs; use crate::sys; /** *Device configuration. Sending from device as reply on PC request, sending from PC as new device configuration */ pub fn BusConfiguration() -> packs::BusConfiguration::Pack_ { packs::BusConfiguration::Pack_(sys::Pack::new(packs::BusConfiguration::meta_)) } /** *Mini assembler instructions buffer starts with a * RW-instruction byte, it switch device in the Read/Write mode and hold the number of Readings/Writings I2C Bus. * . * every Read instruction consume 2 bytes * address * register * . * every Write instruction consume 4 bytes * address * writing_value - 2 bytes * register * . * so InstructionsPack can hold maximum 127 Readings or 64 Writings * . * if RW- < 128 - it contains number of rest Readings from I2C * if 128 < RW - it contains (RW - 128) number of rest Writings into I2C * . * If this pack is not following after RequestConfiguration: * . * if it contains read Sensor data instructions * it will be proceeded many times until fill all SensorsData, and then SensorsData send * . * if it contains any write Sensors registers instructions * it will be proceeded only once */ pub fn InstructionsPack() -> packs::InstructionsPack::Pack_ { packs::InstructionsPack::Pack_(sys::Pack::new(packs::InstructionsPack::meta_)) } pub trait Pack { fn pack(self) -> *mut sys::Pack; } } } } }
use async_net::{TcpListener, TcpStream}; use futures_lite::prelude::*; use trillium_http::{Conn, Stopper}; async fn handler(mut conn: Conn<TcpStream>) -> Conn<TcpStream> { let mut body = conn.request_body().await; while let Some(chunk) = body.next().await { log::info!("< {}", String::from_utf8(chunk).unwrap()); } conn.set_response_body("Hello world"); conn.response_headers().insert("Content-type", "text/plain"); conn.set_status(200); conn } pub fn main() { env_logger::init(); smol::block_on(async move { let stopper = Stopper::new(); let listener = TcpListener::bind("127.0.0.1:8081").await.unwrap(); let mut incoming = stopper.stop_stream(listener.incoming()); while let Some(Ok(stream)) = incoming.next().await { let stopper = stopper.clone(); smol::spawn(async move { match Conn::map(stream, stopper, handler).await { Ok(Some(_)) => log::info!("upgrade"), Ok(None) => log::info!("closing connection"), Err(e) => log::error!("{:?}", e), } }) .detach() } }); }
/* * 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 */ /// IntakePayloadAccepted : The payload accepted for intake. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IntakePayloadAccepted { /// The status of the intake payload. #[serde(rename = "status", skip_serializing_if = "Option::is_none")] pub status: Option<String>, } impl IntakePayloadAccepted { /// The payload accepted for intake. pub fn new() -> IntakePayloadAccepted { IntakePayloadAccepted { status: None, } } }
#[doc = "Register `SECWM2R1` reader"] pub type R = crate::R<SECWM2R1_SPEC>; #[doc = "Register `SECWM2R1` writer"] pub type W = crate::W<SECWM2R1_SPEC>; #[doc = "Field `SECWM2_PSTRT` reader - SECWM2_PSTRT"] pub type SECWM2_PSTRT_R = crate::FieldReader; #[doc = "Field `SECWM2_PSTRT` writer - SECWM2_PSTRT"] pub type SECWM2_PSTRT_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 7, O>; #[doc = "Field `SECWM2_PEND` reader - SECWM2_PEND"] pub type SECWM2_PEND_R = crate::FieldReader; #[doc = "Field `SECWM2_PEND` writer - SECWM2_PEND"] pub type SECWM2_PEND_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 7, O>; impl R { #[doc = "Bits 0:6 - SECWM2_PSTRT"] #[inline(always)] pub fn secwm2_pstrt(&self) -> SECWM2_PSTRT_R { SECWM2_PSTRT_R::new((self.bits & 0x7f) as u8) } #[doc = "Bits 16:22 - SECWM2_PEND"] #[inline(always)] pub fn secwm2_pend(&self) -> SECWM2_PEND_R { SECWM2_PEND_R::new(((self.bits >> 16) & 0x7f) as u8) } } impl W { #[doc = "Bits 0:6 - SECWM2_PSTRT"] #[inline(always)] #[must_use] pub fn secwm2_pstrt(&mut self) -> SECWM2_PSTRT_W<SECWM2R1_SPEC, 0> { SECWM2_PSTRT_W::new(self) } #[doc = "Bits 16:22 - SECWM2_PEND"] #[inline(always)] #[must_use] pub fn secwm2_pend(&mut self) -> SECWM2_PEND_W<SECWM2R1_SPEC, 16> { SECWM2_PEND_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 = "Flash secure watermak2 register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`secwm2r1::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 [`secwm2r1::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct SECWM2R1_SPEC; impl crate::RegisterSpec for SECWM2R1_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`secwm2r1::R`](R) reader structure"] impl crate::Readable for SECWM2R1_SPEC {} #[doc = "`write(|w| ..)` method takes [`secwm2r1::W`](W) writer structure"] impl crate::Writable for SECWM2R1_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets SECWM2R1 to value 0xff00_ff00"] impl crate::Resettable for SECWM2R1_SPEC { const RESET_VALUE: Self::Ux = 0xff00_ff00; }
use core::prelude::*; use num::div_rem; use int2dec::digits::{Digits64, Digits32, Digits16, Digits8}; use int2dec::digits::{NDIGITS64, NDIGITS32, NDIGITS16, NDIGITS8}; pub fn u64_to_digits(mut n: u64) -> Digits64 { let mut buf: Digits64 = [b'0'; NDIGITS64]; for i in (0..NDIGITS64).rev() { if n == 0 { return buf; } let (q, r) = div_rem(n, 10); buf[i] = r as u8 + b'0'; n = q; } buf } pub fn u32_to_digits(mut n: u32) -> Digits32 { let mut buf: Digits32 = [b'0'; NDIGITS32]; for i in (0..NDIGITS32).rev() { if n == 0 { return buf; } let (q, r) = div_rem(n, 10); buf[i] = r as u8 + b'0'; n = q; } buf } pub fn u16_to_digits(mut n: u16) -> Digits16 { let mut buf: Digits16 = [b'0'; NDIGITS16]; for i in (0..NDIGITS16).rev() { if n == 0 { return buf; } let (q, r) = div_rem(n, 10); buf[i] = r as u8 + b'0'; n = q; } buf } pub fn u8_to_digits(mut n: u8) -> Digits8 { let mut buf: Digits8 = [b'0'; NDIGITS8]; for i in (0..NDIGITS8).rev() { if n == 0 { return buf; } let (q, r) = div_rem(n, 10); buf[i] = r as u8 + b'0'; n = q; } buf }
// Des fonctions peuvent transférer l'ownership, le prendre, le rendre fn main() { // Une fonction peut donner l'ownership let s1 = donne_ownership(); // la fonction déplace sa valeur retour dans s1. // s1 est valide dans le scope actuel // Créons une variable dans le scope. Elle sera déplacée par prend_et_rend() let s2 = String::from("Autre chaine de caractères."); // Une fonction peut prendre et rendre l'ownership let s3 = prend_et_rend(s2); // s2 est déplacée vers prend_et_rend() // la valeur est retournée à s3 // s2 est invalide maintenant // Afficher les résultats println!("s1: {}, s3 : {}", s1, s3); } // on sort du scope, toutes les variables sont lâchées (dropped) fn donne_ownership() -> String { // cette fonction déplacera sa valeur // de retour vers la fonction qui l'appelle. let une_chaine = String::from("Hello"); // la variable une_chaine rentre le // scope. une_chaine // renvoie la variable à la fonction qui a appelé donne_ownership() } fn prend_et_rend(autre_chaine: String) -> String { // définir input et output // autre_chaine rentre en scope autre_chaine // la variable est retournée à la fonction appelante }
use std::collections::{BTreeMap}; use std::env; use std::fs; #[derive(Clone, Eq, PartialEq)] struct ChemicalAmount { name: String, quantity: u32, } impl ChemicalAmount { fn parse(s: &str) -> Result<ChemicalAmount, String> { let parts: Vec<&str> = s.trim().split_whitespace().collect(); if parts.len() == 2 { let quantity: u32 = parts[0].parse() .map_err(|_| format!("Couldn't parse quantity: '{}'", parts[0]))?; Ok(Self { name: parts[1].trim().to_string(), quantity }) } else { Err(format!("Failed to parse chemical amount: '{}'", s)) } } fn as_string(&self) -> String { format!("{} {}", self.quantity, self.name) } } impl std::fmt::Debug for ChemicalAmount { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.as_string()) } } #[test] fn test_chemicalamount_parse() { assert_eq!(ChemicalAmount::parse("10 abc"), Ok(ChemicalAmount { name: "abc".to_string(), quantity: 10 })); } #[derive(Clone, Eq, PartialEq)] struct Reaction { inputs: Vec<ChemicalAmount>, output: ChemicalAmount, } impl Reaction { fn parse_line(line: &str) -> Result<Reaction, String> { let i = line.find("=>").ok_or(format!("Invalid reaction: '{}'", line))?; let (left, right) = line.split_at(i); let right = &right[2..]; let output = ChemicalAmount::parse(right)?; let inputs = left.split(',').map(ChemicalAmount::parse).collect::<Result<Vec<ChemicalAmount>, String>>()?; Ok(Self { inputs, output }) } fn as_string(&self) -> String { let input_str = self.inputs.iter().map(|i| i.as_string()).collect::<Vec<String>>().join(", "); format!("<{} => {}>", input_str, self.output.as_string()) } } impl std::fmt::Debug for Reaction { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.as_string()) } } #[test] fn test_reaction_parse_line() { assert_eq!( Reaction::parse_line("10 A => 1 B"), Ok(Reaction { inputs: vec!( ChemicalAmount { name: "A".to_string(), quantity: 10 } ), output: ChemicalAmount { name: "B".to_string(), quantity: 1 } }) ); } fn main() -> Result<(), String> { let input_path: &str = &env::args().nth(1).unwrap(); let reactions = fs::read_to_string(input_path) .map_err(|_| "Error reading input file".to_string())? .lines() .map(Reaction::parse_line) .collect::<Result<Vec<Reaction>, String>>()?; part1(&reactions); part2(&reactions); Ok(()) } fn part1(reactions: &[Reaction]) { println!("Part 1: {}", compute_ore_cost(reactions, 1)); } fn get_multiple(num: u64, denom: u64) -> u64 { let q = num / denom; let r = num % denom; if r == 0 { q } else { q + 1 } } struct ReactionCount<'a> { reaction: &'a Reaction, count: u64, } fn find_missing_requirements<'a>(reaction_counts: &[ReactionCount<'a>]) -> BTreeMap<&'a str, i64> { let mut result: BTreeMap<&str, i64> = BTreeMap::new(); for rc in reaction_counts.iter() { for input in rc.reaction.inputs.iter() { let consumed_quantity = (input.quantity as u64 * rc.count) as i64; let quantity = result.entry(&input.name).or_insert(0); *quantity -= consumed_quantity; } let output = &rc.reaction.output; let produced_quantity = (output.quantity as u64 * rc.count) as i64; let quantity = result.entry(&output.name).or_insert(0); *quantity += produced_quantity; } result.into_iter().filter(|(_, v)| *v < 0).map(|(k, v)| (k, -v)).collect() } fn compute_ore_cost(reactions: &[Reaction], needed_fuel: u64) -> u64 { let mut reaction_counts: Vec<ReactionCount> = reactions.iter().map(|r| ReactionCount { reaction: r, count: 0 }).collect(); for rc in reaction_counts.iter_mut() { if rc.reaction.output.name == "FUEL" { rc.count = needed_fuel; } } let mut missing_requirements = find_missing_requirements(&reaction_counts); let mut max_iterations = 10000; while missing_requirements.len() > 1 || !missing_requirements.contains_key("ORE") { let (missing_chemical, needed_count) = missing_requirements.iter().filter(|(chemical, _)| **chemical != "ORE").nth(0).unwrap(); for rc in reaction_counts.iter_mut() { if rc.reaction.output.name == *missing_chemical { let multiple = get_multiple(*needed_count as u64, rc.reaction.output.quantity as u64); rc.count += multiple; } } let new_missing_requirements = find_missing_requirements(&reaction_counts); if new_missing_requirements == missing_requirements { dbg!(missing_chemical); dbg!(needed_count); panic!("Not making progress"); } missing_requirements = new_missing_requirements; max_iterations -= 1; if max_iterations == 0 { panic!("Too many iterations"); } } missing_requirements["ORE"] as u64 } #[test] fn test_case_0() { let reactions = vec!( Reaction::parse_line("2 ORE => 1 A").unwrap(), Reaction::parse_line("2 A => 1 FUEL").unwrap(), ); assert_eq!(4, compute_ore_cost(&reactions[..], 1)); } #[test] fn test_case_1() { let reactions = vec!( Reaction::parse_line("10 ORE => 10 A").unwrap(), Reaction::parse_line("1 ORE => 1 B").unwrap(), Reaction::parse_line("7 A, 1 B => 1 C").unwrap(), Reaction::parse_line("7 A, 1 C => 1 D").unwrap(), Reaction::parse_line("7 A, 1 D => 1 E").unwrap(), Reaction::parse_line("7 A, 1 E => 1 FUEL").unwrap() ); assert_eq!(31, compute_ore_cost(&reactions[..], 1)); } #[test] fn test_case_2() { let reactions = vec!( Reaction::parse_line("9 ORE => 2 A").unwrap(), Reaction::parse_line("8 ORE => 3 B").unwrap(), Reaction::parse_line("7 ORE => 5 C").unwrap(), Reaction::parse_line("3 A, 4 B => 1 AB").unwrap(), Reaction::parse_line("5 B, 7 C => 1 BC").unwrap(), Reaction::parse_line("4 C, 1 A => 1 CA").unwrap(), Reaction::parse_line("2 AB, 3 BC, 4 CA => 1 FUEL").unwrap(), ); assert_eq!(165, compute_ore_cost(&reactions[..], 1)); } fn part2(reactions: &[Reaction]) { let available_ore: u64 = 1_000_000_000_000; let mut lower_bound = 1; let mut upper_bound = 1_000_000_000; assert!(compute_ore_cost(reactions, upper_bound) > available_ore); while (upper_bound - lower_bound) > 1 { let mid = (upper_bound + lower_bound) / 2; let ore_cost = compute_ore_cost(reactions, mid); if ore_cost > available_ore { upper_bound = mid; } else { lower_bound = mid; } } println!("Part 2: {}", lower_bound); }
//! //! A micro Web framework based on Hyper, Futures and Tokio. //! //! ## WARNING //! This project is not production ready. //! #[doc(hidden)] pub extern crate futures; #[doc(hidden)] pub extern crate hyper; extern crate regex; extern crate tokio_core; #[doc(hidden)] pub extern crate typemap; extern crate unsafe_any; pub mod context; pub mod middleware; pub mod response; pub mod router; pub mod server; pub mod contrib { pub use futures; pub use hyper; pub use typemap; } #[doc(inline)] pub use context::Context; #[doc(inline)] pub use middleware::{Middleware, MiddlewareStack}; #[doc(inline)] pub use response::{Response, Failure, AsyncResult}; #[doc(inline)] pub use server::Server;
pub mod box_demo; pub mod deref_demo; pub mod drop_demo;
use crate::utils::{fill_read_buf, make_io_error}; use bytes::BytesMut; use futures::stream::{SplitSink, SplitStream}; use futures::{Future, SinkExt, Stream}; use std::error::Error; use std::pin::Pin; use std::task::{Context, Poll}; use tokio::io::{AsyncRead, AsyncWrite}; use tokio_tungstenite::WebSocketStream; use tungstenite::protocol::Message; pub struct WebsocketReader<S> { stream: SplitStream<WebSocketStream<S>>, recv_buf: BytesMut, } impl<S> AsyncRead for WebsocketReader<S> where S: AsyncRead + AsyncWrite + Unpin, { fn poll_read( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8], ) -> Poll<std::io::Result<usize>> { let Self { stream, recv_buf } = &mut *self; if !recv_buf.is_empty() { let n = fill_read_buf(recv_buf, buf); return Poll::Ready(Ok(n)); } recv_buf.clear(); pin_mut!(stream); match stream.poll_next(cx) { Poll::Ready(Some(msg)) => { let m = match msg { Ok(m) => m, Err(e) => { return Poll::Ready(Err(make_io_error(&e.to_string()))); } }; if !m.is_binary() { return Poll::Ready(Err(make_io_error("invalid msg type"))); } let data = m.into_data(); let mut copy_n = data.len(); if 0 == copy_n { //close return Poll::Ready(Ok(0)); } if copy_n > buf.len() { copy_n = buf.len(); } // //info!("[{}]tx ready {} ", state.stream_id, copy_n); buf[0..copy_n].copy_from_slice(&data[0..copy_n]); if copy_n < data.len() { recv_buf.extend_from_slice(&data[copy_n..]); } Poll::Ready(Ok(copy_n)) } Poll::Ready(None) => { //state.close(); //rx.close(); Poll::Ready(Ok(0)) } Poll::Pending => Poll::Pending, } } } impl<S> WebsocketReader<S> where S: AsyncRead + AsyncWrite + Unpin, { pub fn new(stream: SplitStream<WebSocketStream<S>>) -> Self { Self { stream, recv_buf: BytesMut::new(), } } } pub struct WebsocketWriter<S> { sink: SplitSink<WebSocketStream<S>, Message>, } impl<S> AsyncWrite for WebsocketWriter<S> where S: AsyncRead + AsyncWrite + Unpin, { fn poll_write( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8], ) -> Poll<Result<usize, std::io::Error>> { let Self { sink } = &mut *self; let blen = buf.len(); let msg = Message::binary(buf); let future = sink.send(msg); pin_mut!(future); match future.as_mut().poll(cx) { Poll::Pending => Poll::Pending, Poll::Ready(Err(e)) => Poll::Ready(Err(make_io_error(&e.to_string()))), Poll::Ready(Ok(())) => Poll::Ready(Ok(blen)), } } fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), std::io::Error>> { Poll::Ready(Ok(())) } fn poll_shutdown( mut self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Result<(), std::io::Error>> { let Self { sink } = &mut *self; let future = sink.close(); pin_mut!(future); match future.as_mut().poll(cx) { Poll::Pending => Poll::Pending, Poll::Ready(Err(e)) => Poll::Ready(Err(make_io_error(&e.to_string()))), Poll::Ready(Ok(())) => Poll::Ready(Ok(())), } } } impl<S> WebsocketWriter<S> where S: AsyncRead + AsyncWrite + Unpin, { pub fn new(sink: SplitSink<WebSocketStream<S>, Message>) -> Self { Self { sink } } }
use crate::{ lua_simple_enum::{LuaAlignment, LuaLinkType}, lua_tag::LuaTag, }; use pulldown_cmark::{CodeBlockKind, CowStr, Tag}; #[derive(Debug, Clone, Copy)] pub struct LuaTagModule; impl mlua::UserData for LuaTagModule { fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(methods: &mut M) { methods.add_method("paragraph", |_, _, ()| -> mlua::Result<LuaTag> { Ok(LuaTag(Tag::Paragraph)) }); methods.add_method("heading", |_, _, n: u32| -> mlua::Result<LuaTag> { Ok(LuaTag(Tag::Heading(n))) }); methods.add_method("indented_code_block", |_, _, ()| -> mlua::Result<LuaTag> { Ok(LuaTag(Tag::CodeBlock(CodeBlockKind::Indented))) }); methods.add_method("fenced_code_block", |_, _, info: String| -> mlua::Result<LuaTag> { Ok(LuaTag(Tag::CodeBlock(CodeBlockKind::Fenced(CowStr::Boxed(info.into_boxed_str()))))) }); methods.add_method("ordered_list", |_, _, start: u64| -> mlua::Result<LuaTag> { Ok(LuaTag(Tag::List(Some(start)))) }); methods.add_method("unordered_list", |_, _, ()| -> mlua::Result<LuaTag> { Ok(LuaTag(Tag::List(None))) }); methods.add_method("footnote_definition", |_, _, def: String| -> mlua::Result<LuaTag> { Ok(LuaTag(Tag::FootnoteDefinition(CowStr::Boxed(def.into_boxed_str())))) }); methods.add_method( "table", |_, _, alignments: Vec<LuaAlignment>| -> mlua::Result<LuaTag> { Ok(LuaTag(Tag::Table(alignments.into_iter().map(|x| x.0).collect()))) }, ); methods.add_method("table_head", |_, _, ()| -> mlua::Result<LuaTag> { Ok(LuaTag(Tag::TableHead)) }); methods.add_method("table_row", |_, _, ()| -> mlua::Result<LuaTag> { Ok(LuaTag(Tag::TableRow)) }); methods.add_method("table_cell", |_, _, ()| -> mlua::Result<LuaTag> { Ok(LuaTag(Tag::TableCell)) }); methods.add_method("emphasis", |_, _, ()| -> mlua::Result<LuaTag> { Ok(LuaTag(Tag::Emphasis)) }); methods .add_method("strong", |_, _, ()| -> mlua::Result<LuaTag> { Ok(LuaTag(Tag::Strong)) }); methods.add_method("strikethrough", |_, _, ()| -> mlua::Result<LuaTag> { Ok(LuaTag(Tag::Strikethrough)) }); methods.add_method( "link", |_, _, (link_type, destination, title): (LuaLinkType, String, String)| -> mlua::Result<LuaTag> { Ok(LuaTag(Tag::Link( link_type.0, CowStr::Boxed(destination.into_boxed_str()), CowStr::Boxed(title.into_boxed_str()), ))) }, ); methods.add_method( "image", |_, _, (link_type, destination, title): (LuaLinkType, String, String)| -> mlua::Result<LuaTag> { Ok(LuaTag(Tag::Image( link_type.0, CowStr::Boxed(destination.into_boxed_str()), CowStr::Boxed(title.into_boxed_str()), ))) }, ); } }
extern crate image; extern crate time; use std::path::Path; use std::thread; use vector::*; use objects::*; mod lighting; pub type Image = image::RgbImage; pub fn write_image(image: Image, filename: &str) { let _ = image.save(&Path::new(filename)); } pub fn raytrace(scene: &Scene, width: u32, height: u32, h_fov: f64) { let start_time = time::precise_time_ns(); let f_width = width as f64; let f_height = height as f64; let v_fov = h_fov * (f_height / f_width); let vw_per_pixel = 2.0 * (h_fov / 2.0).tan() / f_width; let vh_per_pixel = 2.0 * (v_fov / 2.0).tan() / f_height; let norm_up = scene.camera.up.normalized(); let norm_right = scene.camera.direction.cross(scene.camera.up).normalized(); let tracer = move |row_start, num_rows, scene: Scene| { move || { let mut subimage = image::RgbImage::new(width, num_rows); let mut rays = 0; for (x, y, pixel) in subimage.enumerate_pixels_mut() { let y = y + row_start; let cast_ray = |dx: f64, dy: f64, rays: &mut u64| { *rays += 1; let fi = (x as f64) + dx; let fj = (y as f64) + dy; let u_rel = vw_per_pixel * (fi - (f_width / 2.0)); let v_rel = vh_per_pixel * (fj - (f_height / 2.0)); let pixel_loc = scene.camera.position + scene.camera.direction + (norm_right * u_rel) + (norm_up * v_rel); let ray = Ray { origin: scene.camera.position, direction: pixel_loc - scene.camera.position }; let (color, new_rays) = lighting::get_color(&scene, &ray, 3); *rays += new_rays; color }; let c1 = cast_ray(0.25, 0.25, &mut rays); let c2 = cast_ray(0.75, 0.25, &mut rays); let c3 = cast_ray(0.50, 0.50, &mut rays); let c4 = cast_ray(0.75, 0.75, &mut rays); let c5 = cast_ray(0.25, 0.75, &mut rays); *pixel = ((c1 + c2 + c3 + c4 + c5) / 5.0).to_rgb(); }; (rays, subimage) } }; // TODO: split based on core count let mut handles = Vec::new(); let core_count = 4; let split = height / core_count; for i in 0..(core_count - 1) { let new_thread = tracer(i * split, (i + 1) * split, (*scene).clone()); handles.push(thread::spawn(new_thread)); } let rest = (core_count - 1) * split; handles.push(thread::spawn(tracer(rest, height - rest, (*scene).clone()))); let mut image = image::RgbImage::new(width, height); let mut rays = 0; // handles.iter().enumerate() doesn't work since it won't take a mutable // reference to the handle. let mut i = 0; for handle in handles { let (new_rays, subimage) = handle.join().unwrap(); // TODO: see Image.sub_image - is it thread safe? image::GenericImage::copy_from(&mut image, &subimage, 0, (i * split as usize) as u32); rays += new_rays; i += 1; } write_image(image, "test.png"); let elapsed_time = ((time::precise_time_ns() - start_time) as f64) / 1000000.0; let rays_per_s = 1000.0 * (rays as f64) / elapsed_time; println!("Traced {} rays in {} ms ({} rays per second).", rays, elapsed_time, rays_per_s); }
mod cli; mod common; #[cfg(test)] mod tests; // TODO mod server; mod client; use crate::cli::CliArgs; use crate::command_is_executing::CommandIsExecuting; use crate::os_input_output::get_os_input; use crate::utils::{ consts::{ZELLIJ_IPC_PIPE, ZELLIJ_TMP_DIR, ZELLIJ_TMP_LOG_DIR}, logging::*, }; use client::{boundaries, layout, panes, tab}; use common::{ command_is_executing, errors, os_input_output, pty_bus, screen, start, utils, wasm_vm, ApiCommand, }; use std::io::Write; use std::os::unix::net::UnixStream; use structopt::StructOpt; pub fn main() { let opts = CliArgs::from_args(); if let Some(split_dir) = opts.split { match split_dir { 'h' => { let mut stream = UnixStream::connect(ZELLIJ_IPC_PIPE).unwrap(); let api_command = bincode::serialize(&ApiCommand::SplitHorizontally).unwrap(); stream.write_all(&api_command).unwrap(); } 'v' => { let mut stream = UnixStream::connect(ZELLIJ_IPC_PIPE).unwrap(); let api_command = bincode::serialize(&ApiCommand::SplitVertically).unwrap(); stream.write_all(&api_command).unwrap(); } _ => {} }; } else if opts.move_focus { let mut stream = UnixStream::connect(ZELLIJ_IPC_PIPE).unwrap(); let api_command = bincode::serialize(&ApiCommand::MoveFocus).unwrap(); stream.write_all(&api_command).unwrap(); } else if let Some(file_to_open) = opts.open_file { let mut stream = UnixStream::connect(ZELLIJ_IPC_PIPE).unwrap(); let api_command = bincode::serialize(&ApiCommand::OpenFile(file_to_open)).unwrap(); stream.write_all(&api_command).unwrap(); } else { let os_input = get_os_input(); atomic_create_dir(ZELLIJ_TMP_DIR).unwrap(); atomic_create_dir(ZELLIJ_TMP_LOG_DIR).unwrap(); start(Box::new(os_input), opts); } }
#![allow(dead_code)] extern crate chrono; use std::mem; use std::result::Result; use std::convert::TryInto; use chrono::{DateTime, Utc, NaiveDateTime}; use crate::errors::*; #[derive(Debug, Default)] pub struct CoffHeader { f_machine: u16, /* machine type */ f_nscns: u16, /* number of sections */ f_timdat: u32, /* timestamp */ f_symptr: u32, /* pointer to symbol table */ f_nsyms: u32, /* number of symbols */ f_opthdr: u16, /* pointer to optional header */ f_flags: u16 /* flags */ } #[derive(Debug)] pub enum CoffHeaderMachineType { Unknown, AM33, AMD64, ARM, ARM64, ARMNT, EBC, I386, IA64, M32R, MIPS16, MIPSFPU, MIPSFPU16, PowerPC, PowerPCFP, R4000, RISCV32, RISCV64, RISCV128, SH3, SH3DSP, SH4, SH5, Thumb, WCEMIPSV2 } impl CoffHeaderMachineType { pub fn to_value(machine: CoffHeaderMachineType) -> u16 { match machine { CoffHeaderMachineType::Unknown => 0x0000, CoffHeaderMachineType::AM33 => 0x01D3, CoffHeaderMachineType::AMD64 => 0x8664, CoffHeaderMachineType::ARM => 0x01C0, CoffHeaderMachineType::ARM64 => 0xAA64, CoffHeaderMachineType::ARMNT => 0x01C4, CoffHeaderMachineType::EBC => 0x0EBC, CoffHeaderMachineType::I386 => 0x014C, CoffHeaderMachineType::IA64 => 0x0200, CoffHeaderMachineType::M32R => 0x9041, CoffHeaderMachineType::MIPS16 => 0x0266, CoffHeaderMachineType::MIPSFPU => 0x0366, CoffHeaderMachineType::MIPSFPU16 => 0x0466, CoffHeaderMachineType::PowerPC => 0x01F0, CoffHeaderMachineType::PowerPCFP => 0x01F1, CoffHeaderMachineType::R4000 => 0x0166, CoffHeaderMachineType::RISCV32 => 0x5032, CoffHeaderMachineType::RISCV64 => 0x5064, CoffHeaderMachineType::RISCV128 => 0x5128, CoffHeaderMachineType::SH3 => 0x01A2, CoffHeaderMachineType::SH3DSP => 0x01A3, CoffHeaderMachineType::SH4 => 0x01A6, CoffHeaderMachineType::SH5 => 0x01A8, CoffHeaderMachineType::Thumb => 0x01C2, CoffHeaderMachineType::WCEMIPSV2 => 0x0169 } } pub fn from_value(value: u16) -> CoffHeaderMachineType { match value { 0x0000 => CoffHeaderMachineType::Unknown, 0x01D3 => CoffHeaderMachineType::AM33, 0x8664 => CoffHeaderMachineType::AMD64, 0x01C0 => CoffHeaderMachineType::ARM, 0xAA64 => CoffHeaderMachineType::ARM64, 0x01C4 => CoffHeaderMachineType::ARMNT, 0x0EBC => CoffHeaderMachineType::EBC, 0x014C => CoffHeaderMachineType::I386, 0x0200 => CoffHeaderMachineType::IA64, 0x9041 => CoffHeaderMachineType::M32R, 0x0266 => CoffHeaderMachineType::MIPS16, 0x0366 => CoffHeaderMachineType::MIPSFPU, 0x0466 => CoffHeaderMachineType::MIPSFPU16, 0x01F0 => CoffHeaderMachineType::PowerPC, 0x01F1 => CoffHeaderMachineType::PowerPCFP, 0x0166 => CoffHeaderMachineType::R4000, 0x5032 => CoffHeaderMachineType::RISCV32, 0x5064 => CoffHeaderMachineType::RISCV64, 0x5128 => CoffHeaderMachineType::RISCV128, 0x01A2 => CoffHeaderMachineType::SH3, 0x01A3 => CoffHeaderMachineType::SH3DSP, 0x01A6 => CoffHeaderMachineType::SH4, 0x01A8 => CoffHeaderMachineType::SH5, 0x01C2 => CoffHeaderMachineType::Thumb, 0x0169 => CoffHeaderMachineType::WCEMIPSV2, _ => CoffHeaderMachineType::Unknown } } } pub enum CoffHeaderCharacteristic { RelocsStripped, ExecutableImage, LineNumsStripped, LocalSymsStripped, AggressiveWsTrim, LargeAddressAware, Reserved, BytesReversedLo, Machine32Bit, DebugStripped, RemovableRunFromSwap, NetRunFromSwap, FileSystem, Dll, UpSystemOnly, BytesReversedHi } impl CoffHeaderCharacteristic { pub fn to_value(characteristic: CoffHeaderCharacteristic) -> u16 { match characteristic { CoffHeaderCharacteristic::RelocsStripped => 0x0001, CoffHeaderCharacteristic::ExecutableImage => 0x0002, CoffHeaderCharacteristic::LineNumsStripped => 0x0004, CoffHeaderCharacteristic::LocalSymsStripped => 0x0008, CoffHeaderCharacteristic::AggressiveWsTrim => 0x0010, CoffHeaderCharacteristic::LargeAddressAware => 0x0020, CoffHeaderCharacteristic::Reserved => 0x0040, CoffHeaderCharacteristic::BytesReversedLo => 0x0080, CoffHeaderCharacteristic::Machine32Bit => 0x0100, CoffHeaderCharacteristic::DebugStripped => 0x0200, CoffHeaderCharacteristic::RemovableRunFromSwap => 0x0400, CoffHeaderCharacteristic::NetRunFromSwap => 0x0800, CoffHeaderCharacteristic::FileSystem => 0x1000, CoffHeaderCharacteristic::Dll => 0x2000, CoffHeaderCharacteristic::UpSystemOnly => 0x4000, CoffHeaderCharacteristic::BytesReversedHi => 0x8000 } } } impl CoffHeader { pub fn get_machine(&self) -> u16 { self.f_machine } pub fn get_machine_as_enum(&self) -> CoffHeaderMachineType { CoffHeaderMachineType::from_value(self.f_machine) } pub fn set_machine(&mut self, machine: u16) { self.f_machine = machine; } pub fn set_machine_as_enum(&mut self, machine: CoffHeaderMachineType) { self.f_machine = CoffHeaderMachineType::to_value(machine); } pub fn get_nscns(&self) -> u16 { self.f_nscns } pub fn set_nscns(&mut self, nscns: u16) { self.f_nscns = nscns; } pub fn get_timdat(&self) -> u32 { self.f_timdat } pub fn get_timdat_as_dt(&self) -> DateTime<Utc> { DateTime::<Utc>::from_utc( NaiveDateTime::from_timestamp(self.f_timdat as i64, 0), Utc) } pub fn set_timdat(&mut self, timdat: u32) { self.f_timdat = timdat; } pub fn set_timdat_as_dt(&mut self, timdat: DateTime<Utc>) -> Result<(), ButylError> { match timdat.timestamp().try_into() { Ok(t) => { self.f_timdat = t; return Ok(()); }, Err(_e) => return Err(ButylError::ExcessiveDataError) }; } pub fn get_symptr(&self) -> u32 { self.f_symptr } pub fn set_symptr(&mut self, symptr: u32) { self.f_symptr = symptr; } pub fn get_nsyms(&self) -> u32 { self.f_nsyms } pub fn set_nsyms(&mut self, nsyms: u32) { self.f_nsyms = nsyms; } pub fn get_opthdr(&self) -> u16 { self.f_opthdr } pub fn set_opthdr(&mut self, opthdr: u16) { self.f_opthdr = opthdr; } pub fn get_flags(&self) -> u16 { self.f_flags } pub fn set_flags(&mut self, flags: u16) { self.f_flags = flags; } pub fn is_flag_set(&self, flag: CoffHeaderCharacteristic) -> bool { self.f_flags & CoffHeaderCharacteristic::to_value(flag) != 0 } pub fn from_be_bytes(bytes: &[u8]) -> Result<CoffHeader, ButylError> { if bytes.len() < mem::size_of::<CoffHeader>() { /* bounds check */ return Err(ButylError::InsufficientDataError); } let mut coff_header: CoffHeader = CoffHeader::default(); coff_header.f_machine = ((bytes[0] as u16) << 8) | bytes[1] as u16; coff_header.f_nscns = ((bytes[2] as u16) << 8) | bytes[3] as u16; coff_header.f_timdat = ((bytes[4] as u32) << 24) | ((bytes[5] as u32) << 16) | ((bytes[6] as u32) << 8) | bytes[7] as u32; coff_header.f_symptr = ((bytes[8] as u32) << 24) | ((bytes[9] as u32) << 16) | ((bytes[10] as u32) << 8) | bytes[11] as u32; coff_header.f_nsyms = ((bytes[12] as u32) << 24) | ((bytes[13] as u32) << 16) | ((bytes[14] as u32) << 8) | bytes[15] as u32; coff_header.f_opthdr = ((bytes[16] as u16) << 8) | bytes[17] as u16; coff_header.f_flags = ((bytes[17] as u16) << 8) | bytes[18] as u16; Ok(coff_header) } pub fn from_le_bytes(bytes: &[u8]) -> Result<CoffHeader, ButylError> { if bytes.len() < mem::size_of::<CoffHeader>() { /* bounds check */ return Err(ButylError::InsufficientDataError); } let mut coff_header: CoffHeader = CoffHeader::default(); coff_header.f_machine = ((bytes[1] as u16) << 8) | bytes[0] as u16; coff_header.f_nscns = ((bytes[3] as u16) << 8) | bytes[2] as u16; coff_header.f_timdat = ((bytes[7] as u32) << 24) | ((bytes[6] as u32) << 16) | ((bytes[5] as u32) << 8) | bytes[4] as u32; coff_header.f_symptr = ((bytes[11] as u32) << 24) | ((bytes[10] as u32) << 16) | ((bytes[9] as u32) << 8) | bytes[8] as u32; coff_header.f_nsyms = ((bytes[15] as u32) << 24) | ((bytes[14] as u32) << 16) | ((bytes[13] as u32) << 8) | bytes[12] as u32; coff_header.f_opthdr = ((bytes[17] as u16) << 8) | bytes[16] as u16; coff_header.f_flags = ((bytes[19] as u16) << 8) | bytes[18] as u16; Ok(coff_header) } } #[derive(Debug)] pub struct CoffFile<'a> { header: CoffHeader, data: &'a[u8] } impl<'a> CoffFile<'a> { pub fn from_be_bytes(data: &[u8]) -> Result<CoffFile, ButylError> { Ok(CoffFile { header: CoffHeader::from_be_bytes(data)?, data: data }) } pub fn from_le_bytes(data: &[u8]) -> Result<CoffFile, ButylError> { Ok(CoffFile { header: CoffHeader::from_le_bytes(data)?, data: data }) } }
// Copyright 2017 Gerald Haesendonck // Licensed under the Academic Free License version 3.0 //! ntriple, a library to parse N-Triples on a per string basis. //! //! # Examples //! //! Here's a typical example. It sends an input string (can be a line from a //! file for example) to the `triple_line()` method of the `parser`, //! which returns an `Option<Triple>` if the input is valid, or a `None` or `ParseError` //! if the input is a comment or an invalid triple respectively. //! //! If you are sure that the input should be a triple and no comment, white space, //! or other rubbish, you can just use the `triple` method, which omits the //! `Option` and directly returns a `ParseResult<Triple>`. //! //! ``` //!use ntriple::parser::triple_line; //!use ntriple::{Subject, Predicate, Object}; //! //!fn main() { //! //! // Here's some input in n-triples format. Unicode escape sequences are resolved //! // so \u30AA becomes オ. //! let input = "_:subject <http://example.org/predicate> \"\\u30AAオブジェクト\"."; //! //! // parse the input: //! let parse_result = triple_line(&input); //! //! // The result contains an option, or an error when parsing the input failed. //! match parse_result { //! //! // Ok if the input is a triple, a comment, an empty string or whitespace(s). //! Ok(triple_option) => { //! match triple_option { //! Some(triple) => { // a valid triple is found. //! match triple.subject { //! // In this case we expect a blank node label //! Subject::BNode(subject) => println!("Subject: blank node: {}", subject), //! _ => println!("Weird, a blank node is expected here.") //! }; //! match triple.predicate { //! Predicate::IriRef(iri) => println!("Predicate: {}", iri) //! }; //! match triple.object { //! Object::Lit(literal) => println!("Object: literal: {} ", literal.data), //! _ => println!("Weird, a literal is expected here.") //! } //! }, //! None => { println!("Skipped [{}]", input); } //! }; //! }, //! // a parse error: the input is no valid triple, comment, empty string or whitespace(s) //! Err(error) => println!("{}\n{}", input, error), //! }; //!} //! ``` /// Represents an RDF statement in the form of a triple. #[derive(Debug)] pub struct Triple { /// The subject part. This can be an IRI or a blank node. pub subject: Subject, /// The predicate part. This is an IRI. pub predicate: Predicate, /// The object part. This can be an IRI, a blank node or a literal. pub object: Object } /// Represents the subject part of a triple. #[derive(Debug)] pub enum Subject { /// The unescaped lexical form of the IRI. IriRef(String), BNode(String) } /// Represents the predicate part of a triple. #[derive(Debug)] pub enum Predicate { /// The unescaped lexical form of the IRI. IriRef(String) } /// Represents the object part of a triple. #[derive(Debug)] pub enum Object { /// The unescaped lexical form of the IRI. IriRef(String), BNode(String), /// The unescaped lexial form of the literal. Lit(Literal) } /// Represents either a type or a language. #[derive(Debug)] pub enum TypeLang { /// a language tag (e.g. `nl-be`). Lang(String), /// a type reference (e.g. `https://www.w3.org/2001/XMLSchema#float`). Type(String) } /// Represents an RDF literal. #[derive(Debug)] pub struct Literal { /// The literal part (e.g. `This is a literal`). pub data: String, /// The type or language of the literal. pub data_type: TypeLang } pub mod parser { //! Generated code. include!(concat!(env!("OUT_DIR"), "/ntriple.rs")); } mod tests;
use svc_agent::AccountId; use svc_authz::{ Authenticable, ClientMap, Config, ConfigMap, IntentObject, LocalWhitelistConfig, LocalWhitelistRecord, }; use crate::app::AuthzObject; use crate::test_helpers::USR_AUDIENCE; /////////////////////////////////////////////////////////////////////////////// #[derive(Clone, Debug)] pub struct TestAuthz { records: Vec<LocalWhitelistRecord>, audience: String, } impl TestAuthz { pub fn new() -> Self { Self { records: vec![], audience: USR_AUDIENCE.to_owned(), } } pub fn set_audience(&mut self, audience: &str) -> &mut Self { self.audience = audience.to_owned(); self } pub fn allow<A: Authenticable>(&mut self, subject: &A, object: Vec<&str>, action: &str) { let object: Box<dyn IntentObject> = AuthzObject::new(&object).into(); let record = LocalWhitelistRecord::new(subject, object, action); self.records.push(record); } } impl From<TestAuthz> for ClientMap { fn from(authz: TestAuthz) -> Self { let config = LocalWhitelistConfig::new(authz.records); let mut config_map = ConfigMap::new(); config_map.insert(authz.audience.to_owned(), Config::LocalWhitelist(config)); let account_id = AccountId::new("dispatcher", &authz.audience); ClientMap::new(&account_id, None, config_map, None).expect("Failed to build authz") } }
/* Copyright (c) 2021 Jeremy Carter <jeremy@jeremycarter.ca> All uses of this project in part or in whole are governed by the terms of the license contained in the file titled "LICENSE" that's distributed along with the project, which can be found in the top-level directory of this project. If you don't agree to follow those terms or you won't follow them, you are not allowed to use this project or anything that's made with parts of it at all. The project is also depending on some third-party technologies, and some of those are governed by their own separate licenses, so furthermore, whenever legally possible, all license terms from all of the different technologies apply, with this project's license terms taking first priority. */ mod app; pub mod constant; mod id; mod kind; mod obj; mod result; mod root; use app::NobApp; pub use result::{NobResultError, NobResultErrorCode, NobResultSuccess}; pub use root::NobRoot; pub fn main(app: &dyn NobApp) -> Result<NobResultSuccess, (NobResultError, NobResultErrorCode)> { app.main() }
#![doc = "generated by AutoRust 0.1.0"] #![allow(unused_mut)] #![allow(unused_variables)] #![allow(unused_imports)] use crate::models::*; use reqwest::StatusCode; use snafu::{ResultExt, Snafu}; pub mod profiles { use crate::models::*; use reqwest::StatusCode; use snafu::{ResultExt, Snafu}; pub async fn list( operation_config: &crate::OperationConfig, subscription_id: &str, ) -> std::result::Result<ProfileListResult, list::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/providers/Microsoft.Cdn/profiles", &operation_config.base_path, subscription_id ); let mut req_builder = client.get(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(list::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); let req = req_builder.build().context(list::BuildRequestError)?; let rsp = client.execute(req).await.context(list::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?; let rsp_value: ProfileListResult = serde_json::from_slice(&body).context(list::DeserializeError { body })?; Ok(rsp_value) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(list::DeserializeError { body })?; list::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn list_by_resource_group( operation_config: &crate::OperationConfig, resource_group_name: &str, subscription_id: &str, ) -> std::result::Result<ProfileListResult, list_by_resource_group::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/profiles", &operation_config.base_path, subscription_id, resource_group_name ); let mut req_builder = client.get(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(list_by_resource_group::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); let req = req_builder.build().context(list_by_resource_group::BuildRequestError)?; let rsp = client.execute(req).await.context(list_by_resource_group::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(list_by_resource_group::ResponseBytesError)?; let rsp_value: ProfileListResult = serde_json::from_slice(&body).context(list_by_resource_group::DeserializeError { body })?; Ok(rsp_value) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(list_by_resource_group::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(list_by_resource_group::DeserializeError { body })?; list_by_resource_group::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list_by_resource_group { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn get( operation_config: &crate::OperationConfig, resource_group_name: &str, profile_name: &str, subscription_id: &str, ) -> std::result::Result<Profile, get::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/profiles/{}", &operation_config.base_path, subscription_id, resource_group_name, profile_name ); let mut req_builder = client.get(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(get::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); let req = req_builder.build().context(get::BuildRequestError)?; let rsp = client.execute(req).await.context(get::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?; let rsp_value: Profile = serde_json::from_slice(&body).context(get::DeserializeError { body })?; Ok(rsp_value) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(get::DeserializeError { body })?; get::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod get { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn create( operation_config: &crate::OperationConfig, resource_group_name: &str, profile_name: &str, profile: &Profile, subscription_id: &str, ) -> std::result::Result<create::Response, create::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/profiles/{}", &operation_config.base_path, subscription_id, resource_group_name, profile_name ); let mut req_builder = client.put(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(create::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); req_builder = req_builder.json(profile); let req = req_builder.build().context(create::BuildRequestError)?; let rsp = client.execute(req).await.context(create::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?; let rsp_value: Profile = serde_json::from_slice(&body).context(create::DeserializeError { body })?; Ok(create::Response::Ok200(rsp_value)) } StatusCode::CREATED => { let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?; let rsp_value: Profile = serde_json::from_slice(&body).context(create::DeserializeError { body })?; Ok(create::Response::Created201(rsp_value)) } StatusCode::ACCEPTED => { let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?; let rsp_value: Profile = serde_json::from_slice(&body).context(create::DeserializeError { body })?; Ok(create::Response::Accepted202(rsp_value)) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(create::DeserializeError { body })?; create::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod create { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug)] pub enum Response { Ok200(Profile), Created201(Profile), Accepted202(Profile), } #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn update( operation_config: &crate::OperationConfig, resource_group_name: &str, profile_name: &str, profile_update_parameters: &ProfileUpdateParameters, subscription_id: &str, ) -> std::result::Result<update::Response, update::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/profiles/{}", &operation_config.base_path, subscription_id, resource_group_name, profile_name ); let mut req_builder = client.patch(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(update::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); req_builder = req_builder.json(profile_update_parameters); let req = req_builder.build().context(update::BuildRequestError)?; let rsp = client.execute(req).await.context(update::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?; let rsp_value: Profile = serde_json::from_slice(&body).context(update::DeserializeError { body })?; Ok(update::Response::Ok200(rsp_value)) } StatusCode::ACCEPTED => { let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?; let rsp_value: Profile = serde_json::from_slice(&body).context(update::DeserializeError { body })?; Ok(update::Response::Accepted202(rsp_value)) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(update::DeserializeError { body })?; update::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod update { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug)] pub enum Response { Ok200(Profile), Accepted202(Profile), } #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn delete( operation_config: &crate::OperationConfig, resource_group_name: &str, profile_name: &str, subscription_id: &str, ) -> std::result::Result<delete::Response, delete::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/profiles/{}", &operation_config.base_path, subscription_id, resource_group_name, profile_name ); let mut req_builder = client.delete(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(delete::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); let req = req_builder.build().context(delete::BuildRequestError)?; let rsp = client.execute(req).await.context(delete::ExecuteRequestError)?; match rsp.status() { StatusCode::ACCEPTED => Ok(delete::Response::Accepted202), StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204), status_code => { let body: bytes::Bytes = rsp.bytes().await.context(delete::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(delete::DeserializeError { body })?; delete::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod delete { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug)] pub enum Response { Accepted202, NoContent204, } #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn generate_sso_uri( operation_config: &crate::OperationConfig, resource_group_name: &str, profile_name: &str, subscription_id: &str, ) -> std::result::Result<SsoUri, generate_sso_uri::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/profiles/{}/generateSsoUri", &operation_config.base_path, subscription_id, resource_group_name, profile_name ); let mut req_builder = client.post(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(generate_sso_uri::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); req_builder = req_builder.header(reqwest::header::CONTENT_LENGTH, 0); let req = req_builder.build().context(generate_sso_uri::BuildRequestError)?; let rsp = client.execute(req).await.context(generate_sso_uri::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(generate_sso_uri::ResponseBytesError)?; let rsp_value: SsoUri = serde_json::from_slice(&body).context(generate_sso_uri::DeserializeError { body })?; Ok(rsp_value) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(generate_sso_uri::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(generate_sso_uri::DeserializeError { body })?; generate_sso_uri::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod generate_sso_uri { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn list_supported_optimization_types( operation_config: &crate::OperationConfig, resource_group_name: &str, profile_name: &str, subscription_id: &str, ) -> std::result::Result<SupportedOptimizationTypesListResult, list_supported_optimization_types::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/profiles/{}/getSupportedOptimizationTypes", &operation_config.base_path, subscription_id, resource_group_name, profile_name ); let mut req_builder = client.post(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(list_supported_optimization_types::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); req_builder = req_builder.header(reqwest::header::CONTENT_LENGTH, 0); let req = req_builder.build().context(list_supported_optimization_types::BuildRequestError)?; let rsp = client .execute(req) .await .context(list_supported_optimization_types::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(list_supported_optimization_types::ResponseBytesError)?; let rsp_value: SupportedOptimizationTypesListResult = serde_json::from_slice(&body).context(list_supported_optimization_types::DeserializeError { body })?; Ok(rsp_value) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(list_supported_optimization_types::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(list_supported_optimization_types::DeserializeError { body })?; list_supported_optimization_types::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list_supported_optimization_types { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn list_resource_usage( operation_config: &crate::OperationConfig, resource_group_name: &str, profile_name: &str, subscription_id: &str, ) -> std::result::Result<ResourceUsageListResult, list_resource_usage::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/profiles/{}/checkResourceUsage", &operation_config.base_path, subscription_id, resource_group_name, profile_name ); let mut req_builder = client.post(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(list_resource_usage::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); req_builder = req_builder.header(reqwest::header::CONTENT_LENGTH, 0); let req = req_builder.build().context(list_resource_usage::BuildRequestError)?; let rsp = client.execute(req).await.context(list_resource_usage::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(list_resource_usage::ResponseBytesError)?; let rsp_value: ResourceUsageListResult = serde_json::from_slice(&body).context(list_resource_usage::DeserializeError { body })?; Ok(rsp_value) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(list_resource_usage::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(list_resource_usage::DeserializeError { body })?; list_resource_usage::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list_resource_usage { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } } pub mod endpoints { use crate::models::*; use reqwest::StatusCode; use snafu::{ResultExt, Snafu}; pub async fn list_by_profile( operation_config: &crate::OperationConfig, resource_group_name: &str, profile_name: &str, subscription_id: &str, ) -> std::result::Result<EndpointListResult, list_by_profile::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/profiles/{}/endpoints", &operation_config.base_path, subscription_id, resource_group_name, profile_name ); let mut req_builder = client.get(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(list_by_profile::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); let req = req_builder.build().context(list_by_profile::BuildRequestError)?; let rsp = client.execute(req).await.context(list_by_profile::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(list_by_profile::ResponseBytesError)?; let rsp_value: EndpointListResult = serde_json::from_slice(&body).context(list_by_profile::DeserializeError { body })?; Ok(rsp_value) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(list_by_profile::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(list_by_profile::DeserializeError { body })?; list_by_profile::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list_by_profile { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn get( operation_config: &crate::OperationConfig, resource_group_name: &str, profile_name: &str, endpoint_name: &str, subscription_id: &str, ) -> std::result::Result<Endpoint, get::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/profiles/{}/endpoints/{}", &operation_config.base_path, subscription_id, resource_group_name, profile_name, endpoint_name ); let mut req_builder = client.get(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(get::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); let req = req_builder.build().context(get::BuildRequestError)?; let rsp = client.execute(req).await.context(get::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?; let rsp_value: Endpoint = serde_json::from_slice(&body).context(get::DeserializeError { body })?; Ok(rsp_value) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(get::DeserializeError { body })?; get::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod get { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn create( operation_config: &crate::OperationConfig, resource_group_name: &str, profile_name: &str, endpoint_name: &str, endpoint: &Endpoint, subscription_id: &str, ) -> std::result::Result<create::Response, create::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/profiles/{}/endpoints/{}", &operation_config.base_path, subscription_id, resource_group_name, profile_name, endpoint_name ); let mut req_builder = client.put(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(create::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); req_builder = req_builder.json(endpoint); let req = req_builder.build().context(create::BuildRequestError)?; let rsp = client.execute(req).await.context(create::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?; let rsp_value: Endpoint = serde_json::from_slice(&body).context(create::DeserializeError { body })?; Ok(create::Response::Ok200(rsp_value)) } StatusCode::CREATED => { let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?; let rsp_value: Endpoint = serde_json::from_slice(&body).context(create::DeserializeError { body })?; Ok(create::Response::Created201(rsp_value)) } StatusCode::ACCEPTED => { let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?; let rsp_value: Endpoint = serde_json::from_slice(&body).context(create::DeserializeError { body })?; Ok(create::Response::Accepted202(rsp_value)) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(create::DeserializeError { body })?; create::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod create { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug)] pub enum Response { Ok200(Endpoint), Created201(Endpoint), Accepted202(Endpoint), } #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn update( operation_config: &crate::OperationConfig, resource_group_name: &str, profile_name: &str, endpoint_name: &str, endpoint_update_properties: &EndpointUpdateParameters, subscription_id: &str, ) -> std::result::Result<update::Response, update::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/profiles/{}/endpoints/{}", &operation_config.base_path, subscription_id, resource_group_name, profile_name, endpoint_name ); let mut req_builder = client.patch(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(update::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); req_builder = req_builder.json(endpoint_update_properties); let req = req_builder.build().context(update::BuildRequestError)?; let rsp = client.execute(req).await.context(update::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?; let rsp_value: Endpoint = serde_json::from_slice(&body).context(update::DeserializeError { body })?; Ok(update::Response::Ok200(rsp_value)) } StatusCode::ACCEPTED => { let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?; let rsp_value: Endpoint = serde_json::from_slice(&body).context(update::DeserializeError { body })?; Ok(update::Response::Accepted202(rsp_value)) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(update::DeserializeError { body })?; update::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod update { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug)] pub enum Response { Ok200(Endpoint), Accepted202(Endpoint), } #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn delete( operation_config: &crate::OperationConfig, resource_group_name: &str, profile_name: &str, endpoint_name: &str, subscription_id: &str, ) -> std::result::Result<delete::Response, delete::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/profiles/{}/endpoints/{}", &operation_config.base_path, subscription_id, resource_group_name, profile_name, endpoint_name ); let mut req_builder = client.delete(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(delete::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); let req = req_builder.build().context(delete::BuildRequestError)?; let rsp = client.execute(req).await.context(delete::ExecuteRequestError)?; match rsp.status() { StatusCode::ACCEPTED => Ok(delete::Response::Accepted202), StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204), status_code => { let body: bytes::Bytes = rsp.bytes().await.context(delete::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(delete::DeserializeError { body })?; delete::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod delete { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug)] pub enum Response { Accepted202, NoContent204, } #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn start( operation_config: &crate::OperationConfig, resource_group_name: &str, profile_name: &str, endpoint_name: &str, subscription_id: &str, ) -> std::result::Result<start::Response, start::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/profiles/{}/endpoints/{}/start", &operation_config.base_path, subscription_id, resource_group_name, profile_name, endpoint_name ); let mut req_builder = client.post(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(start::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); req_builder = req_builder.header(reqwest::header::CONTENT_LENGTH, 0); let req = req_builder.build().context(start::BuildRequestError)?; let rsp = client.execute(req).await.context(start::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(start::ResponseBytesError)?; let rsp_value: Endpoint = serde_json::from_slice(&body).context(start::DeserializeError { body })?; Ok(start::Response::Ok200(rsp_value)) } StatusCode::ACCEPTED => { let body: bytes::Bytes = rsp.bytes().await.context(start::ResponseBytesError)?; let rsp_value: Endpoint = serde_json::from_slice(&body).context(start::DeserializeError { body })?; Ok(start::Response::Accepted202(rsp_value)) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(start::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(start::DeserializeError { body })?; start::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod start { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug)] pub enum Response { Ok200(Endpoint), Accepted202(Endpoint), } #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn stop( operation_config: &crate::OperationConfig, resource_group_name: &str, profile_name: &str, endpoint_name: &str, subscription_id: &str, ) -> std::result::Result<stop::Response, stop::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/profiles/{}/endpoints/{}/stop", &operation_config.base_path, subscription_id, resource_group_name, profile_name, endpoint_name ); let mut req_builder = client.post(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(stop::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); req_builder = req_builder.header(reqwest::header::CONTENT_LENGTH, 0); let req = req_builder.build().context(stop::BuildRequestError)?; let rsp = client.execute(req).await.context(stop::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(stop::ResponseBytesError)?; let rsp_value: Endpoint = serde_json::from_slice(&body).context(stop::DeserializeError { body })?; Ok(stop::Response::Ok200(rsp_value)) } StatusCode::ACCEPTED => { let body: bytes::Bytes = rsp.bytes().await.context(stop::ResponseBytesError)?; let rsp_value: Endpoint = serde_json::from_slice(&body).context(stop::DeserializeError { body })?; Ok(stop::Response::Accepted202(rsp_value)) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(stop::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(stop::DeserializeError { body })?; stop::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod stop { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug)] pub enum Response { Ok200(Endpoint), Accepted202(Endpoint), } #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn purge_content( operation_config: &crate::OperationConfig, resource_group_name: &str, profile_name: &str, endpoint_name: &str, content_file_paths: &PurgeParameters, subscription_id: &str, ) -> std::result::Result<purge_content::Response, purge_content::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/profiles/{}/endpoints/{}/purge", &operation_config.base_path, subscription_id, resource_group_name, profile_name, endpoint_name ); let mut req_builder = client.post(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(purge_content::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); req_builder = req_builder.json(content_file_paths); let req = req_builder.build().context(purge_content::BuildRequestError)?; let rsp = client.execute(req).await.context(purge_content::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => Ok(purge_content::Response::Ok200), StatusCode::ACCEPTED => Ok(purge_content::Response::Accepted202), status_code => { let body: bytes::Bytes = rsp.bytes().await.context(purge_content::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(purge_content::DeserializeError { body })?; purge_content::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod purge_content { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug)] pub enum Response { Ok200, Accepted202, } #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn load_content( operation_config: &crate::OperationConfig, resource_group_name: &str, profile_name: &str, endpoint_name: &str, content_file_paths: &LoadParameters, subscription_id: &str, ) -> std::result::Result<load_content::Response, load_content::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/profiles/{}/endpoints/{}/load", &operation_config.base_path, subscription_id, resource_group_name, profile_name, endpoint_name ); let mut req_builder = client.post(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(load_content::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); req_builder = req_builder.json(content_file_paths); let req = req_builder.build().context(load_content::BuildRequestError)?; let rsp = client.execute(req).await.context(load_content::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => Ok(load_content::Response::Ok200), StatusCode::ACCEPTED => Ok(load_content::Response::Accepted202), status_code => { let body: bytes::Bytes = rsp.bytes().await.context(load_content::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(load_content::DeserializeError { body })?; load_content::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod load_content { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug)] pub enum Response { Ok200, Accepted202, } #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn validate_custom_domain( operation_config: &crate::OperationConfig, resource_group_name: &str, profile_name: &str, endpoint_name: &str, custom_domain_properties: &ValidateCustomDomainInput, subscription_id: &str, ) -> std::result::Result<ValidateCustomDomainOutput, validate_custom_domain::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/profiles/{}/endpoints/{}/validateCustomDomain", &operation_config.base_path, subscription_id, resource_group_name, profile_name, endpoint_name ); let mut req_builder = client.post(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(validate_custom_domain::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); req_builder = req_builder.json(custom_domain_properties); let req = req_builder.build().context(validate_custom_domain::BuildRequestError)?; let rsp = client.execute(req).await.context(validate_custom_domain::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(validate_custom_domain::ResponseBytesError)?; let rsp_value: ValidateCustomDomainOutput = serde_json::from_slice(&body).context(validate_custom_domain::DeserializeError { body })?; Ok(rsp_value) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(validate_custom_domain::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(validate_custom_domain::DeserializeError { body })?; validate_custom_domain::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod validate_custom_domain { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn list_resource_usage( operation_config: &crate::OperationConfig, resource_group_name: &str, profile_name: &str, endpoint_name: &str, subscription_id: &str, ) -> std::result::Result<ResourceUsageListResult, list_resource_usage::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/profiles/{}/endpoints/{}/checkResourceUsage", &operation_config.base_path, subscription_id, resource_group_name, profile_name, endpoint_name ); let mut req_builder = client.post(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(list_resource_usage::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); req_builder = req_builder.header(reqwest::header::CONTENT_LENGTH, 0); let req = req_builder.build().context(list_resource_usage::BuildRequestError)?; let rsp = client.execute(req).await.context(list_resource_usage::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(list_resource_usage::ResponseBytesError)?; let rsp_value: ResourceUsageListResult = serde_json::from_slice(&body).context(list_resource_usage::DeserializeError { body })?; Ok(rsp_value) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(list_resource_usage::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(list_resource_usage::DeserializeError { body })?; list_resource_usage::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list_resource_usage { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } } pub mod origins { use crate::models::*; use reqwest::StatusCode; use snafu::{ResultExt, Snafu}; pub async fn list_by_endpoint( operation_config: &crate::OperationConfig, resource_group_name: &str, profile_name: &str, endpoint_name: &str, subscription_id: &str, ) -> std::result::Result<OriginListResult, list_by_endpoint::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/profiles/{}/endpoints/{}/origins", &operation_config.base_path, subscription_id, resource_group_name, profile_name, endpoint_name ); let mut req_builder = client.get(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(list_by_endpoint::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); let req = req_builder.build().context(list_by_endpoint::BuildRequestError)?; let rsp = client.execute(req).await.context(list_by_endpoint::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(list_by_endpoint::ResponseBytesError)?; let rsp_value: OriginListResult = serde_json::from_slice(&body).context(list_by_endpoint::DeserializeError { body })?; Ok(rsp_value) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(list_by_endpoint::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(list_by_endpoint::DeserializeError { body })?; list_by_endpoint::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list_by_endpoint { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn get( operation_config: &crate::OperationConfig, resource_group_name: &str, profile_name: &str, endpoint_name: &str, origin_name: &str, subscription_id: &str, ) -> std::result::Result<Origin, get::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/profiles/{}/endpoints/{}/origins/{}", &operation_config.base_path, subscription_id, resource_group_name, profile_name, endpoint_name, origin_name ); let mut req_builder = client.get(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(get::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); let req = req_builder.build().context(get::BuildRequestError)?; let rsp = client.execute(req).await.context(get::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?; let rsp_value: Origin = serde_json::from_slice(&body).context(get::DeserializeError { body })?; Ok(rsp_value) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(get::DeserializeError { body })?; get::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod get { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn create( operation_config: &crate::OperationConfig, resource_group_name: &str, profile_name: &str, endpoint_name: &str, origin_name: &str, origin: &Origin, subscription_id: &str, ) -> std::result::Result<create::Response, create::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/profiles/{}/endpoints/{}/origins/{}", &operation_config.base_path, subscription_id, resource_group_name, profile_name, endpoint_name, origin_name ); let mut req_builder = client.put(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(create::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); req_builder = req_builder.json(origin); let req = req_builder.build().context(create::BuildRequestError)?; let rsp = client.execute(req).await.context(create::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?; let rsp_value: Origin = serde_json::from_slice(&body).context(create::DeserializeError { body })?; Ok(create::Response::Ok200(rsp_value)) } StatusCode::CREATED => { let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?; let rsp_value: Origin = serde_json::from_slice(&body).context(create::DeserializeError { body })?; Ok(create::Response::Created201(rsp_value)) } StatusCode::ACCEPTED => { let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?; let rsp_value: Origin = serde_json::from_slice(&body).context(create::DeserializeError { body })?; Ok(create::Response::Accepted202(rsp_value)) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(create::DeserializeError { body })?; create::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod create { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug)] pub enum Response { Ok200(Origin), Created201(Origin), Accepted202(Origin), } #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn update( operation_config: &crate::OperationConfig, resource_group_name: &str, profile_name: &str, endpoint_name: &str, origin_name: &str, origin_update_properties: &OriginUpdateParameters, subscription_id: &str, ) -> std::result::Result<update::Response, update::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/profiles/{}/endpoints/{}/origins/{}", &operation_config.base_path, subscription_id, resource_group_name, profile_name, endpoint_name, origin_name ); let mut req_builder = client.patch(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(update::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); req_builder = req_builder.json(origin_update_properties); let req = req_builder.build().context(update::BuildRequestError)?; let rsp = client.execute(req).await.context(update::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?; let rsp_value: Origin = serde_json::from_slice(&body).context(update::DeserializeError { body })?; Ok(update::Response::Ok200(rsp_value)) } StatusCode::ACCEPTED => { let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?; let rsp_value: Origin = serde_json::from_slice(&body).context(update::DeserializeError { body })?; Ok(update::Response::Accepted202(rsp_value)) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(update::DeserializeError { body })?; update::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod update { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug)] pub enum Response { Ok200(Origin), Accepted202(Origin), } #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn delete( operation_config: &crate::OperationConfig, resource_group_name: &str, profile_name: &str, endpoint_name: &str, origin_name: &str, subscription_id: &str, ) -> std::result::Result<delete::Response, delete::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/profiles/{}/endpoints/{}/origins/{}", &operation_config.base_path, subscription_id, resource_group_name, profile_name, endpoint_name, origin_name ); let mut req_builder = client.delete(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(delete::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); let req = req_builder.build().context(delete::BuildRequestError)?; let rsp = client.execute(req).await.context(delete::ExecuteRequestError)?; match rsp.status() { StatusCode::ACCEPTED => Ok(delete::Response::Accepted202), StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204), status_code => { let body: bytes::Bytes = rsp.bytes().await.context(delete::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(delete::DeserializeError { body })?; delete::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod delete { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug)] pub enum Response { Accepted202, NoContent204, } #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } } pub mod origin_groups { use crate::models::*; use reqwest::StatusCode; use snafu::{ResultExt, Snafu}; pub async fn list_by_endpoint( operation_config: &crate::OperationConfig, resource_group_name: &str, profile_name: &str, endpoint_name: &str, subscription_id: &str, ) -> std::result::Result<OriginGroupListResult, list_by_endpoint::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/profiles/{}/endpoints/{}/originGroups", &operation_config.base_path, subscription_id, resource_group_name, profile_name, endpoint_name ); let mut req_builder = client.get(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(list_by_endpoint::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); let req = req_builder.build().context(list_by_endpoint::BuildRequestError)?; let rsp = client.execute(req).await.context(list_by_endpoint::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(list_by_endpoint::ResponseBytesError)?; let rsp_value: OriginGroupListResult = serde_json::from_slice(&body).context(list_by_endpoint::DeserializeError { body })?; Ok(rsp_value) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(list_by_endpoint::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(list_by_endpoint::DeserializeError { body })?; list_by_endpoint::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list_by_endpoint { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn get( operation_config: &crate::OperationConfig, resource_group_name: &str, profile_name: &str, endpoint_name: &str, origin_group_name: &str, subscription_id: &str, ) -> std::result::Result<OriginGroup, get::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/profiles/{}/endpoints/{}/originGroups/{}", &operation_config.base_path, subscription_id, resource_group_name, profile_name, endpoint_name, origin_group_name ); let mut req_builder = client.get(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(get::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); let req = req_builder.build().context(get::BuildRequestError)?; let rsp = client.execute(req).await.context(get::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?; let rsp_value: OriginGroup = serde_json::from_slice(&body).context(get::DeserializeError { body })?; Ok(rsp_value) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(get::DeserializeError { body })?; get::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod get { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn create( operation_config: &crate::OperationConfig, resource_group_name: &str, profile_name: &str, endpoint_name: &str, origin_group_name: &str, origin_group: &OriginGroup, subscription_id: &str, ) -> std::result::Result<create::Response, create::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/profiles/{}/endpoints/{}/originGroups/{}", &operation_config.base_path, subscription_id, resource_group_name, profile_name, endpoint_name, origin_group_name ); let mut req_builder = client.put(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(create::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); req_builder = req_builder.json(origin_group); let req = req_builder.build().context(create::BuildRequestError)?; let rsp = client.execute(req).await.context(create::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?; let rsp_value: OriginGroup = serde_json::from_slice(&body).context(create::DeserializeError { body })?; Ok(create::Response::Ok200(rsp_value)) } StatusCode::CREATED => { let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?; let rsp_value: OriginGroup = serde_json::from_slice(&body).context(create::DeserializeError { body })?; Ok(create::Response::Created201(rsp_value)) } StatusCode::ACCEPTED => { let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?; let rsp_value: OriginGroup = serde_json::from_slice(&body).context(create::DeserializeError { body })?; Ok(create::Response::Accepted202(rsp_value)) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(create::DeserializeError { body })?; create::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod create { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug)] pub enum Response { Ok200(OriginGroup), Created201(OriginGroup), Accepted202(OriginGroup), } #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn update( operation_config: &crate::OperationConfig, resource_group_name: &str, profile_name: &str, endpoint_name: &str, origin_group_name: &str, origin_group_update_properties: &OriginGroupUpdateParameters, subscription_id: &str, ) -> std::result::Result<update::Response, update::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/profiles/{}/endpoints/{}/originGroups/{}", &operation_config.base_path, subscription_id, resource_group_name, profile_name, endpoint_name, origin_group_name ); let mut req_builder = client.patch(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(update::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); req_builder = req_builder.json(origin_group_update_properties); let req = req_builder.build().context(update::BuildRequestError)?; let rsp = client.execute(req).await.context(update::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?; let rsp_value: OriginGroup = serde_json::from_slice(&body).context(update::DeserializeError { body })?; Ok(update::Response::Ok200(rsp_value)) } StatusCode::ACCEPTED => { let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?; let rsp_value: OriginGroup = serde_json::from_slice(&body).context(update::DeserializeError { body })?; Ok(update::Response::Accepted202(rsp_value)) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(update::DeserializeError { body })?; update::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod update { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug)] pub enum Response { Ok200(OriginGroup), Accepted202(OriginGroup), } #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn delete( operation_config: &crate::OperationConfig, resource_group_name: &str, profile_name: &str, endpoint_name: &str, origin_group_name: &str, subscription_id: &str, ) -> std::result::Result<delete::Response, delete::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/profiles/{}/endpoints/{}/originGroups/{}", &operation_config.base_path, subscription_id, resource_group_name, profile_name, endpoint_name, origin_group_name ); let mut req_builder = client.delete(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(delete::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); let req = req_builder.build().context(delete::BuildRequestError)?; let rsp = client.execute(req).await.context(delete::ExecuteRequestError)?; match rsp.status() { StatusCode::ACCEPTED => Ok(delete::Response::Accepted202), StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204), status_code => { let body: bytes::Bytes = rsp.bytes().await.context(delete::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(delete::DeserializeError { body })?; delete::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod delete { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug)] pub enum Response { Accepted202, NoContent204, } #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } } pub mod custom_domains { use crate::models::*; use reqwest::StatusCode; use snafu::{ResultExt, Snafu}; pub async fn list_by_endpoint( operation_config: &crate::OperationConfig, resource_group_name: &str, profile_name: &str, endpoint_name: &str, subscription_id: &str, ) -> std::result::Result<CustomDomainListResult, list_by_endpoint::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/profiles/{}/endpoints/{}/customDomains", &operation_config.base_path, subscription_id, resource_group_name, profile_name, endpoint_name ); let mut req_builder = client.get(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(list_by_endpoint::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); let req = req_builder.build().context(list_by_endpoint::BuildRequestError)?; let rsp = client.execute(req).await.context(list_by_endpoint::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(list_by_endpoint::ResponseBytesError)?; let rsp_value: CustomDomainListResult = serde_json::from_slice(&body).context(list_by_endpoint::DeserializeError { body })?; Ok(rsp_value) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(list_by_endpoint::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(list_by_endpoint::DeserializeError { body })?; list_by_endpoint::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list_by_endpoint { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn get( operation_config: &crate::OperationConfig, resource_group_name: &str, profile_name: &str, endpoint_name: &str, custom_domain_name: &str, subscription_id: &str, ) -> std::result::Result<CustomDomain, get::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/profiles/{}/endpoints/{}/customDomains/{}", &operation_config.base_path, subscription_id, resource_group_name, profile_name, endpoint_name, custom_domain_name ); let mut req_builder = client.get(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(get::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); let req = req_builder.build().context(get::BuildRequestError)?; let rsp = client.execute(req).await.context(get::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?; let rsp_value: CustomDomain = serde_json::from_slice(&body).context(get::DeserializeError { body })?; Ok(rsp_value) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(get::DeserializeError { body })?; get::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod get { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn create( operation_config: &crate::OperationConfig, resource_group_name: &str, profile_name: &str, endpoint_name: &str, custom_domain_name: &str, custom_domain_properties: &CustomDomainParameters, subscription_id: &str, ) -> std::result::Result<create::Response, create::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/profiles/{}/endpoints/{}/customDomains/{}", &operation_config.base_path, subscription_id, resource_group_name, profile_name, endpoint_name, custom_domain_name ); let mut req_builder = client.put(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(create::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); req_builder = req_builder.json(custom_domain_properties); let req = req_builder.build().context(create::BuildRequestError)?; let rsp = client.execute(req).await.context(create::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?; let rsp_value: CustomDomain = serde_json::from_slice(&body).context(create::DeserializeError { body })?; Ok(create::Response::Ok200(rsp_value)) } StatusCode::CREATED => { let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?; let rsp_value: CustomDomain = serde_json::from_slice(&body).context(create::DeserializeError { body })?; Ok(create::Response::Created201(rsp_value)) } StatusCode::ACCEPTED => { let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?; let rsp_value: CustomDomain = serde_json::from_slice(&body).context(create::DeserializeError { body })?; Ok(create::Response::Accepted202(rsp_value)) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(create::DeserializeError { body })?; create::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod create { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug)] pub enum Response { Ok200(CustomDomain), Created201(CustomDomain), Accepted202(CustomDomain), } #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn delete( operation_config: &crate::OperationConfig, resource_group_name: &str, profile_name: &str, endpoint_name: &str, custom_domain_name: &str, subscription_id: &str, ) -> std::result::Result<delete::Response, delete::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/profiles/{}/endpoints/{}/customDomains/{}", &operation_config.base_path, subscription_id, resource_group_name, profile_name, endpoint_name, custom_domain_name ); let mut req_builder = client.delete(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(delete::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); let req = req_builder.build().context(delete::BuildRequestError)?; let rsp = client.execute(req).await.context(delete::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => Ok(delete::Response::Ok200), StatusCode::ACCEPTED => { let body: bytes::Bytes = rsp.bytes().await.context(delete::ResponseBytesError)?; let rsp_value: CustomDomain = serde_json::from_slice(&body).context(delete::DeserializeError { body })?; Ok(delete::Response::Accepted202(rsp_value)) } StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204), status_code => { let body: bytes::Bytes = rsp.bytes().await.context(delete::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(delete::DeserializeError { body })?; delete::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod delete { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug)] pub enum Response { Ok200, Accepted202(CustomDomain), NoContent204, } #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn disable_custom_https( operation_config: &crate::OperationConfig, resource_group_name: &str, profile_name: &str, endpoint_name: &str, custom_domain_name: &str, subscription_id: &str, ) -> std::result::Result<disable_custom_https::Response, disable_custom_https::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/profiles/{}/endpoints/{}/customDomains/{}/disableCustomHttps", &operation_config.base_path, subscription_id, resource_group_name, profile_name, endpoint_name, custom_domain_name ); let mut req_builder = client.post(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(disable_custom_https::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); req_builder = req_builder.header(reqwest::header::CONTENT_LENGTH, 0); let req = req_builder.build().context(disable_custom_https::BuildRequestError)?; let rsp = client.execute(req).await.context(disable_custom_https::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => Ok(disable_custom_https::Response::Ok200), StatusCode::ACCEPTED => { let body: bytes::Bytes = rsp.bytes().await.context(disable_custom_https::ResponseBytesError)?; let rsp_value: CustomDomain = serde_json::from_slice(&body).context(disable_custom_https::DeserializeError { body })?; Ok(disable_custom_https::Response::Accepted202(rsp_value)) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(disable_custom_https::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(disable_custom_https::DeserializeError { body })?; disable_custom_https::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod disable_custom_https { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug)] pub enum Response { Ok200, Accepted202(CustomDomain), } #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn enable_custom_https( operation_config: &crate::OperationConfig, resource_group_name: &str, profile_name: &str, endpoint_name: &str, custom_domain_name: &str, custom_domain_https_parameters: Option<&CustomDomainHttpsParameters>, subscription_id: &str, ) -> std::result::Result<enable_custom_https::Response, enable_custom_https::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/profiles/{}/endpoints/{}/customDomains/{}/enableCustomHttps", &operation_config.base_path, subscription_id, resource_group_name, profile_name, endpoint_name, custom_domain_name ); let mut req_builder = client.post(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(enable_custom_https::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); if let Some(custom_domain_https_parameters) = custom_domain_https_parameters { req_builder = req_builder.json(custom_domain_https_parameters); } let req = req_builder.build().context(enable_custom_https::BuildRequestError)?; let rsp = client.execute(req).await.context(enable_custom_https::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => Ok(enable_custom_https::Response::Ok200), StatusCode::ACCEPTED => { let body: bytes::Bytes = rsp.bytes().await.context(enable_custom_https::ResponseBytesError)?; let rsp_value: CustomDomain = serde_json::from_slice(&body).context(enable_custom_https::DeserializeError { body })?; Ok(enable_custom_https::Response::Accepted202(rsp_value)) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(enable_custom_https::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(enable_custom_https::DeserializeError { body })?; enable_custom_https::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod enable_custom_https { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug)] pub enum Response { Ok200, Accepted202(CustomDomain), } #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } } pub async fn check_name_availability( operation_config: &crate::OperationConfig, check_name_availability_input: &CheckNameAvailabilityInput, ) -> std::result::Result<CheckNameAvailabilityOutput, check_name_availability::Error> { let client = &operation_config.client; let uri_str = &format!("{}/providers/Microsoft.Cdn/checkNameAvailability", &operation_config.base_path,); let mut req_builder = client.post(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(check_name_availability::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); req_builder = req_builder.json(check_name_availability_input); let req = req_builder.build().context(check_name_availability::BuildRequestError)?; let rsp = client.execute(req).await.context(check_name_availability::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(check_name_availability::ResponseBytesError)?; let rsp_value: CheckNameAvailabilityOutput = serde_json::from_slice(&body).context(check_name_availability::DeserializeError { body })?; Ok(rsp_value) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(check_name_availability::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(check_name_availability::DeserializeError { body })?; check_name_availability::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod check_name_availability { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn check_name_availability_with_subscription( operation_config: &crate::OperationConfig, check_name_availability_input: &CheckNameAvailabilityInput, subscription_id: &str, ) -> std::result::Result<CheckNameAvailabilityOutput, check_name_availability_with_subscription::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/providers/Microsoft.Cdn/checkNameAvailability", &operation_config.base_path, subscription_id ); let mut req_builder = client.post(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(check_name_availability_with_subscription::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); req_builder = req_builder.json(check_name_availability_input); let req = req_builder .build() .context(check_name_availability_with_subscription::BuildRequestError)?; let rsp = client .execute(req) .await .context(check_name_availability_with_subscription::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp .bytes() .await .context(check_name_availability_with_subscription::ResponseBytesError)?; let rsp_value: CheckNameAvailabilityOutput = serde_json::from_slice(&body).context(check_name_availability_with_subscription::DeserializeError { body })?; Ok(rsp_value) } status_code => { let body: bytes::Bytes = rsp .bytes() .await .context(check_name_availability_with_subscription::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(check_name_availability_with_subscription::DeserializeError { body })?; check_name_availability_with_subscription::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod check_name_availability_with_subscription { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn validate_probe( operation_config: &crate::OperationConfig, validate_probe_input: &ValidateProbeInput, subscription_id: &str, ) -> std::result::Result<ValidateProbeOutput, validate_probe::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/providers/Microsoft.Cdn/validateProbe", &operation_config.base_path, subscription_id ); let mut req_builder = client.post(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(validate_probe::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); req_builder = req_builder.json(validate_probe_input); let req = req_builder.build().context(validate_probe::BuildRequestError)?; let rsp = client.execute(req).await.context(validate_probe::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(validate_probe::ResponseBytesError)?; let rsp_value: ValidateProbeOutput = serde_json::from_slice(&body).context(validate_probe::DeserializeError { body })?; Ok(rsp_value) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(validate_probe::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(validate_probe::DeserializeError { body })?; validate_probe::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod validate_probe { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub mod resource_usage { use crate::models::*; use reqwest::StatusCode; use snafu::{ResultExt, Snafu}; pub async fn list( operation_config: &crate::OperationConfig, subscription_id: &str, ) -> std::result::Result<ResourceUsageListResult, list::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/providers/Microsoft.Cdn/checkResourceUsage", &operation_config.base_path, subscription_id ); let mut req_builder = client.post(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(list::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); req_builder = req_builder.header(reqwest::header::CONTENT_LENGTH, 0); let req = req_builder.build().context(list::BuildRequestError)?; let rsp = client.execute(req).await.context(list::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?; let rsp_value: ResourceUsageListResult = serde_json::from_slice(&body).context(list::DeserializeError { body })?; Ok(rsp_value) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(list::DeserializeError { body })?; list::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } } pub mod operations { use crate::models::*; use reqwest::StatusCode; use snafu::{ResultExt, Snafu}; pub async fn list(operation_config: &crate::OperationConfig) -> std::result::Result<OperationsListResult, list::Error> { let client = &operation_config.client; let uri_str = &format!("{}/providers/Microsoft.Cdn/operations", &operation_config.base_path,); let mut req_builder = client.get(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(list::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); let req = req_builder.build().context(list::BuildRequestError)?; let rsp = client.execute(req).await.context(list::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?; let rsp_value: OperationsListResult = serde_json::from_slice(&body).context(list::DeserializeError { body })?; Ok(rsp_value) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(list::DeserializeError { body })?; list::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } } pub mod edge_nodes { use crate::models::*; use reqwest::StatusCode; use snafu::{ResultExt, Snafu}; pub async fn list(operation_config: &crate::OperationConfig) -> std::result::Result<EdgenodeResult, list::Error> { let client = &operation_config.client; let uri_str = &format!("{}/providers/Microsoft.Cdn/edgenodes", &operation_config.base_path,); let mut req_builder = client.get(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(list::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); let req = req_builder.build().context(list::BuildRequestError)?; let rsp = client.execute(req).await.context(list::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?; let rsp_value: EdgenodeResult = serde_json::from_slice(&body).context(list::DeserializeError { body })?; Ok(rsp_value) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(list::DeserializeError { body })?; list::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } } pub mod policies { use crate::models::*; use reqwest::StatusCode; use snafu::{ResultExt, Snafu}; pub async fn list( operation_config: &crate::OperationConfig, resource_group_name: &str, subscription_id: &str, ) -> std::result::Result<CdnWebApplicationFirewallPolicyList, list::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/CdnWebApplicationFirewallPolicies", &operation_config.base_path, subscription_id, resource_group_name ); let mut req_builder = client.get(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(list::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); let req = req_builder.build().context(list::BuildRequestError)?; let rsp = client.execute(req).await.context(list::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?; let rsp_value: CdnWebApplicationFirewallPolicyList = serde_json::from_slice(&body).context(list::DeserializeError { body })?; Ok(rsp_value) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(list::DeserializeError { body })?; list::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn get( operation_config: &crate::OperationConfig, resource_group_name: &str, policy_name: &str, subscription_id: &str, ) -> std::result::Result<CdnWebApplicationFirewallPolicy, get::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/CdnWebApplicationFirewallPolicies/{}", &operation_config.base_path, subscription_id, resource_group_name, policy_name ); let mut req_builder = client.get(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(get::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); let req = req_builder.build().context(get::BuildRequestError)?; let rsp = client.execute(req).await.context(get::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?; let rsp_value: CdnWebApplicationFirewallPolicy = serde_json::from_slice(&body).context(get::DeserializeError { body })?; Ok(rsp_value) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(get::DeserializeError { body })?; get::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod get { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn create_or_update( operation_config: &crate::OperationConfig, resource_group_name: &str, policy_name: &str, subscription_id: &str, cdn_web_application_firewall_policy: &CdnWebApplicationFirewallPolicy, ) -> std::result::Result<create_or_update::Response, create_or_update::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/CdnWebApplicationFirewallPolicies/{}", &operation_config.base_path, subscription_id, resource_group_name, policy_name ); let mut req_builder = client.put(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(create_or_update::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); req_builder = req_builder.json(cdn_web_application_firewall_policy); let req = req_builder.build().context(create_or_update::BuildRequestError)?; let rsp = client.execute(req).await.context(create_or_update::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?; let rsp_value: CdnWebApplicationFirewallPolicy = serde_json::from_slice(&body).context(create_or_update::DeserializeError { body })?; Ok(create_or_update::Response::Ok200(rsp_value)) } StatusCode::CREATED => { let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?; let rsp_value: CdnWebApplicationFirewallPolicy = serde_json::from_slice(&body).context(create_or_update::DeserializeError { body })?; Ok(create_or_update::Response::Created201(rsp_value)) } StatusCode::ACCEPTED => { let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?; let rsp_value: CdnWebApplicationFirewallPolicy = serde_json::from_slice(&body).context(create_or_update::DeserializeError { body })?; Ok(create_or_update::Response::Accepted202(rsp_value)) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(create_or_update::DeserializeError { body })?; create_or_update::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod create_or_update { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug)] pub enum Response { Ok200(CdnWebApplicationFirewallPolicy), Created201(CdnWebApplicationFirewallPolicy), Accepted202(CdnWebApplicationFirewallPolicy), } #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn update( operation_config: &crate::OperationConfig, resource_group_name: &str, policy_name: &str, subscription_id: &str, cdn_web_application_firewall_policy_patch_parameters: &CdnWebApplicationFirewallPolicyPatchParameters, ) -> std::result::Result<update::Response, update::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/CdnWebApplicationFirewallPolicies/{}", &operation_config.base_path, subscription_id, resource_group_name, policy_name ); let mut req_builder = client.patch(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(update::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); req_builder = req_builder.json(cdn_web_application_firewall_policy_patch_parameters); let req = req_builder.build().context(update::BuildRequestError)?; let rsp = client.execute(req).await.context(update::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?; let rsp_value: CdnWebApplicationFirewallPolicy = serde_json::from_slice(&body).context(update::DeserializeError { body })?; Ok(update::Response::Ok200(rsp_value)) } StatusCode::ACCEPTED => { let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?; let rsp_value: CdnWebApplicationFirewallPolicy = serde_json::from_slice(&body).context(update::DeserializeError { body })?; Ok(update::Response::Accepted202(rsp_value)) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(update::DeserializeError { body })?; update::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod update { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug)] pub enum Response { Ok200(CdnWebApplicationFirewallPolicy), Accepted202(CdnWebApplicationFirewallPolicy), } #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn delete( operation_config: &crate::OperationConfig, resource_group_name: &str, policy_name: &str, subscription_id: &str, ) -> std::result::Result<delete::Response, delete::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Cdn/CdnWebApplicationFirewallPolicies/{}", &operation_config.base_path, subscription_id, resource_group_name, policy_name ); let mut req_builder = client.delete(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(delete::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); let req = req_builder.build().context(delete::BuildRequestError)?; let rsp = client.execute(req).await.context(delete::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => Ok(delete::Response::Ok200), StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204), status_code => { let body: bytes::Bytes = rsp.bytes().await.context(delete::ResponseBytesError)?; delete::UnexpectedResponse { status_code, body: body }.fail() } } } pub mod delete { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug)] pub enum Response { Ok200, NoContent204, } #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { UnexpectedResponse { status_code: StatusCode, body: bytes::Bytes }, BuildRequestError { source: reqwest::Error }, ExecuteRequestError { source: reqwest::Error }, ResponseBytesError { source: reqwest::Error }, DeserializeError { source: serde_json::Error, body: bytes::Bytes }, GetTokenError { source: azure_core::errors::AzureError }, } } } pub mod managed_rule_sets { use crate::models::*; use reqwest::StatusCode; use snafu::{ResultExt, Snafu}; pub async fn list( operation_config: &crate::OperationConfig, subscription_id: &str, ) -> std::result::Result<ManagedRuleSetDefinitionList, list::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/providers/Microsoft.Cdn/CdnWebApplicationFirewallManagedRuleSets", &operation_config.base_path, subscription_id ); let mut req_builder = client.get(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(list::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); let req = req_builder.build().context(list::BuildRequestError)?; let rsp = client.execute(req).await.context(list::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?; let rsp_value: ManagedRuleSetDefinitionList = serde_json::from_slice(&body).context(list::DeserializeError { body })?; Ok(rsp_value) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?; let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(list::DeserializeError { body })?; list::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::ErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } }
extern crate sdl2; extern crate rand; use rand::Rng; use std::io::{Write, stdout}; mod grid; mod render; mod input; mod view; mod file_reader; macro_rules! enum_str { (enum $name:ident { $($variant:ident),*, }) => { enum $name { $($variant),* } impl std::fmt::Display for $name { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { $($name::$variant => write!(f, stringify!($variant))),* } } } }; } enum_str!{ enum SimStatus { PAUSED, RUNNING, } } struct Statistics { sim_step_ms : u128, generation : u128, fps : u64, rendering : bool, sim_status : SimStatus, board_width : u128, board_height : u128, resolution_width : u32, resolution_height : u32, } impl Statistics { fn new() -> Statistics { Statistics { sim_step_ms : 10, generation : 0, fps : 0, rendering : true, sim_status : SimStatus::PAUSED, board_width : 0, board_height : 0, resolution_width : 0, resolution_height : 0, } } } pub struct RustyLife { renderer : render::Renderer, grid : grid::Grid, input : input::Input, view : view::OrthoView, stats : Statistics, } impl RustyLife { pub fn new (board_size : (u32, u32), name : &str, window_size : (u32, u32)) -> RustyLife { let mut board_size = board_size; board_size.0 = match board_size.0 % 16 { 0 => board_size.0, x => board_size.0 + (16 - x) }; board_size.1 = match board_size.1 % 16 { 0 => board_size.1, x => board_size.1 + (16 - x) }; let mut stats = Statistics::new(); stats.board_width = board_size.0 as u128; stats.board_height = board_size.1 as u128; stats.resolution_width = window_size.0 as u32; stats.resolution_height = window_size.1 as u32; let mut grid = grid::Grid::new(board_size); let renderer = render::Renderer::new(name, window_size, grid.num_rows as u32, grid.num_cols as u32); let input = renderer.create_input(); let view = view::OrthoView::new(window_size); // match file_reader::read_rle("./foo.rle") { // Some(p) => { // for v in &p.pattern { // grid.set_cell(v.0 as usize, v.1 as usize, true); // } // } // _ => println!("Couldn't load!"), // } // Randomly initialize grid let mut rng = rand::thread_rng(); for _ in 0..(board_size.0 * board_size.1 / 2) { let col = rng.gen_range(0, board_size.0); let row = rng.gen_range(0, board_size.1); grid.set_cell(col as usize, row as usize, true); } // Or use armada of Gliders // for i in 0..=10000 { // for j in 0..=10000{ // grid.set_cell(0 + i * 7, 2 + j * 5, true); // grid.set_cell(1 + i * 7, 2 + j * 5, true); // grid.set_cell(2 + i * 7, 2 + j * 5, true); // grid.set_cell(2 + i * 7, 1 + j * 5, true); // grid.set_cell(1 + i * 7, 0 + j * 5, true); // } // } Self{renderer : renderer, input : input, grid : grid, view : view, stats : stats } } pub fn run(self : &mut Self) { match crossterm::execute!(stdout(), crossterm::cursor::SavePosition) { Err(_) => (), Ok(_) => (), } let mut sim_timer = std::time::Instant::now(); let mut frame_counter_timer = std::time::Instant::now(); let mut frame_timer = std::time::Instant::now(); let mut fps_counter = 0; let mut run = true; while run { self.input.update_input(); let input_map = self.input.get_input_map(); if input_map.keys_pressed[input::Key::ESC] { run = false; } if input_map.keys_pressed[input::Key::N] { self.grid.run_lifecycle(); self.stats.generation += 1; } if input_map.keys_pressed[input::Key::R] { self.stats.rendering = !self.stats.rendering; } if input_map.keys_pressed[input::Key::SPACE] { match self.stats.sim_status { SimStatus::RUNNING => self.stats.sim_status = SimStatus::PAUSED, _ => self.stats.sim_status = SimStatus::RUNNING, } } if input_map.keys_hold[input::Key::LSHIFT] && input_map.keys_pressed[input::Key::NumPLUS] { if self.stats.sim_step_ms < std::u128::MAX-10 { self.stats.sim_step_ms += 10; } } else if input_map.keys_pressed[input::Key::NumPLUS] { if self.stats.sim_step_ms < std::u128::MAX { self.stats.sim_step_ms += 1; } } if input_map.keys_hold[input::Key::LSHIFT] && input_map.keys_pressed[input::Key::NumMINUS] { if self.stats.sim_step_ms > 10 { self.stats.sim_step_ms -= 10; } } else if input_map.keys_pressed[input::Key::NumMINUS] { if self.stats.sim_step_ms > 0 { self.stats.sim_step_ms -= 1; } } match self.stats.sim_status { SimStatus::RUNNING => { if sim_timer.elapsed().as_millis() >= self.stats.sim_step_ms { self.grid.run_lifecycle(); self.stats.generation += 1; sim_timer = std::time::Instant::now(); } }, _ => (), } if self.stats.rendering { let frame_duration = frame_timer.elapsed(); frame_timer = std::time::Instant::now(); self.view.update(&input_map, &frame_duration); self.renderer.render(&self.grid.cells, &self.view, &frame_duration); } fps_counter = fps_counter + 1; if frame_counter_timer.elapsed().as_millis() >= 1000 { self.stats.fps = fps_counter; fps_counter = 0; frame_counter_timer = std::time::Instant::now(); } match self.print_statistics() { Err(err) => println!("Error printing Stats: \n\t{}", err), _ => (), } } } fn print_statistics(self : &Self) -> crossterm::Result<()> { use crossterm::*; let mut stdout = stdout(); queue!(stdout, cursor::RestorePosition)?; queue!(stdout, cursor::SavePosition)?; queue!(stdout, style::Print("----------------------------Rusty Life---------------------------------\n"))?; queue!(stdout, style::Print(format!("| sim_step: {}ms ", self.stats.sim_step_ms)))?; queue!(stdout, cursor::MoveToColumn(40))?; queue!(stdout, style::Print(format!("board size: {}x{} ", self.stats.board_width, self.stats.board_height)))?; queue!(stdout, cursor::MoveToColumn(71))?; queue!(stdout, style::Print("|\n"))?; queue!(stdout, style::Print(format!("| generation: {} ", self.stats.generation)))?; queue!(stdout, cursor::MoveToColumn(40))?; queue!(stdout, style::Print(format!("resolution: {}x{} ", self.stats.resolution_width, self.stats.resolution_height)))?; queue!(stdout, cursor::MoveToColumn(71))?; queue!(stdout, style::Print("|\n"))?; queue!(stdout, style::Print(format!("| fps: {} ", self.stats.fps)))?; queue!(stdout, cursor::MoveToColumn(71))?; queue!(stdout, style::Print("|\n"))?; queue!(stdout, style::Print(format!("| rendering: {} ", self.stats.rendering)))?; queue!(stdout, cursor::MoveToColumn(71))?; queue!(stdout, style::Print("|\n"))?; queue!(stdout, style::Print(format!("| status: {} ", self.stats.sim_status)))?; queue!(stdout, cursor::MoveToColumn(71))?; queue!(stdout, style::Print("|\n"))?; queue!(stdout, style::Print("-----------------------------------------------------------------------\n"))?; stdout.flush()?; Ok(()) } }
use wasm_bindgen::prelude::*; use web_sys::console; // When the `wee_alloc` feature is enabled, this uses `wee_alloc` as the global // allocator. // // If you don't want to use `wee_alloc`, you can safely delete this. #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; // This is like the `main` function, except for JavaScript. #[wasm_bindgen] pub fn greet() -> Result<JsValue, JsValue> { // This provides better error messages in debug mode. // It's disabled in release mode so it doesn't bloat up the file size. #[cfg(debug_assertions)] console_error_panic_hook::set_once(); // Your code goes here! let result = JsValue::from_str("Hello from Rust!"); console::log_1(&result); Ok(result) } #[wasm_bindgen] pub struct Person { pub age: u32, } #[wasm_bindgen] pub fn get_object() -> Result<JsValue,JsValue> { Ok(Person { age: 10 }.into()) } #[wasm_bindgen] pub fn throw_exception() -> Result<(),JsValue> { Err("Error message".into()) }
extern crate bsearch; #[test] fn find_indices() { let mut v = vec![0; 100]; for n in 0..100 { v[n] = n as i32; } for (expected_index, n) in (0..100).enumerate() { let index = match bsearch::bsearch(&v, n) { Some(i) => i, None => 1, }; assert_eq!(index, expected_index as usize); } } #[test] fn find_indices_negative_values() { let v = vec![-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]; for (expected_index, n) in (&v).iter().enumerate() { let index = match bsearch::bsearch(&v, *n) { Some(i) => i, None => 1, }; assert_eq!(index, expected_index); } } #[test] fn empty_vector() { let v = vec![]; let n = 5; let index = match bsearch::bsearch(&v, n) { Some(i) => i, None => 1, }; assert_eq!(index, 1); }
#![allow(non_snake_case, non_upper_case_globals)] extern crate time; use time::precise_time_s; /////////////////////////////////////////////////////////////////////////////// // 1. Calibration /////////////////////////////////////////////////////////////////////////////// const aalpha:f64 = 0.33333333333; // Elasticity of output w.r.t. capital const bbeta:f64 = 0.95; // Discount factor // Productivity values const vProductivity:[f64; 5] = [0.9792, 0.9896, 1.0000, 1.0106, 1.0212]; // Transition matrix const mTransition:[[f64; 5]; 5] = [ [0.9727, 0.0273, 0.0000, 0.0000, 0.0000], [0.0041, 0.9806, 0.0153, 0.0000, 0.0000], [0.0000, 0.0082, 0.9837, 0.0082, 0.0000], [0.0000, 0.0000, 0.0153, 0.9806, 0.0041], [0.0000, 0.0000, 0.0000, 0.0273, 0.9727] ]; // Dimensions to generate the grid of capital const nGridCapital: usize = 17820; const nGridProductivity: usize = 5; fn main() { let cpu0 = precise_time_s(); ///////////////////////////////////////////////////////////////////////////// // 2. Steady State ///////////////////////////////////////////////////////////////////////////// let capitalSteadyState:f64 = (aalpha*bbeta).powf(1_f64/(1_f64-aalpha)); let outputSteadyState:f64 = capitalSteadyState.powf(aalpha); let consumptionSteadyState:f64 = outputSteadyState-capitalSteadyState; println!("\ Output = {}, Capital = {}, Consumption = {}", outputSteadyState, capitalSteadyState, consumptionSteadyState); let vGridCapital = (0..nGridCapital).map(|nCapital| 0.5*capitalSteadyState + 0.00001*(nCapital as f64) ).collect::<Vec<f64>>(); // 3. Required matrices and vectors // One could use: vec![vec![0_f64; nGridProductivity]; nGridCapital]; // but for some reasons this is faster. #[inline] fn row() -> Vec<f64> { (0..nGridProductivity).map(|_| 0_f64).collect::<Vec<f64>>() } let mut mValueFunction = (0..nGridCapital).map(|_| row()).collect::<Vec<Vec<f64>>>(); let mut mValueFunctionNew = (0..nGridCapital).map(|_| row()).collect::<Vec<Vec<f64>>>(); let mut mPolicyFunction = (0..nGridCapital).map(|_| row()).collect::<Vec<Vec<f64>>>(); let mut expectedValueFunction = (0..nGridCapital).map(|_| row()).collect::<Vec<Vec<f64>>>(); // 4. We pre-build output for each point in the grid let mOutput = (0..nGridCapital).map(|nCapital| { (0..nGridProductivity).map(|nProductivity| vProductivity[nProductivity]*vGridCapital[nCapital].powf(aalpha) ).collect::<Vec<f64>>() }).collect::<Vec<Vec<f64>>>(); // 5. Main iteration // TODO: one could implement a macro for the multiple declarations let mut maxDifference = 10_f64; let mut diff: f64; let mut diffHighSoFar: f64; let tolerance = 0.0000001_f64; // compiler warn: variable does not need to be mutable let mut valueHighSoFar: f64; let mut valueProvisional: f64; let mut consumption: f64; let mut capitalChoice: f64; let mut iteration = 0; while maxDifference > tolerance { for nProductivity in 0..nGridProductivity { for nCapital in 0..nGridCapital { expectedValueFunction[nCapital][nProductivity] = 0.0; for nProductivityNextPeriod in 0..nGridProductivity { expectedValueFunction[nCapital][nProductivity] += mTransition[nProductivity][nProductivityNextPeriod]*mValueFunction[nCapital][nProductivityNextPeriod]; } } } for nProductivity in 0..nGridProductivity { // We start from previous choice (monotonicity of policy function) let mut gridCapitalNextPeriod = 0; for nCapital in 0..nGridCapital { valueHighSoFar = -100000.0; //capitalChoice = vGridCapital[0]; // compiler warn: is never read for nCapitalNextPeriod in gridCapitalNextPeriod..nGridCapital { consumption = mOutput[nCapital][nProductivity]-vGridCapital[nCapitalNextPeriod]; valueProvisional = (1_f64-bbeta)*(consumption.ln())+bbeta*expectedValueFunction[nCapitalNextPeriod][nProductivity]; if valueProvisional>valueHighSoFar { valueHighSoFar = valueProvisional; capitalChoice = vGridCapital[nCapitalNextPeriod]; gridCapitalNextPeriod = nCapitalNextPeriod; } else{ break; // We break when we have achieved the max } mValueFunctionNew[nCapital][nProductivity] = valueHighSoFar; mPolicyFunction[nCapital][nProductivity] = capitalChoice; } } } diffHighSoFar = -100000.0; for nProductivity in 0..nGridProductivity { for nCapital in 0..nGridCapital { diff = (mValueFunction[nCapital][nProductivity]-mValueFunctionNew[nCapital][nProductivity]).abs(); if diff>diffHighSoFar { diffHighSoFar = diff; } mValueFunction[nCapital][nProductivity] = mValueFunctionNew[nCapital][nProductivity]; } } maxDifference = diffHighSoFar; iteration += 1; if iteration % 10 == 0 || iteration == 1 { println!("Iteration = {}, Sup Diff = {}", iteration, maxDifference); } } println!("Iteration = {}, Sup Diff = {}\n", iteration, maxDifference); println!("My check = {}\n", mPolicyFunction[999][2]); let cpu1 = precise_time_s(); println!("Elapsed time is = {}", cpu1 - cpu0); }
#![feature(test)] extern crate test; extern crate byteorder; extern crate speedy; use std::io::{Read, Write}; use test::{Bencher, black_box}; use byteorder::{ReadBytesExt, NativeEndian}; use speedy::{Readable, Writable, Endianness}; #[bench] fn deserialization_manual_bytes( b: &mut Bencher ) { let original: &[u8] = black_box( &[1, 2, 3, 4] ); let data = original.write_to_vec( Endianness::NATIVE ).unwrap(); b.iter( || { let mut buffer = &data[..]; let len = buffer.read_u32::< NativeEndian >().unwrap() as usize; let mut vec = Vec::with_capacity( len ); unsafe { vec.set_len( len ); } buffer.read_exact( &mut vec[..] ).unwrap(); vec }) } #[bench] fn deserialization_speedy_bytes( b: &mut Bencher ) { let original: &[u8] = black_box( &[1, 2, 3, 4] ); let data = original.write_to_vec( Endianness::NATIVE ).unwrap(); b.iter( || { let deserialized: Vec< u8 > = Readable::read_from_buffer( Endianness::NATIVE, &data ).unwrap(); deserialized }) } #[bench] fn deserialization_manual_string( b: &mut Bencher ) { let original: &str = black_box( "Hello world!" ); let data = original.write_to_vec( Endianness::NATIVE ).unwrap(); b.iter( || { let mut buffer = &data[..]; let len = buffer.read_u32::< NativeEndian >().unwrap() as usize; let mut vec = Vec::with_capacity( len ); unsafe { vec.set_len( len ); } buffer.read_exact( &mut vec[..] ).unwrap(); String::from_utf8( vec ) }) } #[bench] fn deserialization_speedy_string( b: &mut Bencher ) { let original: &str = black_box( "Hello world!" ); let data = original.write_to_vec( Endianness::NATIVE ).unwrap(); b.iter( || { let deserialized: String = Readable::read_from_buffer( Endianness::NATIVE, &data ).unwrap(); deserialized }) } #[bench] fn deserialization_manual_u8( b: &mut Bencher ) { let original: u8 = black_box( 12 ); let data = original.write_to_vec( Endianness::NATIVE ).unwrap(); b.iter( || { let mut buffer = &data[..]; buffer.read_u8().unwrap() }) } #[bench] fn deserialization_speedy_u8( b: &mut Bencher ) { let original: u8 = black_box( 12 ); let data = original.write_to_vec( Endianness::NATIVE ).unwrap(); b.iter( || { let deserialized: u8 = Readable::read_from_buffer( Endianness::NATIVE, &data ).unwrap(); deserialized }) } #[bench] fn deserialization_manual_u64( b: &mut Bencher ) { let original: u64 = black_box( 1234 ); let data = original.write_to_vec( Endianness::NATIVE ).unwrap(); b.iter( || { let mut buffer = &data[..]; buffer.read_u64::< NativeEndian >().unwrap() }) } #[bench] fn deserialization_speedy_u64( b: &mut Bencher ) { let original: u64 = black_box( 1234 ); let data = original.write_to_vec( Endianness::NATIVE ).unwrap(); b.iter( || { let deserialized: u64 = Readable::read_from_buffer( Endianness::NATIVE, &data ).unwrap(); deserialized }) } #[bench] fn serialization_manual_megabyte_buffer( b: &mut Bencher ) { let mut buffer: Vec< u8 > = Vec::new(); buffer.resize( 1024 * 1024, 1 ); buffer = black_box( buffer ); b.iter( || { let mut output = Vec::new(); Write::write_all( &mut output, &buffer ).unwrap(); output }) } // These two benchmarks should have exactly the same speeds. #[bench] fn serialization_speedy_megabyte_buffer_le( b: &mut Bencher ) { let mut buffer: Vec< u8 > = Vec::new(); buffer.resize( 1024 * 1024, 1 ); buffer = black_box( buffer ); b.iter( || { let mut output = Vec::new(); buffer.write_to_stream( Endianness::LittleEndian, &mut output ).unwrap(); output }) } #[bench] fn serialization_speedy_megabyte_buffer_be( b: &mut Bencher ) { let mut buffer: Vec< u8 > = Vec::new(); buffer.resize( 1024 * 1024, 1 ); buffer = black_box( buffer ); b.iter( || { let mut output = Vec::new(); buffer.write_to_stream( Endianness::BigEndian, &mut output ).unwrap(); output }) }
use iced::{Application, Element, TextInput, Settings, Column, Align, text_input, Text, Length, HorizontalAlignment, Container, Command, executor, Subscription, Color, scrollable, Scrollable}; use std::fs; use std::process; use std::cmp::max; use std::cmp::min; use std::env; pub fn main() { // only open one finder at a time let is_open = process::Command::new("pgrep") .arg("bansheefinder") .output() .expect("Failed to pgrep") .stdout .iter() .fold( 0, |accumulator, value| { if value == &0xA { return accumulator + 1; } else { return accumulator; } } ); if is_open == 1 { FuzzyFinder::run(Settings { window: iced::window::Settings { decorations: false, resizable: false, size: (300, 200), }, antialiasing: false, default_font: None, flags: (), }); } } #[derive(Default)] struct FuzzyFinder { path_cache: Vec<String>, program_list: ProgramList, input: text_input::State, search: String, search_saved: String, search_index: i32, } #[derive(Debug, Clone)] enum Message { EventOccurred(iced_native::Event), InputTyped(String), Submit, } impl Application for FuzzyFinder { type Executor = executor::Default; type Message = Message; type Flags = (); fn new(_flags: ()) -> (FuzzyFinder, Command<Message>) { return (FuzzyFinder { path_cache: generate_directories(), program_list: ProgramList::default(), input: text_input::State::focused(), search: String::from(""), search_saved: String::from(""), search_index: 0, }, Command::none()); } fn title(&self) -> String { return String::from("Finder"); } fn subscription(&self) -> Subscription<Message> { return iced_native::subscription::events().map(Message::EventOccurred); } fn update(&mut self, message: Message) -> Command<Message> { match message { Message::EventOccurred(event) => { match event { iced_native::Event::Keyboard(input) => { match input { iced_native::keyboard::Event::KeyPressed { key_code, modifiers: _, } => { match key_code { iced_native::keyboard::KeyCode::Escape => { process::exit(0); } iced_native::keyboard::KeyCode::Tab => { let mut results = autocomplete(&self.search, &self.path_cache, true); sort_results(&mut results); if results.len() > 0 { self.search = results.first().expect("Failed to get first autocomplete").clone(); self.search_saved = self.search.clone(); self.search_index = 0; self.program_list.update(ProgramListMessage::Update(self.search.clone(), results)); self.program_list.update(ProgramListMessage::SearchIndex(0)); self.input.move_cursor_to_end(); } } iced_native::keyboard::KeyCode::Down => { let mut results = autocomplete(&self.search_saved, &self.path_cache, false); sort_results(&mut results); if results.len() > 0 { self.search_index = max(0, min(results.len() as i32 - 1, self.search_index + 1)); self.search = results.get(self.search_index as usize).expect("Failed to get nth element down").clone(); self.input.move_cursor_to_end(); self.program_list.update(ProgramListMessage::SearchIndex(self.search_index)); } } iced_native::keyboard::KeyCode::Up => { let mut results = autocomplete(&self.search_saved, &self.path_cache, false); sort_results(&mut results); if results.len() > 0 { self.search_index = max(0, min(results.len() as i32 - 1, self.search_index - 1)); self.search = results.get(self.search_index as usize).expect("Failed to get nth element up").clone(); self.input.move_cursor_to_end(); self.program_list.update(ProgramListMessage::SearchIndex(self.search_index)); } } _ => (), } } _ => (), } } _ => (), } } Message::InputTyped(value) => { self.search = value.clone(); self.search_saved = self.search.clone(); self.search_index = -1; let mut results = autocomplete(&self.search_saved, &self.path_cache, false); sort_results(&mut results); self.program_list.update(ProgramListMessage::Update(value, results)); } Message::Submit => { let command = self.search.clone().replace("!", ""); if command.len() > 0 { // if we have the ! modifier, then open the program in urxvt if self.search.find("!") != None { process::Command::new("i3-msg") .arg("exec") .arg("exec urxvt -e bash -c") .arg(format!("\"{} && bash\"", &command)) .output() .expect("Failed to exec urxvt"); } else { process::Command::new("i3-msg") .arg("exec") .arg(&command) .output() .expect("Failed to exec"); } process::exit(0x0); } } } return Command::none(); } fn view(&mut self) -> Element<Message> { return Container::new( Column::new() .padding(0) .align_items(Align::Center) .push( TextInput::new( &mut self.input, "", &self.search, Message::InputTyped, ) .size(15) .padding(7) .style(style::TextInput) .on_submit(Message::Submit) ) .push( self.program_list.view() ) ) .style(selected::Container) .height(Length::Fill) .padding(1) .into(); } } #[derive(Default)] struct ProgramList { search: String, search_index: i32, scroll: scrollable::State, results: Vec<String> } enum ProgramListMessage { SearchIndex(i32), Update(String, Vec<String>), } // reads directories from path and puts results into cache fn generate_directories() -> Vec<String> { if let Some(path) = env::var_os("PATH") { return env::split_paths(&path) .map( |entry| { return fs::read_dir(entry) .expect("Unable to read directory") .map( |entry| { entry .as_ref() .expect("Unable to unpack entry") .file_name() .into_string() .expect("Failed to convert OsString to String") } ) } ) .fold( Vec::new(), |mut accumulator: Vec<String>, iterator| { accumulator.append(&mut iterator.collect::<Vec<String>>()); return accumulator; } ); } else { return Vec::new(); } } fn autocomplete(search: &String, path_cache: &Vec<String>, use_find: bool) -> Vec<String> { let new_search = search.clone().replace("!", ""); if new_search.len() >= 1 { if let Some(path) = env::var_os("PATH") { return path_cache .iter() .cloned() .filter( |entry| { (!use_find && entry.find(&new_search) != None) || (use_find && entry.find(&new_search) == Some(0 as usize)) } ) .collect(); } } return Vec::new(); } fn sort_results(results: &mut Vec<String>) { results.sort_by( |a, b| { a.len().cmp(&b.len()) } ); } impl ProgramList { fn update(&mut self, message: ProgramListMessage) { match message { ProgramListMessage::Update(value, results) => { *self = ProgramList { search: value, search_index: -1, scroll: self.scroll, results } } ProgramListMessage::SearchIndex(value) => { *self = ProgramList { search: self.search.clone(), search_index: value, scroll: self.scroll, results: self.results.clone() } } } } fn view(&mut self) -> Element<Message> { let mut container = Column::new(); let mut index = 0; for result in &self.results { let mut new_result = result.clone(); new_result.insert_str(0, " "); if index == self.search_index { container = container.push( Container::new( Text::new(new_result) .width(Length::Fill) .size(10) .color(TEXT_COLOR) .horizontal_alignment(HorizontalAlignment::Left) ) .style(selected::Container) .padding(3) .width(Length::Fill) ); } else { container = container.push( Container::new( Text::new(new_result) .width(Length::Fill) .size(10) .color(UNTEXT_COLOR) .horizontal_alignment(HorizontalAlignment::Left) ) .style(style::Container) .padding(3) .width(Length::Fill) ); } index = index + 1; } return Container::new( Scrollable::new(&mut self.scroll) .push(container) .width(Length::Fill) .height(Length::Units(167)) .style(style::Scrollable) ) .width(Length::Fill) .height(Length::Fill) .style(style::Container) .into() } } const DARK_PURPLE: Color = Color::from_rgb( 0x1E as f32 / 255.0, 0x12 as f32 / 255.0, 0x1E as f32 / 255.0, ); const TEXT_COLOR: Color = Color::from_rgb( 0xB7 as f32 / 255.0, 0xAC as f32 / 255.0, 0xB7 as f32 / 255.0, ); const UNTEXT_COLOR: Color = Color::from_rgb( 0x80 as f32 / 255.0, 0x78 as f32 / 255.0, 0x80 as f32 / 255.0, ); const SELECTION_COLOR: Color = Color::from_rgb( 0x38 as f32 / 255.0, 0x26 as f32 / 255.0, 0x3F as f32 / 255.0, ); mod style { use iced::{text_input, Background, Color, container, scrollable}; pub struct TextInput; impl text_input::StyleSheet for TextInput { fn active(&self) -> text_input::Style { return text_input::Style { background: Background::Color(super::DARK_PURPLE), border_radius: 0, border_width: 1, border_color: super::DARK_PURPLE, }; } fn value_color(&self) -> Color { return super::TEXT_COLOR; } fn placeholder_color(&self) -> Color { return super::UNTEXT_COLOR; } fn focused(&self) -> text_input::Style { return text_input::Style { border_width: 1, border_color: super::DARK_PURPLE, ..self.active() }; } fn hovered(&self) -> text_input::Style { return text_input::Style { ..self.focused() }; } fn selection_color(&self) -> Color { return super::SELECTION_COLOR; } } pub struct Container; impl container::StyleSheet for Container { fn style(&self) -> container::Style { container::Style { background: Some(Background::Color(super::DARK_PURPLE)), text_color: Some(Color::from_rgb(0.0, 0.0, 0.0)), ..container::Style::default() } } } pub struct Scrollable; impl scrollable::StyleSheet for Scrollable { fn active(&self) -> scrollable::Scrollbar { scrollable::Scrollbar { background: Some(Background::Color(Color::TRANSPARENT)), border_radius: 0, border_width: 0, border_color: Color::TRANSPARENT, scroller: scrollable::Scroller { color: super::SELECTION_COLOR, border_radius: 5, border_width: 1, border_color: super::DARK_PURPLE, }, } } fn hovered(&self) -> scrollable::Scrollbar { let active = self.active(); scrollable::Scrollbar { ..active } } fn dragging(&self) -> scrollable::Scrollbar { let active = self.active(); scrollable::Scrollbar { ..active } } } } mod selected { use iced::{container, Background}; pub struct Container; impl container::StyleSheet for Container { fn style(&self) -> container::Style { container::Style { background: Some(Background::Color(super::SELECTION_COLOR)), text_color: Some(super::TEXT_COLOR), ..container::Style::default() } } } }
use serde::Deserialize; use std::{collections::BinaryHeap, convert::TryFrom, iter::FromIterator}; use necsim_core::event::PackedEvent; mod globbed; pub mod segment; mod sorted_segments; use globbed::GlobbedSortedSegments; use segment::SortedSegment; use sorted_segments::SortedSortedSegments; #[allow(clippy::module_name_repetitions)] #[derive(Debug, Deserialize)] #[serde(try_from = "Vec<GlobbedSortedSegments>")] pub struct EventLogReplay { frontier: BinaryHeap<SortedSortedSegments>, with_speciation: bool, with_dispersal: bool, } impl TryFrom<Vec<GlobbedSortedSegments>> for EventLogReplay { type Error = anyhow::Error; fn try_from(vec: Vec<GlobbedSortedSegments>) -> Result<Self, Self::Error> { vec.into_iter().flatten().collect() } } impl EventLogReplay { #[must_use] pub fn length(&self) -> usize { self.frontier.iter().map(SortedSortedSegments::length).sum() } #[must_use] pub fn with_speciation(&self) -> bool { self.with_speciation } #[must_use] pub fn with_dispersal(&self) -> bool { self.with_dispersal } } impl FromIterator<SortedSegment> for anyhow::Result<EventLogReplay> { fn from_iter<T: IntoIterator<Item = SortedSegment>>(iter: T) -> Self { let mut segments: Vec<SortedSegment> = iter.into_iter().collect(); if segments.is_empty() { anyhow::bail!("The EventLogReplay requires at least one event log segment.") } let mut with_speciation = None; let mut with_dispersal = None; for segment in &segments { if let Some(with_speciation) = with_speciation { anyhow::ensure!( with_speciation == segment.header().with_speciation(), "There is a mismatch in reporting speciation events between some segments." ); } else { with_speciation = Some(segment.header().with_speciation()); } if let Some(with_dispersal) = with_dispersal { anyhow::ensure!( with_dispersal == segment.header().with_dispersal(), "There is a mismatch in reporting dispersal events between some segments." ); } else { with_dispersal = Some(segment.header().with_dispersal()); } } let mut grouped_segments: Vec<Vec<SortedSegment>> = Vec::new(); let mut current_group: Vec<SortedSegment> = Vec::new(); let mut max_time: f64 = f64::NEG_INFINITY; while !segments.is_empty() { let mut min_time: f64 = f64::INFINITY; let mut min_index: Option<usize> = None; for (i, seg) in segments.iter().enumerate() { if seg.header().min_time() > max_time && seg.header().min_time() < min_time { min_time = seg.header().min_time().get(); min_index = Some(i); } } let min_index = if let Some(min_index) = min_index { min_index } else { if !current_group.is_empty() { grouped_segments.push(current_group); current_group = Vec::new(); } max_time = f64::NEG_INFINITY; continue; }; let min_segement = segments.swap_remove(min_index); max_time = min_segement.header().max_time().get(); current_group.push(min_segement); } if !current_group.is_empty() { grouped_segments.push(current_group); } let mut frontier = BinaryHeap::with_capacity(grouped_segments.len()); for group in grouped_segments { frontier.push(SortedSortedSegments::new(group)); } Ok(EventLogReplay { frontier, with_speciation: with_speciation.unwrap(), with_dispersal: with_dispersal.unwrap(), }) } } impl Iterator for EventLogReplay { type Item = PackedEvent; fn next(&mut self) -> Option<Self::Item> { let mut next_segment = self.frontier.pop()?; let next_event = next_segment.next(); self.frontier.push(next_segment); next_event } }
use std::fs; use intcode::Computer; fn main() { let input: Vec<i64> = fs::read_to_string("input") .unwrap() .split(',') .map(|n| n.trim().parse().unwrap()) .collect(); let cpu = Computer::from(&input[..]); part1(cpu.clone()); part2(cpu.clone()); } fn part1(mut cpu: Computer) { cpu.memory[1] = 12; cpu.memory[2] = 2; let _ = cpu.run(&[]); println!("{}", cpu.memory[0]); } fn part2(cpu: Computer) { const VALUE: i64 = 19690720; let mut done = false; for noun in 0..99 { for verb in 0..99 { let mut cpu = cpu.clone(); cpu.memory[1] = noun; cpu.memory[2] = verb; let _ = cpu.run(&[]); if cpu.memory[0] == VALUE { println!("{}", 100 * noun + verb); done = true; break; } } if done { break; } } }
use ndarray_vision::core::*; use ndarray_vision::format::netpbm::*; use ndarray_vision::format::*; use ndarray_vision::processing::*; use std::env::current_exe; use std::path::PathBuf; fn canny_edges(img: &Image<f64, Gray>) -> Image<f64, Gray> { let x = CannyBuilder::<f64>::new() .lower_threshold(0.3) .upper_threshold(0.5) .blur((5, 5), [0.4, 0.4]) .build(); let res = img.canny_edge_detector(x).expect("Failed to run canny"); Image::from_data(res.data.mapv(|x| if x { 1.0 } else { 0.0 })) } fn main() { if let Ok(mut root) = current_exe() { root.pop(); root.pop(); root.pop(); root.pop(); let mut lena = PathBuf::from(&root); lena.push("images/lena.ppm"); let decoder = PpmDecoder::default(); let image: Image<u8, _> = decoder.decode_file(lena).expect("Couldn't open Lena.ppm"); let image: Image<f64, _> = image.into_type(); let image: Image<_, Gray> = image.into(); let canny = canny_edges(&image); let image = image.apply_sobel().expect("Error in sobel"); // back to RGB let image: Image<_, RGB> = image.into(); let mut lena = PathBuf::from(&root); lena.push("images/lena-sobel.ppm"); let ppm = PpmEncoder::new_plaintext_encoder(); ppm.encode_file(&image, lena).expect("Unable to encode ppm"); let mut lena = PathBuf::from(&root); lena.push("images/lena-canny.ppm"); ppm.encode_file(&canny.into(), lena) .expect("Unable to encode ppm"); } }
extern crate nuklear_rust; #[macro_use] extern crate gfx; use nuklear_rust::{NkHandle, NkContext, NkConvertConfig, NkVec2, NkBuffer, NkDrawVertexLayoutElements, NkDrawVertexLayoutAttribute, NkDrawVertexLayoutFormat}; use gfx::{Factory, Resources, Encoder}; use gfx::texture::{Kind, AaMode}; use gfx::format::{R8_G8_B8_A8, Unorm, U8Norm}; use gfx::handle::{ShaderResourceView, RenderTargetView, Sampler, Buffer}; use gfx::traits::FactoryExt; pub type ColorFormat = gfx::format::Rgba8; pub enum GfxBackend { OpenGlsl150, DX11Hlsl, } gfx_defines!{ vertex Vertex { pos: [f32; 2] = "Position", tex: [f32; 2] = "TexCoord", col: [U8Norm; 4] = "Color", } constant Locals { proj: [[f32; 4]; 4] = "ProjMtx", } pipeline pipe { vbuf: gfx::VertexBuffer<Vertex> = (), tex: gfx::TextureSampler<[f32; 4]> = "Texture", output: gfx::BlendTarget<super::ColorFormat> = ("Target0", gfx::state::MASK_ALL, gfx::preset::blend::ALPHA), locals: gfx::ConstantBuffer<Locals> = "Locals", scissors: gfx::Scissor = (), } } impl Default for Vertex { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub struct Drawer<R: Resources> { cmd: NkBuffer, pso: gfx::PipelineState<R, pipe::Meta>, smp: Sampler<R>, tex: Vec<ShaderResourceView<R, [f32; 4]>>, vbf: Buffer<R, Vertex>, ebf: Buffer<R, u16>, lbf: Buffer<R, Locals>, vsz: usize, esz: usize, vle: NkDrawVertexLayoutElements, pub col: Option<RenderTargetView<R, (R8_G8_B8_A8, Unorm)>>, } impl<R: gfx::Resources> Drawer<R> { pub fn new<F>(factory: &mut F, col: RenderTargetView<R, (R8_G8_B8_A8, Unorm)>, texture_count: usize, vbo_size: usize, ebo_size: usize, command_buffer: NkBuffer, backend: GfxBackend) -> Drawer<R> where F: Factory<R> { use gfx::pso::buffer::Structure; let vs: &[u8] = match backend { GfxBackend::OpenGlsl150 => include_bytes!("../shaders/glsl_150/vs.glsl"), GfxBackend::DX11Hlsl => include_bytes!("../shaders/hlsl/vs.fx"), }; let fs: &[u8] = match backend { GfxBackend::OpenGlsl150 => include_bytes!("../shaders/glsl_150/fs.glsl"), GfxBackend::DX11Hlsl => include_bytes!("../shaders/hlsl/ps.fx"), //_ => &[0u8; 0], }; Drawer { cmd: command_buffer, col: Some(col), smp: factory.create_sampler_linear(), pso: factory.create_pipeline_simple(vs, fs, pipe::new()).unwrap(), tex: Vec::with_capacity(texture_count + 1), vbf: factory.create_upload_buffer::<Vertex>(vbo_size).unwrap(), ebf: factory.create_upload_buffer::<u16>(ebo_size).unwrap(), vsz: vbo_size, esz: ebo_size, lbf: factory.create_constant_buffer::<Locals>(1), vle: NkDrawVertexLayoutElements::new(&[(NkDrawVertexLayoutAttribute::NK_VERTEX_POSITION, NkDrawVertexLayoutFormat::NK_FORMAT_FLOAT, Vertex::query("Position").unwrap().offset), (NkDrawVertexLayoutAttribute::NK_VERTEX_TEXCOORD, NkDrawVertexLayoutFormat::NK_FORMAT_FLOAT, Vertex::query("TexCoord").unwrap().offset), (NkDrawVertexLayoutAttribute::NK_VERTEX_COLOR, NkDrawVertexLayoutFormat::NK_FORMAT_R8G8B8A8, Vertex::query("Color").unwrap().offset), (NkDrawVertexLayoutAttribute::NK_VERTEX_ATTRIBUTE_COUNT, NkDrawVertexLayoutFormat::NK_FORMAT_COUNT, 0u32)]), } } pub fn add_texture<F>(&mut self, factory: &mut F, image: &[u8], width: u32, height: u32) -> NkHandle where F: Factory<R> { let (_, view) = factory.create_texture_immutable_u8::<ColorFormat>(Kind::D2(width as u16, height as u16, AaMode::Single), &[image]) .unwrap(); self.tex.push(view); NkHandle::from_id(self.tex.len() as i32) } pub fn draw<F, B: gfx::CommandBuffer<R>>(&mut self, ctx: &mut NkContext, cfg: &mut NkConvertConfig, encoder: &mut Encoder<R, B>, factory: &mut F, width: u32, height: u32, scale: NkVec2) where F: Factory<R> { use gfx::IntoIndexBuffer; if self.col.clone().is_none() { return; } let ortho = [[2.0f32 / width as f32, 0.0f32, 0.0f32, 0.0f32], [0.0f32, -2.0f32 / height as f32, 0.0f32, 0.0f32], [0.0f32, 0.0f32, -1.0f32, 0.0f32], [-1.0f32, 1.0f32, 0.0f32, 1.0f32]]; cfg.set_vertex_layout(&self.vle); cfg.set_vertex_size(::std::mem::size_of::<Vertex>()); { let mut rwv = factory.write_mapping(&mut self.vbf).unwrap(); let mut rvbuf = unsafe { ::std::slice::from_raw_parts_mut(&mut *rwv as *mut [Vertex] as *mut u8, ::std::mem::size_of::<Vertex>() * self.vsz) }; let mut vbuf = NkBuffer::with_fixed(&mut rvbuf); let mut rwe = factory.write_mapping(&mut self.ebf).unwrap(); let mut rebuf = unsafe { ::std::slice::from_raw_parts_mut(&mut *rwe as *mut [u16] as *mut u8, ::std::mem::size_of::<u16>() * self.esz) }; let mut ebuf = NkBuffer::with_fixed(&mut rebuf); ctx.convert(&mut self.cmd, &mut vbuf, &mut ebuf, cfg); } let mut slice = ::gfx::Slice { start: 0, end: 0, base_vertex: 0, instances: None, buffer: self.ebf.clone().into_index_buffer(factory), }; encoder.update_constant_buffer(&mut self.lbf, &Locals { proj: ortho }); for cmd in ctx.draw_command_iterator(&self.cmd) { if cmd.elem_count() < 1 { continue; } slice.end = slice.start + cmd.elem_count(); let id = cmd.texture().id().unwrap(); let x = cmd.clip_rect().x * scale.x; let y = cmd.clip_rect().y * scale.y; let w = cmd.clip_rect().w * scale.x; let h = cmd.clip_rect().h * scale.y; let sc_rect = gfx::Rect { x: (if x < 0f32 { 0f32 } else { x }) as u16, y: (if y < 0f32 { 0f32 } else { y }) as u16, w: (if x < 0f32 { w + x } else { w }) as u16, h: (if y < 0f32 { h + y } else { h }) as u16, }; let res = self.find_res(id).unwrap(); let data = pipe::Data { vbuf: self.vbf.clone(), tex: (res, self.smp.clone()), output: self.col.clone().unwrap(), scissors: sc_rect, locals: self.lbf.clone(), }; encoder.draw(&slice, &self.pso, &data); slice.start = slice.end; } } fn find_res(&self, id: i32) -> Option<ShaderResourceView<R, [f32; 4]>> { let mut ret = None; if id > 0 && id as usize <= self.tex.len() { ret = Some(self.tex[(id - 1) as usize].clone()); } ret } }
use iron::prelude::*; use iron::status; use iron::headers::ContentType; use iron::modifiers::Header; use jsonway; use persistent::Read; use postgres::rows::Rows; use postgres::rows::Row; use rustc_serialize::json; use serde_json::value::Value as serde_Value; use uuid::Uuid; use iron_helpers; use jsonapi; #[derive(Debug, RustcEncodable)] pub struct Book { book_id: Uuid, title: String, author: String, slug: String, description: String, isbn: String, price: i32, pages: i32, cover_image: String, } impl Book { fn from_row(row: Row) -> Book { Book { book_id: row.get("book_id"), title: row.get("title"), author: row.get("author"), slug: row.get("slug"), description: row.get("description"), isbn: row.get("isbn"), price: row.get("price"), pages: row.get("pages"), cover_image: row.get("cover_image"), } } } impl jsonapi::JsonApiAble for Book { fn to_jsonapi(&self) -> serde_Value { let json = jsonway::object(|json| { json.set("type", "books".to_string()); json.set("id", self.book_id.to_string()); json.object("attributes", |json| { json.set("title", &self.title); json.set("author", &self.author); json.set("slug", &self.slug); json.set("description", &self.description); json.set("isbn", &self.isbn); json.set("price", &self.price); json.set("pages", &self.pages); json.set("cover_image", &self.cover_image); }); }); json.unwrap() } } // Saves a book pub fn create(req: &mut Request) -> IronResult<Response> { // read post parameters let title = iron_helpers::extract_param_value_from_encoded_body(req, "title"); let author = iron_helpers::extract_param_value_from_encoded_body(req, "author"); let description = iron_helpers::extract_param_value_from_encoded_body(req, "description").unwrap(); let isbn = iron_helpers::extract_param_value_from_encoded_body(req, "isbn").unwrap(); let price = iron_helpers::extract_i32_param_value_from_encoded_body(req, "price"); let pages = iron_helpers::extract_i32_param_value_from_encoded_body(req, "pages"); let cover_image = iron_helpers::extract_param_value_from_encoded_body(req, "cover_image"); // TODO: validate all required attributes // TODO: generate error dynamically if title.is_none() { let payload = "{\"missing\": \"title\"}"; return Ok(Response::with((status::UnprocessableEntity, payload))); } if price.is_none() { let payload = "{\"missing\": \"price\"}"; return Ok(Response::with((status::UnprocessableEntity, payload))); } let unwrapped_title = title.unwrap(); let slug = unwrapped_title.clone().to_lowercase().replace(" ", "-").replace(":", ""); let book = Book { book_id: Uuid::new_v4(), title: unwrapped_title, author: author.unwrap(), description: description, isbn: isbn, price: price.unwrap(), pages: pages.unwrap(), slug: slug, cover_image: cover_image.unwrap(), }; let pool = req.get::<Read<::AppDb>>().unwrap(); let conn = pool.get().unwrap(); conn.execute("INSERT INTO books (book_id, title, description, isbn, \ price, , pages, slug) VALUES ($1, $2, $3, $4, $5, $6, $7)", &[&book.book_id, &book.title, &book.description, &book.isbn, &book.price, &book.pages, &book.slug]).unwrap(); println!("created book {:?} ", book); let payload = json::encode(&book).unwrap(); Ok(Response::with((status::Created, Header(ContentType::json()), payload))) } pub fn index(req: &mut Request) -> IronResult<Response> { let pool = req.get::<Read<::AppDb>>().unwrap(); let conn = pool.get().unwrap(); let slug = iron_helpers::extract_string_param(req, "filter[slug]"); let mut sql = String::new(); sql.push_str("SELECT book_id, title, author, description, isbn, price, pages, \ slug, cover_image FROM books"); if slug.is_some() { sql.push_str(" WHERE slug='"); sql.push_str(&slug.unwrap()); sql.push_str("'"); } else { sql.push_str(" LIMIT 10"); } let mut books: Vec<Book> = Vec::new(); for row in &conn.query(&sql, &[]).unwrap() { let book = Book::from_row(row); books.push(book); } let response = jsonapi::json_collection_wrapped_in("data", books); Ok(Response::with((status::Ok, Header(jsonapi::jsonapi_content_type()), response))) } pub fn related(req: &mut Request) -> IronResult<Response> { let book_id = iron_helpers::extract_param_from_path(req, "book_id"); let book_uuid = Uuid::parse_str(&book_id).unwrap(); let pool = req.get::<Read<::AppDb>>().unwrap(); let conn = pool.get().unwrap(); let sql = "SELECT book_id, title, author, description, isbn, price, pages, \ slug, cover_image FROM books WHERE book_id != $1 ORDER BY random() LIMIT 5"; let mut books: Vec<Book> = Vec::new(); for row in &conn.query(&sql, &[&book_uuid]).unwrap() { let book = Book::from_row(row); books.push(book); } let response = jsonapi::json_collection_wrapped_in("data", books); Ok(Response::with((status::Ok, Header(jsonapi::jsonapi_content_type()), response))) } pub fn show(req: &mut Request) -> IronResult<Response> { let book_id = iron_helpers::extract_param_from_path(req, "book_id"); let book_uuid = Uuid::parse_str(&book_id).unwrap(); let pool = req.get::<Read<::AppDb>>().unwrap(); let conn = pool.get().unwrap(); let stmt = conn.prepare("SELECT book_id, title, author, description, isbn, price, pages, \ slug, cover_image FROM books WHERE book_id=$1").unwrap(); let rows = stmt.query(&[&book_uuid]).unwrap(); let book = extract_book(rows); if book.is_none() { Ok(Response::with((status::NotFound, Header(ContentType::json())))) } else { let response = jsonapi::json_wrapped_in("data", book.unwrap()); Ok(Response::with((status::Ok, Header(jsonapi::jsonapi_content_type()), response))) } } fn extract_book(rows: Rows) -> Option<Book> { if rows.len() == 0 { return None; } else { let row = rows.iter().next().unwrap(); let book = Book::from_row(row); return Some(book); } }
use crate::headers::from_headers::*; use crate::prelude::*; use crate::resources::Database; use crate::ResourceQuota; use azure_core::headers::{etag_from_headers, session_token_from_headers}; use azure_core::{collect_pinned_stream, Request as HttpRequest, Response as HttpResponse}; use chrono::{DateTime, Utc}; #[derive(Debug, Clone)] pub struct CreateDatabaseOptions { consistency_level: Option<ConsistencyLevel>, } impl CreateDatabaseOptions { pub fn new() -> Self { Self { consistency_level: None, } } setters! { consistency_level: ConsistencyLevel => Some(consistency_level), } } impl CreateDatabaseOptions { pub(crate) fn decorate_request( &self, request: &mut HttpRequest, database_name: &str, ) -> crate::Result<()> { #[derive(Serialize)] struct CreateDatabaseRequest<'a> { pub id: &'a str, } let req = CreateDatabaseRequest { id: database_name }; azure_core::headers::add_optional_header2(&self.consistency_level, request)?; request.set_body(bytes::Bytes::from(serde_json::to_string(&req)?).into()); Ok(()) } } #[derive(Debug, Clone, PartialEq, PartialOrd)] pub struct CreateDatabaseResponse { pub database: Database, pub charge: f64, pub etag: String, pub session_token: String, pub last_state_change: DateTime<Utc>, pub resource_quota: Vec<ResourceQuota>, pub resource_usage: Vec<ResourceQuota>, pub quorum_acked_lsn: u64, pub current_write_quorum: u64, pub current_replica_set_size: u64, pub schema_version: String, pub service_version: String, pub activity_id: uuid::Uuid, pub gateway_version: String, } impl CreateDatabaseResponse { pub async fn try_from(response: HttpResponse) -> crate::Result<Self> { let (_status_code, headers, pinned_stream) = response.deconstruct(); let body = collect_pinned_stream(pinned_stream).await?; Ok(Self { database: serde_json::from_slice(&body)?, charge: request_charge_from_headers(&headers)?, etag: etag_from_headers(&headers)?, session_token: session_token_from_headers(&headers)?, last_state_change: last_state_change_from_headers(&headers)?, resource_quota: resource_quota_from_headers(&headers)?, resource_usage: resource_usage_from_headers(&headers)?, quorum_acked_lsn: quorum_acked_lsn_from_headers(&headers)?, current_write_quorum: current_write_quorum_from_headers(&headers)?, current_replica_set_size: current_replica_set_size_from_headers(&headers)?, schema_version: schema_version_from_headers(&headers)?.to_owned(), service_version: service_version_from_headers(&headers)?.to_owned(), activity_id: activity_id_from_headers(&headers)?, gateway_version: gateway_version_from_headers(&headers)?.to_owned(), }) } }
extern crate chrono; use chrono::Utc; use jsonwebtoken::{decode, encode, Header, Validation}; use rand::{Rng, thread_rng}; use rand::distributions::Alphanumeric; use rocket::http::Status; use crate::mongodb::db::ThreadedDatabase; use crate::user::{get_user, get_username_with_token, User}; use crate::utils::mongo::connect_mongodb; #[derive(Debug, PartialEq, Clone, Serialize, Deserialize)] struct Claims { exp: i64, } pub fn create_token(_username: String) -> String { let my_claims = Claims { exp: Utc::now().timestamp() + 3600, }; let mut header = Header::default(); header.kid = Some(_username.clone()); let token = encode(&header, &my_claims, "secret_salty_encoded_string".as_ref()).unwrap(); token } pub fn decode_token(_token: String) -> Result<User, Status> { match decode::<Claims>(&_token, "secret_salty_encoded_string".as_ref(), &Validation::default()) { Ok(_t) => return Ok(get_user(_t.header.kid.unwrap().to_string())), Err(_e) => return Err(Status::Unauthorized), }; } pub fn change_user_refresh_token(_refresh_token: String) -> (String, String) { let db: std::sync::Arc<mongodb::db::DatabaseInner> = connect_mongodb(); let collection = db.collection("users"); let _rng = thread_rng(); let username = get_username_with_token(_refresh_token.clone()); let document = doc! { "refresh_token" => _refresh_token.clone() }; let token_refreshed: String = thread_rng() .sample_iter(&Alphanumeric) .take(30) .collect(); let updt = doc! { "$set": { "refresh_token": token_refreshed.clone() } }; collection.update_one(document, updt, None).unwrap(); let access_token = create_token(username.clone()); (token_refreshed, access_token) } pub fn generate_first_refresh_token(_username: String) -> String { let db: std::sync::Arc<mongodb::db::DatabaseInner> = connect_mongodb(); let collection = db.collection("users"); let _rng = rand::thread_rng(); let document = doc! { "username" => _username }; let token_refreshed: String = thread_rng() .sample_iter(&Alphanumeric) .take(30) .collect(); let updt = doc! { "$set": { "refresh_token": token_refreshed.clone() } }; collection.update_one(document, updt, None).unwrap(); token_refreshed }
const BIT_NOISE1: u64 = 0xB5297A4D; const BIT_NOISE2: u64 = 0x68E31DA4; const BIT_NOISE3: u64 = 0x1B56C4E9; fn squirrel3(position: u64, seed: u64) -> u64 { let mut mangled = position; mangled = mangled.wrapping_mul(BIT_NOISE1); mangled = mangled.wrapping_add(seed); mangled ^= mangled >> 8; mangled = mangled.wrapping_add(BIT_NOISE2); mangled ^= mangled << 8; mangled = mangled.wrapping_mul(BIT_NOISE3); mangled ^= mangled >> 8; return mangled; } pub fn noise_1d(x: u64, seed: u64) -> u64 { return squirrel3(x, seed); } const PRIME_Y: u64 = 14536142487739796659; const PRIME_Z: u64 = 17330241684369242527; pub fn noise_2d(x: u64, y: u64, seed: u64) -> u64 { return squirrel3(x.wrapping_add(y.wrapping_mul(PRIME_Y)), seed); } pub fn noise_3d(x: u64, y: u64, z: u64, seed: u64) -> u64 { return squirrel3(x.wrapping_add(y.wrapping_mul(PRIME_Y)).wrapping_add(z.wrapping_mul(PRIME_Z)), seed); } pub fn noise_1d_f64_normalized(x: f64, seed: u64) -> f64 { return (squirrel3(x as u64, seed) as f64) / (u64::MAX as f64); } pub fn noise_3d_f64_normalized(x: u64, y: u64, z: u64, seed: u64) -> f64 { return (noise_3d(x, y, z, seed) as f64) / (u64::MAX as f64); } #[cfg(test)] mod tests { extern crate test; use test::Bencher; #[test] fn squirrel3_tests() { let seed = 55u64; assert_eq!(12687927802791220436, crate::noise::squirrel3(1, seed)); let seed = 56u64; assert_eq!(12687927848928216793, crate::noise::squirrel3(1, seed)); let seed = 0u64; assert_eq!(3033592379929695938, crate::noise::squirrel3(0, seed)); } #[bench] fn noise_1d(b: &mut Bencher) { let mut seed = test::black_box(1000); b.iter(|| { for _ in 1..=128 { let y= [ crate::noise::noise_1d(12687927802791220436, seed), crate::noise::noise_1d(12687927802791220437, seed), crate::noise::noise_1d(12687927802791220438, seed), crate::noise::noise_1d(12687927802791220439, seed), crate::noise::noise_1d(12687927802791220440, seed), crate::noise::noise_1d(12687927802791220441, seed), crate::noise::noise_1d(12687927802791220442, seed), crate::noise::noise_1d(12687927802791220443, seed), ]; seed = y[0]; } }); } #[bench] fn perlin_2d(b: &mut Bencher) { let seed = test::black_box(1000); b.iter(|| { simdnoise::NoiseBuilder::fbm_2d(1024, 1024).with_seed(seed).generate_scaled(0.0, 1.0); }); } }
// If even x 2 , if odd x 3 +1 ---> should end with 4,2,1. //TESTS //collatz(5) => [5,16,8,4,2,1] //collatz(12) => [12,6,3,10,5,16,8,4,2,1] use std::io; fn main() { println!("To test the Collatz Conjeture, please, type a number:"); let mut input_01 = String::new(); io::stdin() .read_line(&mut input_01) .expect("Failed to read line"); let mut input_01: i32 = input_01.trim().parse().expect("Please type a number!"); let mut collatz: Vec<i32> = Vec::new(); println!("The Collatz Conjeture for {} is:", input_01); loop{ if collatz.contains(&input_01) { println!("{:?}", collatz); break } else{ collatz.push(input_01); if input_01 % 2 == 0{ input_01 = input_01 / 2; } else { input_01 = (input_01 * 3) + 1; } } } }
use futures::stream::StreamExt; use kube::Resource; use kube::ResourceExt; use kube::{api::ListParams, client::Client, Api}; use kube_runtime::controller::{Context, ReconcilerAction}; use kube_runtime::Controller; use tokio::time::Duration; use crate::crd::Echo; pub mod crd; mod echo; mod finalizer; #[tokio::main] async fn main() { // First, a Kubernetes client must be obtained using the `kube` crate // The client will later be moved to the custom controller let kubernetes_client: Client = Client::try_default() .await .expect("Expected a valid KUBECONFIG environment variable."); // Preparation of resources used by the `kube_runtime::Controller` let crd_api: Api<Echo> = Api::all(kubernetes_client.clone()); let context: Context<ContextData> = Context::new(ContextData::new(kubernetes_client.clone())); // The controller comes from the `kube_runtime` crate and manages the reconciliation process. // It requires the following information: // - `kube::Api<T>` this controller "owns". In this case, `T = Echo`, as this controller owns the `Echo` resource, // - `kube::api::ListParams` to select the `Echo` resources with. Can be used for Echo filtering `Echo` resources before reconciliation, // - `reconcile` function with reconciliation logic to be called each time a resource of `Echo` kind is created/updated/deleted, // - `on_error` function to call whenever reconciliation fails. Controller::new(crd_api.clone(), ListParams::default()) .run(reconcile, on_error, context) .for_each(|reconciliation_result| async move { match reconciliation_result { Ok(echo_resource) => { println!("Reconciliation successful. Resource: {:?}", echo_resource); } Err(reconciliation_err) => { eprintln!("Reconciliation error: {:?}", reconciliation_err) } } }) .await; } /// Context injected with each `reconcile` and `on_error` method invocation. struct ContextData { /// Kubernetes client to make Kubernetes API requests with. Required for K8S resource management. client: Client, } impl ContextData { /// Constructs a new instance of ContextData. /// /// # Arguments: /// - `client`: A Kubernetes client to make Kubernetes REST API requests with. Resources /// will be created and deleted with this client. pub fn new(client: Client) -> Self { ContextData { client } } } /// Action to be taken upon an `Echo` resource during reconciliation enum Action { /// Create the subresources, this includes spawning `n` pods with Echo service Create, /// Delete all subresources created in the `Create` phase Delete, /// This `Echo` resource is in desired state and requires no actions to be taken NoOp, } async fn reconcile(echo: Echo, context: Context<ContextData>) -> Result<ReconcilerAction, Error> { let client: Client = context.get_ref().client.clone(); // The `Client` is shared -> a clone from the reference is obtained // The resource of `Echo` kind is required to have a namespace set. However, it is not guaranteed // the resource will have a `namespace` set. Therefore, the `namespace` field on object's metadata // is optional and Rust forces the programmer to check for it's existence first. let namespace: String = match echo.namespace() { None => { // If there is no namespace to deploy to defined, reconciliation ends with an error immediately. return Err(Error::UserInputError( "Expected Echo resource to be namespaced. Can't deploy to an unknown namespace." .to_owned(), )); } // If namespace is known, proceed. In a more advanced version of the operator, perhaps // the namespace could be checked for existence first. Some(namespace) => namespace, }; // Performs action as decided by the `determine_action` function. return match determine_action(&echo) { Action::Create => { // Creates a deployment with `n` Echo service pods, but applies a finalizer first. // Finalizer is applied first, as the operator might be shut down and restarted // at any time, leaving subresources in intermediate state. This prevents leaks on // the `Echo` resource deletion. let name = echo.name(); // Name of the Echo resource is used to name the subresources as well. // Apply the finalizer first. If that fails, the `?` operator invokes automatic conversion // of `kube::Error` to the `Error` defined in this crate. finalizer::add(client.clone(), &name, &namespace).await?; // Invoke creation of a Kubernetes built-in resource named deployment with `n` echo service pods. echo::deploy(client, &echo.name(), echo.spec.replicas, &namespace).await?; Ok(ReconcilerAction { // Finalizer is added, deployment is deployed, re-check in 10 seconds. requeue_after: Some(Duration::from_secs(10)), }) } Action::Delete => { // Deletes any subresources related to this `Echo` resources. If and only if all subresources // are deleted, the finalizer is removed and Kubernetes is free to remove the `Echo` resource. //First, delete the deployment. If there is any error deleting the deployment, it is // automatically converted into `Error` defined in this crate and the reconciliation is ended // with that error. // Note: A more advanced implementation would for the Deployment's existence. echo::delete(client.clone(), &echo.name(), &namespace).await?; // Once the deployment is successfully removed, remove the finalizer to make it possible // for Kubernetes to delete the `Echo` resource. finalizer::delete(client, &echo.name(), &namespace).await?; Ok(ReconcilerAction { requeue_after: None, // Makes no sense to delete after a successful delete, as the resource is gone }) } Action::NoOp => Ok(ReconcilerAction { // The resource is already in desired state, do nothing and re-check after 10 seconds requeue_after: Some(Duration::from_secs(10)), }), }; } /// Resources arrives into reconciliation queue in a certain state. This function looks at /// the state of given `Echo` resource and decides which actions needs to be performed. /// The finite set of possible actions is represented by the `Action` enum. /// /// # Arguments /// - `echo`: A reference to `Echo` being reconciled to decide next action upon. fn determine_action(echo: &Echo) -> Action { return if echo.meta().deletion_timestamp.is_some() { Action::Delete } else if echo .meta() .finalizers .as_ref() .map_or(true, |finalizers| finalizers.is_empty()) { Action::Create } else { Action::NoOp }; } /// Actions to be taken when a reconciliation fails - for whatever reason. /// Prints out the error to `stderr` and requeues the resource for another reconciliation after /// five seconds. /// /// # Arguments /// - `error`: A reference to the `kube::Error` that occurred during reconciliation. /// - `_context`: Unused argument. Context Data "injected" automatically by kube-rs. fn on_error(error: &Error, _context: Context<ContextData>) -> ReconcilerAction { eprintln!("Reconciliation error:\n{:?}", error); ReconcilerAction { requeue_after: Some(Duration::from_secs(5)), } } /// All errors possible to occur during reconciliation #[derive(Debug, thiserror::Error)] pub enum Error { /// Any error originating from the `kube-rs` crate #[error("Kubernetes reported error: {source}")] KubeError { #[from] source: kube::Error, }, /// Error in user input or Echo resource definition, typically missing fields. #[error("Invalid Echo CRD: {0}")] UserInputError(String), }
extern crate chrono; extern crate hostname; extern crate serde; extern crate serde_json; extern crate uuid; use chrono::{DateTime, FixedOffset}; use hostname::get_hostname; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use uuid::Uuid; use crate::event::SpecVersion; use crate::event::Payload; const DEFAULT_TYPE: &str = "generated.cloudevents-sdk"; const DEFAULT_SOURCE: &str = "cloudevents.io"; #[derive(Serialize, Deserialize, PartialEq, Debug, Clone, Builder)] #[builder(setter(into, strip_option))] pub struct Event { #[builder(default = "Uuid::new_v4().to_string()")] pub id: String, #[builder(default = "get_hostname().unwrap_or(DEFAULT_SOURCE.to_string())")] pub source: String, #[builder(default = "SpecVersion::V10")] #[serde(rename = "specversion")] pub spec_version: SpecVersion, #[builder(default = "DEFAULT_TYPE.to_string()")] #[serde(rename = "type")] pub event_type: String, #[builder(default)] #[serde(skip_serializing_if = "Option::is_none")] pub subject: Option<String>, #[builder(default)] #[serde(skip_serializing_if = "Option::is_none")] pub time: Option<DateTime<FixedOffset>>, #[serde(flatten)] #[builder(default)] #[serde(skip_serializing_if = "Option::is_none")] pub payload: Option<Payload>, #[serde(flatten)] #[builder(default)] pub extensions: HashMap<String, String>, } #[allow(non_snake_case)] impl Event { pub fn new() -> Event { return EventBuilder::default().build().unwrap(); } }
#[doc = "Register `MISR` reader"] pub type R = crate::R<MISR_SPEC>; #[doc = "Field `ALRAMF` reader - Alarm A masked flag This flag is set by hardware when the alarm A non-secure interrupt occurs."] pub type ALRAMF_R = crate::BitReader; #[doc = "Field `ALRBMF` reader - Alarm B non-secure masked flag This flag is set by hardware when the alarm B non-secure interrupt occurs."] pub type ALRBMF_R = crate::BitReader; #[doc = "Field `WUTMF` reader - Wakeup timer non-secure masked flag This flag is set by hardware when the wakeup timer non-secure interrupt occurs. This flag must be cleared by software at least 1.5 RTCCLK periods before WUTF is set to 1 again."] pub type WUTMF_R = crate::BitReader; #[doc = "Field `TSMF` reader - Timestamp non-secure masked flag This flag is set by hardware when a timestamp non-secure interrupt occurs. If ITSF flag is set, TSF must be cleared together with ITSF."] pub type TSMF_R = crate::BitReader; #[doc = "Field `TSOVMF` reader - Timestamp overflow non-secure masked flag This flag is set by hardware when a timestamp interrupt occurs while TSMF is already set. It is recommended to check and then clear TSOVF only after clearing the TSF bit. Otherwise, an overflow might not be noticed if a timestamp event occurs immediately before the TSF bit is cleared."] pub type TSOVMF_R = crate::BitReader; #[doc = "Field `ITSMF` reader - Internal timestamp non-secure masked flag This flag is set by hardware when a timestamp on the internal event occurs and timestamp non-secure interrupt is raised."] pub type ITSMF_R = crate::BitReader; #[doc = "Field `SSRUMF` reader - SSR underflow non-secure masked flag This flag is set by hardware when the SSR underflow non-secure interrupt occurs."] pub type SSRUMF_R = crate::BitReader; impl R { #[doc = "Bit 0 - Alarm A masked flag This flag is set by hardware when the alarm A non-secure interrupt occurs."] #[inline(always)] pub fn alramf(&self) -> ALRAMF_R { ALRAMF_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - Alarm B non-secure masked flag This flag is set by hardware when the alarm B non-secure interrupt occurs."] #[inline(always)] pub fn alrbmf(&self) -> ALRBMF_R { ALRBMF_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - Wakeup timer non-secure masked flag This flag is set by hardware when the wakeup timer non-secure interrupt occurs. This flag must be cleared by software at least 1.5 RTCCLK periods before WUTF is set to 1 again."] #[inline(always)] pub fn wutmf(&self) -> WUTMF_R { WUTMF_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - Timestamp non-secure masked flag This flag is set by hardware when a timestamp non-secure interrupt occurs. If ITSF flag is set, TSF must be cleared together with ITSF."] #[inline(always)] pub fn tsmf(&self) -> TSMF_R { TSMF_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 4 - Timestamp overflow non-secure masked flag This flag is set by hardware when a timestamp interrupt occurs while TSMF is already set. It is recommended to check and then clear TSOVF only after clearing the TSF bit. Otherwise, an overflow might not be noticed if a timestamp event occurs immediately before the TSF bit is cleared."] #[inline(always)] pub fn tsovmf(&self) -> TSOVMF_R { TSOVMF_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - Internal timestamp non-secure masked flag This flag is set by hardware when a timestamp on the internal event occurs and timestamp non-secure interrupt is raised."] #[inline(always)] pub fn itsmf(&self) -> ITSMF_R { ITSMF_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 6 - SSR underflow non-secure masked flag This flag is set by hardware when the SSR underflow non-secure interrupt occurs."] #[inline(always)] pub fn ssrumf(&self) -> SSRUMF_R { SSRUMF_R::new(((self.bits >> 6) & 1) != 0) } } #[doc = "RTC non-secure masked interrupt status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`misr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct MISR_SPEC; impl crate::RegisterSpec for MISR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`misr::R`](R) reader structure"] impl crate::Readable for MISR_SPEC {} #[doc = "`reset()` method sets MISR to value 0"] impl crate::Resettable for MISR_SPEC { const RESET_VALUE: Self::Ux = 0; }
#[doc = "RCB LL control register.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [ctrl](ctrl) module"] pub type CTRL = crate::Reg<u32, _CTRL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _CTRL; #[doc = "`read()` method returns [ctrl::R](ctrl::R) reader structure"] impl crate::Readable for CTRL {} #[doc = "`write(|w| ..)` method takes [ctrl::W](ctrl::W) writer structure"] impl crate::Writable for CTRL {} #[doc = "RCB LL control register."] pub mod ctrl; #[doc = "Master interrupt request register.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [intr](intr) module"] pub type INTR = crate::Reg<u32, _INTR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _INTR; #[doc = "`read()` method returns [intr::R](intr::R) reader structure"] impl crate::Readable for INTR {} #[doc = "`write(|w| ..)` method takes [intr::W](intr::W) writer structure"] impl crate::Writable for INTR {} #[doc = "Master interrupt request register."] pub mod intr; #[doc = "Master interrupt set request register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [intr_set](intr_set) module"] pub type INTR_SET = crate::Reg<u32, _INTR_SET>; #[allow(missing_docs)] #[doc(hidden)] pub struct _INTR_SET; #[doc = "`read()` method returns [intr_set::R](intr_set::R) reader structure"] impl crate::Readable for INTR_SET {} #[doc = "`write(|w| ..)` method takes [intr_set::W](intr_set::W) writer structure"] impl crate::Writable for INTR_SET {} #[doc = "Master interrupt set request register"] pub mod intr_set; #[doc = "Master interrupt mask register.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [intr_mask](intr_mask) module"] pub type INTR_MASK = crate::Reg<u32, _INTR_MASK>; #[allow(missing_docs)] #[doc(hidden)] pub struct _INTR_MASK; #[doc = "`read()` method returns [intr_mask::R](intr_mask::R) reader structure"] impl crate::Readable for INTR_MASK {} #[doc = "`write(|w| ..)` method takes [intr_mask::W](intr_mask::W) writer structure"] impl crate::Writable for INTR_MASK {} #[doc = "Master interrupt mask register."] pub mod intr_mask; #[doc = "Master interrupt masked request register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [intr_masked](intr_masked) module"] pub type INTR_MASKED = crate::Reg<u32, _INTR_MASKED>; #[allow(missing_docs)] #[doc(hidden)] pub struct _INTR_MASKED; #[doc = "`read()` method returns [intr_masked::R](intr_masked::R) reader structure"] impl crate::Readable for INTR_MASKED {} #[doc = "Master interrupt masked request register"] pub mod intr_masked; #[doc = "Address of Register#1 in Radio (MDON)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [radio_reg1_addr](radio_reg1_addr) module"] pub type RADIO_REG1_ADDR = crate::Reg<u32, _RADIO_REG1_ADDR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _RADIO_REG1_ADDR; #[doc = "`read()` method returns [radio_reg1_addr::R](radio_reg1_addr::R) reader structure"] impl crate::Readable for RADIO_REG1_ADDR {} #[doc = "`write(|w| ..)` method takes [radio_reg1_addr::W](radio_reg1_addr::W) writer structure"] impl crate::Writable for RADIO_REG1_ADDR {} #[doc = "Address of Register#1 in Radio (MDON)"] pub mod radio_reg1_addr; #[doc = "Address of Register#2 in Radio (RSSI)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [radio_reg2_addr](radio_reg2_addr) module"] pub type RADIO_REG2_ADDR = crate::Reg<u32, _RADIO_REG2_ADDR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _RADIO_REG2_ADDR; #[doc = "`read()` method returns [radio_reg2_addr::R](radio_reg2_addr::R) reader structure"] impl crate::Readable for RADIO_REG2_ADDR {} #[doc = "`write(|w| ..)` method takes [radio_reg2_addr::W](radio_reg2_addr::W) writer structure"] impl crate::Writable for RADIO_REG2_ADDR {} #[doc = "Address of Register#2 in Radio (RSSI)"] pub mod radio_reg2_addr; #[doc = "Address of Register#3 in Radio (ACCL)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [radio_reg3_addr](radio_reg3_addr) module"] pub type RADIO_REG3_ADDR = crate::Reg<u32, _RADIO_REG3_ADDR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _RADIO_REG3_ADDR; #[doc = "`read()` method returns [radio_reg3_addr::R](radio_reg3_addr::R) reader structure"] impl crate::Readable for RADIO_REG3_ADDR {} #[doc = "`write(|w| ..)` method takes [radio_reg3_addr::W](radio_reg3_addr::W) writer structure"] impl crate::Writable for RADIO_REG3_ADDR {} #[doc = "Address of Register#3 in Radio (ACCL)"] pub mod radio_reg3_addr; #[doc = "Address of Register#4 in Radio (ACCH)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [radio_reg4_addr](radio_reg4_addr) module"] pub type RADIO_REG4_ADDR = crate::Reg<u32, _RADIO_REG4_ADDR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _RADIO_REG4_ADDR; #[doc = "`read()` method returns [radio_reg4_addr::R](radio_reg4_addr::R) reader structure"] impl crate::Readable for RADIO_REG4_ADDR {} #[doc = "`write(|w| ..)` method takes [radio_reg4_addr::W](radio_reg4_addr::W) writer structure"] impl crate::Writable for RADIO_REG4_ADDR {} #[doc = "Address of Register#4 in Radio (ACCH)"] pub mod radio_reg4_addr; #[doc = "Address of Register#5 in Radio (RSSI ENERGY)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [radio_reg5_addr](radio_reg5_addr) module"] pub type RADIO_REG5_ADDR = crate::Reg<u32, _RADIO_REG5_ADDR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _RADIO_REG5_ADDR; #[doc = "`read()` method returns [radio_reg5_addr::R](radio_reg5_addr::R) reader structure"] impl crate::Readable for RADIO_REG5_ADDR {} #[doc = "`write(|w| ..)` method takes [radio_reg5_addr::W](radio_reg5_addr::W) writer structure"] impl crate::Writable for RADIO_REG5_ADDR {} #[doc = "Address of Register#5 in Radio (RSSI ENERGY)"] pub mod radio_reg5_addr; #[doc = "N/A\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [cpu_write_reg](cpu_write_reg) module"] pub type CPU_WRITE_REG = crate::Reg<u32, _CPU_WRITE_REG>; #[allow(missing_docs)] #[doc(hidden)] pub struct _CPU_WRITE_REG; #[doc = "`read()` method returns [cpu_write_reg::R](cpu_write_reg::R) reader structure"] impl crate::Readable for CPU_WRITE_REG {} #[doc = "`write(|w| ..)` method takes [cpu_write_reg::W](cpu_write_reg::W) writer structure"] impl crate::Writable for CPU_WRITE_REG {} #[doc = "N/A"] pub mod cpu_write_reg; #[doc = "N/A\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [cpu_read_reg](cpu_read_reg) module"] pub type CPU_READ_REG = crate::Reg<u32, _CPU_READ_REG>; #[allow(missing_docs)] #[doc(hidden)] pub struct _CPU_READ_REG; #[doc = "`read()` method returns [cpu_read_reg::R](cpu_read_reg::R) reader structure"] impl crate::Readable for CPU_READ_REG {} #[doc = "`write(|w| ..)` method takes [cpu_read_reg::W](cpu_read_reg::W) writer structure"] impl crate::Writable for CPU_READ_REG {} #[doc = "N/A"] pub mod cpu_read_reg;
extern crate plotters; use chrono::DateTime; use plotters::prelude::*; use serde::Deserialize; use std::env; #[derive(Debug, PartialOrd, PartialEq, Clone, Default, Deserialize)] struct YfRow { symb: String, t: f32, o: f32, h: f32, l: f32, c: f32, v: u64, } #[derive(Debug, PartialOrd, PartialEq, Clone, Default, Deserialize)] struct RtRow { symbol: String, t: String, x: f32, v: u64, } fn main() -> Result<(), Box<dyn std::error::Error>> { let args = env::args().collect::<Vec<String>>(); if args.len() != 3 { panic!("arg 2: folder, arg 3: file_name. this looks in ../data/"); } let input_fold = args[1].clone(); let input_fn = args[2].clone(); //let data: Vec<YfRow> = get_data(&input_fold, &input_fn); let data: Vec<RtRow> = get_data(&input_fold, &input_fn); let xs = data.iter().map(|x| x.x).collect::<Vec<f32>>(); let ts = data .iter() .map(|x| DateTime::parse_from_rfc3339(&x.t).unwrap().timestamp()) .collect::<Vec<i64>>(); //let closes = data.iter().map(|x| x.c).collect::<Vec<f32>>(); //let min = let plot_fn = format!("../data/viz/{}.png", input_fn); let root = BitMapBackend::new(&plot_fn, (640, 480)).into_drawing_area(); root.fill(&WHITE)?; let mut chart = ChartBuilder::on(&root) .caption(input_fn, ("sans-serif", 50).into_font()) .margin(5) .x_label_area_size(30) .y_label_area_size(30) .build_ranged( ts[0]..ts[data.len() - 1], //closes[0]..closes[closes.len() - 1], xs[0]..xs[xs.len() - 1], )?; let to_plot = data .iter() .map(|x| (DateTime::parse_from_rfc3339(&x.t).unwrap().timestamp(), x.x)) .into_iter(); chart.configure_mesh().draw()?; let series = LineSeries::new(to_plot, &RED); chart.draw_series(series); //chart // .draw_series(data.iter().map(|x| { // CandleStick::new( // //DateTime::parse_from_rfc3339(x.t).unwrap_or(panic!("fuck dates")), // x.t, x.o, x.h, x.l, x.c, &GREEN, &RED, 15, // ) // }))? // .label("y = x^2") // .legend(|(x, y)| PathElement::new(vec![(x, y), (x + 20, y)], &RED)); chart .configure_series_labels() .background_style(&WHITE.mix(0.8)) .border_style(&BLACK) .draw()?; Ok(()) } pub fn get_data<'a, T: ?Sized>(folder: &str, file_name: &str) -> Vec<T> where for<'de> T: serde::Deserialize<'de> + 'a, { let file_name_fmtd = format!("../data/{}/{}", folder, file_name); let mut rdr = csv::Reader::from_path(file_name_fmtd.clone()).expect(&file_name_fmtd); let iter = rdr.deserialize(); let mut recs = vec![]; for res in iter { if let Ok(r) = res { let rec: T = r; recs.push(rec); } } recs }
#!/usr/local/bin/rust run /** The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? */ extern mod extra; use std::*; fn main(){ let startnum = 13195; let mut result = startnum; let mut value = 1; loop{ value += 1; if value >= result{ break; } while result % value == 0{ println(fmt!("%u is divisible by %u", result, value)); result = result / value; } } println(fmt!("The Largest Factor is: %u", result)); }
use std::borrow::Borrow; use bytes::{Buf, BufMut, BytesMut}; use dencode::{Decoder, Encoder, FramedRead, FramedWrite}; use crate::{ messages::{SBPMessage, SBP}, parser::{parse_sbp, ParseResult}, Error, Result, }; const MAX_FRAME_LENGTH: usize = crate::MSG_HEADER_LEN + crate::SBP_MAX_PAYLOAD_SIZE + crate::MSG_CRC_LEN; const PREAMBLE: u8 = 0x55; #[cfg(feature = "async")] pub fn stream_messages<R: futures::AsyncRead + Unpin>( input: R, ) -> impl futures::Stream<Item = Result<SBP>> { FramedRead::new(input, SbpDecoder::new()) } pub fn iter_messages<R: std::io::Read>(input: R) -> impl Iterator<Item = Result<SBP>> { FramedRead::new(input, SbpDecoder::new()) } pub struct SbpDecoder {} impl SbpDecoder { pub fn new() -> Self { Self {} } } impl Decoder for SbpDecoder { type Item = SBP; type Error = Error; fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>> { let start = match src.iter().position(|b| b == &PREAMBLE) { Some(idx) => idx, None => { src.clear(); return Ok(None); } }; src.advance(start); match parse_sbp(&src) { ParseResult::Ok((bytes_read, msg)) => { src.advance(bytes_read); log::trace!("{:?}", msg); Ok(Some(msg)) } ParseResult::Err((bytes_read, err)) => { src.advance(bytes_read); Err(err) } ParseResult::Incomplete => { src.reserve(MAX_FRAME_LENGTH); Ok(None) } } } fn decode_eof(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>> { let res = match self.decode(buf) { Ok(Some(frame)) => Ok(Some(frame)), _ => Ok(None), }; buf.clear(); res } } pub struct SbpEncoder { frame: Vec<u8>, } impl SbpEncoder { pub fn new() -> Self { SbpEncoder { frame: Vec::with_capacity(MAX_FRAME_LENGTH), } } pub fn framed<W>(writer: W) -> FramedWrite<W, Self> { FramedWrite::new(writer, Self::new()) } } impl<T> Encoder<T> for SbpEncoder where T: Borrow<SBP>, { type Error = Error; fn encode(&mut self, msg: T, dst: &mut BytesMut) -> Result<()> { self.frame.clear(); match msg.borrow().write_frame(&mut self.frame) { Ok(_) => dst.put_slice(self.frame.as_slice()), Err(err) => log::error!("Error converting sbp message to frame: {}", err), } Ok(()) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_parse_nothing() { let mut decoder = SbpDecoder::new(); let data = vec![0u8; 1000]; let mut bytes = BytesMut::from(&data[..]); assert_eq!(bytes.len(), 1000); assert!(matches!(decoder.decode(&mut bytes), Ok(None))); assert!(bytes.is_empty()); } }
use mio::{Ready, Registration}; use std::{ io::{self, prelude::*}, sync::mpsc::{self, Receiver}, thread }; pub struct MioStdin { pub reg: Registration, pub rx: Receiver<Vec<u8>> } impl MioStdin { pub fn new() -> Self { let (reg, control) = Registration::new2(); let (tx, rx) = mpsc::channel(); thread::spawn(move || { let stdin = io::stdin(); let mut stdin = stdin.lock(); let mut buf = [0; 1024]; while let Ok(read) = stdin.read(&mut buf) { if read == 0 { break; } tx.send(buf[..read].to_vec()).unwrap(); control.set_readiness(Ready::readable()).unwrap(); } }); Self { reg, rx } } }
use std::collections::{HashMap, HashSet, BinaryHeap, VecDeque}; use std::collections::hash_map::Entry; use crate::data::component::{Component, PortType, StateChange}; use crate::data::subnet::{Subnet, SubnetState}; use std::cmp::Reverse; pub(crate) mod subnet; pub(crate) mod component; #[cfg(test)] mod test; /// Struct to represent the data that the backend should keep track of #[derive(Debug)] pub struct Data { components: HashMap<i32, (Box<dyn Component>, Vec<SubnetState>)>, // should be an option components_free: BinaryHeap<Reverse<i32>>, subnets: HashMap<i32, Subnet>, // <id, subnet> subnet_edges: HashMap<i32, HashSet<Edge>>, component_edges: HashMap<i32, HashSet<Edge>>, clocks: Vec<i32>, simulation: Simulator, } impl Data { pub fn new() -> Self { Self { components: HashMap::new(), components_free: BinaryHeap::new(), subnets: HashMap::new(), subnet_edges: HashMap::new(), component_edges: HashMap::new(), clocks: Vec::new(), simulation: Simulator::new(), } } fn alloc_component(&mut self, component: Box<dyn Component>) -> i32 { let idx = if self.components_free.len() == 0 { self.components.len() as i32 + 1 } else { self.components_free.pop().unwrap().0 }; let ports = component.ports(); assert!(self.components.insert(idx, (component, vec![SubnetState::Floating; ports])).is_none()); idx } pub(crate) fn add_component(&mut self, component: Box<dyn Component>, ports: Vec<Option<i32>>) -> Result<i32, ()> { if ports.len() != component.ports() { return Err(()); } let ports = ports.into_iter() .enumerate() .filter_map(|(i, e)| e.map(|e| (component.port_type(i).unwrap(), i, e))) .collect::<Vec<_>>(); let idx = self.alloc_component(component); for port in ports { assert!(self.link(idx, port.1, port.2)); } Ok(idx) } pub(crate) fn clock(&mut self, clock_id: i32) { self.clocks.push(clock_id); } pub(crate) fn remove_component(&mut self, id: i32) -> bool { if self.components.remove(&id).is_none() { return false; }; self.components_free.push(Reverse(id)); let mut to_remove = Vec::new(); if let Some(edges) = self.component_edges.get(&id) { for edge in edges { to_remove.push(edge.clone()); } } for r in to_remove { self.remove_edge(&r); self.simulation.dirty_subnet(r.subnet); } self.simulation.process_until_clean(&mut self.components, &mut self.subnets, &self.subnet_edges, &self.component_edges); true } pub(crate) fn add_subnet(&mut self, id: i32) -> bool { self.subnets.insert(id, Subnet::new()).is_none() } pub(crate) fn remove_subnet(&mut self, subnet: i32) -> bool { if self.subnets.remove(&subnet).is_none() { return false; } if let Some(edges) = self.subnet_edges.get(&subnet) { let mut to_remove = Vec::new(); for edge in edges { to_remove.push(edge.clone()); } for r in to_remove { self.remove_edge(&r); } } true } pub(crate) fn link(&mut self, component: i32, port: usize, subnet: i32) -> bool { let direction = match self.port_direction_component(component, port) { Some(t) => t, None => return false, }; let mut linked_to = None; for edge in self.component_edges.get(&component).unwrap_or(&HashSet::new()) { if edge.port == port { linked_to = Some(edge.subnet); } } if let Some(old_subnet) = linked_to { self.unlink(component, port, old_subnet); } if !self.add_edge(subnet, component, port, direction) { return false; } self.simulation.update_component(component, &mut self.components, &mut self.subnets, &self.subnet_edges, &self.component_edges); self.simulation.process_until_clean(&mut self.components, &mut self.subnets, &self.subnet_edges, &self.component_edges); true } pub(crate) fn unlink(&mut self, component: i32, port: usize, subnet: i32) -> bool { let direction = match self.port_direction_component(component, port) { Some(t) => t, None => return false, }; if !self.remove_edge(&Edge::new(subnet, component, port, direction)) { return false; } self.simulation.dirty_subnet(subnet); self.simulation.update_component(component, &mut self.components, &mut self.subnets, &self.subnet_edges, &self.component_edges); self.simulation.process_until_clean(&mut self.components, &mut self.subnets, &self.subnet_edges, &self.component_edges); true } pub(crate) fn press_component(&mut self, id: i32) -> SubnetState { let state = self.components.get(&id).unwrap().0.pressed(); self.simulation.update_component(id, &mut self.components, &mut self.subnets, &self.subnet_edges, &self.component_edges); self.simulation.process_until_clean(&mut self.components, &mut self.subnets, &self.subnet_edges, &self.component_edges); return state } pub(crate) fn release_component(&mut self, id: i32) -> SubnetState { let state = self.components.get(&id).unwrap().0.released(); self.simulation.update_component(id, &mut self.components, &mut self.subnets, &self.subnet_edges, &self.component_edges); self.simulation.process_until_clean(&mut self.components, &mut self.subnets, &self.subnet_edges, &self.component_edges); return state } fn add_edge(&mut self, subnet: i32, component: i32, port: usize, direction: EdgeDirection) -> bool { let edge = Edge::new(subnet, component, port, direction); let mut removing = Vec::new(); if let Entry::Occupied(inner) = self.component_edges.entry(component) { let mut same = None; for e in inner.get() { if e.same_nodes(&edge) { same = Some(e.clone()); } if e.component == edge.component && e.port == edge.port && e.subnet != edge.subnet { return false; } } if let Some(same) = same { //This edge already exists removing.push(same.clone()); } } for r in removing { self.remove_edge(&r); } // here, we're guaranteed to not have an edge between the subnet and the component's port // so we can just put in edges without worry of collision self.component_edges.entry(component).or_default().insert(edge.clone()); self.subnet_edges.entry(subnet).or_default().insert(edge); true } fn remove_edge(&mut self, edge: &Edge) -> bool { match self.component_edges.get_mut(&(edge.component)) { Some(t) => t.remove(edge), None => return false, }; self.subnet_edges.get_mut(&(edge.subnet)).unwrap().remove(edge); // If an edge exists in one direction, there should also exist one in the other direction if self.component_edges.get(&(edge.component)).unwrap().len() == 0 { self.component_edges.remove(&(edge.component)); } if self.subnet_edges.get(&(edge.subnet)).unwrap().len() == 0 { self.subnet_edges.remove(&(edge.subnet)); } true } fn port_direction_component(&self, component: i32, port: usize) -> Option<EdgeDirection> { Some(self.components.get(&component)?.0.port_type(port)?.to_edge_direction()) } /// Gets the state of a subnet pub(crate) fn subnet_state(&self, subnet: i32) -> Option<SubnetState> { Some(self.subnets.get(&subnet)?.val()) } /// Gets the state of a subnet which a port is connected to pub(crate) fn port_state(&self, component: i32, port: usize) -> Option<SubnetState> { self.components.get(&component)?.1.get(port).map(|e| *e) } pub(crate) fn time_step(&mut self) { self.simulation.time_step(&self.clocks, &mut self.components, &mut self.subnets, &self.subnet_edges, &self.component_edges); } } #[cfg(test)] impl Data { fn update_subnet(&mut self, subnet: i32, state: SubnetState) { self.simulation.update_subnet(subnet, state, &mut self.subnets); } fn advance_time(&mut self) { self.simulation.advance_time(&mut self.components, &mut self.subnets, &self.subnet_edges, &self.component_edges); } fn update_silent(&mut self, subnet: i32, state: SubnetState) { self.subnets.get_mut(&subnet).unwrap().update(state); } } #[derive(Debug)] struct Simulator { dirty_subnets: VecDeque<HashSet<i32>>, changed_subnets: HashMap<i32, SubnetState>, //<subnet, old state> } impl Simulator { fn new() -> Self { Self { dirty_subnets: VecDeque::new(), changed_subnets: HashMap::new(), } } fn advance_time( &mut self, components: &mut HashMap<i32, (Box<dyn Component>, Vec<SubnetState>)>, subnets: &mut HashMap<i32, Subnet>, subnet_edges: &HashMap<i32, HashSet<Edge>>, component_edges: &HashMap<i32, HashSet<Edge>> ) -> bool { let to_simulate = match self.dirty_subnets.pop_front() { Some(t) => t, None => return false, }; let mut simulating = HashSet::new(); for subnet in &to_simulate { for edge in subnet_edges.get(subnet).unwrap_or(&HashSet::new()) { if edge.direction != EdgeDirection::ToSubnet { simulating.insert(edge.component); } } } let mut old_state = HashMap::new(); std::mem::swap(&mut self.changed_subnets, &mut old_state); let mut to_eval = HashSet::new(); for s in simulating { self.simulate(s, &old_state, components, subnets, component_edges); for edge in component_edges.get(&s).unwrap() { if edge.direction != EdgeDirection::ToComponent { to_eval.insert(edge.subnet); } } } to_eval.extend(to_simulate); let mut diff: HashMap<i32, HashSet<SubnetState>> = HashMap::new(); for evaluating_subnets in to_eval { diff.entry(evaluating_subnets).or_default() .extend(subnet_edges.get(&evaluating_subnets).unwrap_or(&HashSet::new()) .into_iter() .filter(|edge| edge.direction != EdgeDirection::ToComponent) .map(|edge| *components .get(&edge.component) .unwrap() .1 .get(edge.port) .unwrap())); } self.apply_state_diff(diff, subnets); true } /// Takes in a component id and the difference between the old state and the current. Updates /// what each port is driving. It is the responsibility of the caller to use the updated edge /// state fn simulate( &mut self, component: i32, old_state: &HashMap<i32, SubnetState>, components: &mut HashMap<i32, (Box<dyn Component>, Vec<SubnetState>)>, subnets: &HashMap<i32, Subnet>, component_edges: &HashMap<i32, HashSet<Edge>> ) { let comp = components.get_mut(&component).unwrap(); let edges = component_edges.get(&component); let mut searching = HashSet::new(); let mut dirty_ports = HashSet::new(); for (port_idx, port_type) in comp.0.ports_type() .into_iter() .enumerate() { if port_type != PortType::Output { searching.insert(port_idx); } else if port_type != PortType::Input { dirty_ports.insert(port_idx); } } let mut states = HashMap::new(); let mut dirtying = HashMap::new(); for edge in edges.unwrap_or(&HashSet::new()) { if searching.contains(&edge.port) { let val = subnets.get(&edge.subnet).unwrap().val(); let old = match old_state.get(&edge.subnet) { Some(t) => *t, None => val, }; let diff = StateChange::new(old, val); states.insert(edge.port, diff); } else if dirty_ports.contains(&edge.port) { dirtying.insert(edge.port, edge.subnet); } } let res = comp.0.evaluate(states); for (port, state) in res { *comp.1.get_mut(port).unwrap() = state; } } /// Forces a component to update and advances time. Is probably called when the user places a /// components and wants the changes to propagate. Also empties propagates changes until no /// more updates are happening. fn update_component( &mut self, component: i32, components: &mut HashMap<i32, (Box<dyn Component>, Vec<SubnetState>)>, subnets: &mut HashMap<i32, Subnet>, subnet_edges: &HashMap<i32, HashSet<Edge>>, component_edges: &HashMap<i32, HashSet<Edge>> ) { let mut old_state = HashMap::new(); std::mem::swap(&mut old_state, &mut self.changed_subnets); self.simulate(component, &old_state, components, subnets, component_edges); let mut to_eval = HashSet::new(); for edge in component_edges.get(&component).unwrap_or(&HashSet::new()) { if edge.direction != EdgeDirection::ToComponent { to_eval.insert(edge.subnet); } } let mut diff: HashMap<i32, HashSet<SubnetState>> = HashMap::new(); for evaluating_subnets in to_eval { for edge in subnet_edges.get(&evaluating_subnets).unwrap() { if edge.direction != EdgeDirection::ToComponent { diff .entry(evaluating_subnets) .or_default() .insert( *components .get(&edge.component) .unwrap() .1 .get(edge.port) .unwrap() ); } } } self.apply_state_diff(diff, subnets); } /// Takes a change in subnet_state and updates the relevant subnets fn apply_state_diff(&mut self, diff: HashMap<i32, HashSet<SubnetState>>, subnets: &mut HashMap<i32, Subnet>) { for (subnet, proposals) in diff { self.update_subnet(subnet, SubnetState::work_out_diff(&proposals), subnets); } } /// Changes a subnets value and enques it in dirty_subnets if the state changed fn update_subnet(&mut self, subnet: i32, state: SubnetState, subnets: &mut HashMap<i32, Subnet>) { let old_state = subnets.get(&subnet).unwrap().val(); if subnets.get_mut(&subnet).unwrap().update(state) { //we actually changed a subnet if self.dirty_subnets.len() == 0 { //maybe change to account for propagation time self.dirty_subnets.push_back(HashSet::new()); } self.dirty_subnets.get_mut(0).unwrap().insert(subnet); self.changed_subnets.insert(subnet, old_state); } } /// Dirties a subnet fn dirty_subnet(&mut self, subnet: i32) { if self.dirty_subnets.len() == 0 { self.dirty_subnets.push_back(HashSet::new()); } self.dirty_subnets.get_mut(0).unwrap().insert(subnet); } fn process_until_clean( &mut self, components: &mut HashMap<i32, (Box<dyn Component>, Vec<SubnetState>)>, subnets: &mut HashMap<i32, Subnet>, subnet_edges: &HashMap<i32, HashSet<Edge>>, component_edges: &HashMap<i32, HashSet<Edge>> ) -> bool { const MAX_ITERS: i32 = 1000; for _ in 0..MAX_ITERS { if !self.advance_time(components, subnets, subnet_edges, component_edges) { return true; } } false } /// Toggles all clocks fn time_step( &mut self, clocks: &[i32], components: &mut HashMap<i32, (Box<dyn Component>, Vec<SubnetState>)>, subnets: &mut HashMap<i32, Subnet>, subnet_edges: &HashMap<i32, HashSet<Edge>>, component_edges: &HashMap<i32, HashSet<Edge>> ) { let mut updating = Vec::new(); for clock in clocks { updating.push(*clock); } for u in updating { self.update_component(u, components, subnets, subnet_edges, component_edges); } self.process_until_clean(components, subnets, subnet_edges, component_edges); } } /// Stores subnets and components in edge-query format #[derive(Debug, Eq, PartialEq, Clone, Hash)] struct Edge { subnet: i32, component: i32, port: usize, direction: EdgeDirection, } impl Edge { fn new(subnet: i32, component: i32, port: usize, direction: EdgeDirection) -> Self { Self { subnet, component, port, direction } } fn same_nodes(&self, other: &Self) -> bool { self.subnet == other.subnet && self.component == other.component && self.port == other.port } fn add_direction(mut self, direction: EdgeDirection) -> Self { if self.direction == direction { self } else { self.direction = EdgeDirection::Bidirectional; self } } } #[derive(Debug, Eq, PartialEq, Clone, Copy, Hash)] pub(crate) enum EdgeDirection { ToComponent, ToSubnet, Bidirectional, }
use ::file::text::Point; use std::sync::mpsc::Sender; #[derive(Debug, Eq, PartialEq, Hash, Clone, Copy)] pub struct FileThreadId(pub usize); /// Messages that can be sent to the file thread to manipulate text #[derive(Debug)] pub enum ToFileThreadMsg { /// Replace text between the start point and end point with the data from the string. /// If the end point is `None`, the text is just inserted at the start point. /// If the string is the empty string, the text between the start point and end point is /// deleted. ReplaceText(Point, Option<Point>, String), /// Clears all the text in the file ClearAllText, /// Saves the file to the OS file system. If the path is `None`, the file will not be saved. /// The front end is responsible for making sure the file thread has a proper path to a file. /// This may in the future accept a channel that Save(Sender<SaveResult>), } /// Used to output the result of the save message. The frontend can use this information to know if /// a file saved successfully. pub enum SaveResult { Ok, Err, PromptForPath, }
extern crate url; use self::url::percent_encoding::from_hex; extern crate hyper; use hyper::uri::RequestUri; use std::collections::HashMap; /// Percent-decode the input string /// /// Not using url::percent_decode because it does not throw an error for malformed percent encoding /// such as %AK pub fn percent_decode(input: &str) -> Result<Vec<u8>, String> { let mut output: Vec<u8> = Vec::new(); let mut input_iterator = input.as_bytes().into_iter(); while let Some(i) = input_iterator.next() { match i { &b'%' => { let hexdigit1 = input_iterator.next() .and_then(|h| from_hex(*h)); let hexdigit2 = input_iterator.next() .and_then(|h| from_hex(*h)); match (hexdigit1, hexdigit2) { (Some(h1), Some(h2)) => { output.push(h1 * 0x10 + h2); }, _ => { return Err("Invalid percent encoding".to_owned()); }, } } _ => { output.push(*i); } } } return Ok(output); } #[test] fn percent_decode_test() { // Successes assert_eq!(percent_decode("%1a").unwrap(), [26]); assert_eq!(percent_decode("%1A").unwrap(), [26]); assert_eq!(percent_decode("a").unwrap(), [97]); // Failures assert!(percent_decode("%").is_err()); //too short assert!(percent_decode("%a").is_err()); //too short assert!(percent_decode("%ak").is_err()); //not in [0-9a-f] } /// Converts bytes to a hexstring /// /// Lowercase-hex pub fn hexstring(input: &[u8]) -> String { let mut output = String::new(); for byte in input { output.push_str(&format!("{:02x}", byte)); } return output; } #[test] fn hexstring_test() { assert_eq!(hexstring(&[0x5, 0x6]), "0506"); assert_eq!(hexstring(&[0x0B, 0xf1]), "0bf1"); } /// Extract query key-values as a HashMap from a RequestUri::AbsolutePath pub fn query_hashmap(uri: &RequestUri) -> HashMap<&str, &str> { let mut retval: HashMap<&str, &str> = HashMap::new(); let path = match uri { &RequestUri::AbsolutePath(ref i) => i, _ => return retval, }; let query = match path.find('?') { Some(i) => &path[i+1..], None => "", }; for component in query.split('&') { match component.find('=') { Some(position) => { retval.insert(&component[..position], &component[position + 1..]); } None => {}, } } return retval; } #[test] pub fn query_hashmap_test() { let uri = RequestUri::AbsolutePath("/q?param=hello&n=&m&&something=world".to_owned()); let hmap = query_hashmap(&uri); assert_eq!(*hmap.get("param").unwrap(), "hello"); assert_eq!(*hmap.get("something").unwrap(), "world"); assert_eq!(*hmap.get("n").unwrap(), ""); assert_eq!(hmap.len(), 3); } /* The info hash is stored in mongo, which is not binary string safe apparently, so it needs to be parsed to a hexadecimal string rather than a binary one. */ pub fn parse_info_hash(input: &str) -> Result<String, String> { let info_hash_binary = try!(percent_decode(input)); if info_hash_binary.len() != 20 { return Err("Info hash is invalid (too short).".to_owned()); } return Ok(hexstring(&info_hash_binary)); } #[test] fn parse_info_hash_test() { // Success assert_eq!(parse_info_hash("%124Vx%9A%BC%DE%F1%23Eg%89%AB%CD%EF%124Vx%9A").unwrap(), "123456789abcdef123456789abcdef123456789a"); // Failures assert!(parse_info_hash("%124Vx%9A%BC%DE%F1%23Eg%89%AB%CD%EF%124Vx").is_err()); // too short assert!(parse_info_hash("%124Vx%9A%BC%DE%F1%23Eg%89%AB%CD%EF%124Vxab").is_err()); // too long assert!(parse_info_hash("%124Vx%9A%BC%DE%F1%23Eg%89%AB%CD%EF%124Vx%ZA").is_err()); // invalid percent encoding } /* Peer id is only ever used with redis, which is binary string safe. */ /* pub fn parse_peer_id(input: &str) -> Result<Vec<u8>, String> { let peer_id_binary = try!(percent_decode(input)); if peer_id_binary.len() != 20 { return Err("Peer ID is invalid (too short).".to_owned()); } return Ok(peer_id_binary); } #[test] fn parse_peer_id_test() { // Success assert_eq!(parse_peer_id("%124Vx%9A%BC%DE%F1%23Eg%89%AB%CD%EF%124Vx%9A").unwrap(), [0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf1, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x12, 0x34, 0x56, 0x78, 0x9a]); // Failures assert!(parse_peer_id("%124Vx%9A%BC%DE%F1%23Eg%89%AB%CD%EF%124Vx").is_err()); // too short assert!(parse_peer_id("%124Vx%9A%BC%DE%F1%23Eg%89%AB%CD%EF%124Vxab").is_err()); // too long assert!(parse_peer_id("%124Vx%9A%BC%DE%F1%23Eg%89%AB%CD%EF%124Vx%ZA").is_err()); // invalid percent encoding } */
// This file is part of Basilisk-node. // Copyright (C) 2020-2021 Intergalactic, Limited (GIB). // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. pub mod currency { pub use crate::Balance; pub const FORTUNE: Balance = u128::MAX; pub const BSX: Balance = 1_000_000_000_000; pub const DOLLARS: Balance = BSX * 100; // 100 BSX ~= 1 $ pub const CENTS: Balance = DOLLARS / 100; // 1 BSX ~= 1 cent pub const MILLICENTS: Balance = CENTS / 1_000; pub const NATIVE_EXISTENTIAL_DEPOSIT: Balance = CENTS; } pub mod time { use crate::{BlockNumber, Moment}; /// Since BABE is probabilistic this is the average expected block time that /// we are targeting. Blocks will be produced at a minimum duration defined /// by `SLOT_DURATION`, but some slots will not be allocated to any /// authority and hence no block will be produced. We expect to have this /// block time on average following the defined slot duration and the value /// of `c` configured for BABE (where `1 - c` represents the probability of /// a slot being empty). /// This value is only used indirectly to define the unit constants below /// that are expressed in blocks. The rest of the code should use /// `SLOT_DURATION` instead (like the Timestamp pallet for calculating the /// minimum period). /// /// If using BABE with secondary slots (default) then all of the slots will /// always be assigned, in which case `MILLISECS_PER_BLOCK` and /// `SLOT_DURATION` should have the same value. /// /// <https://research.web3.foundation/en/latest/polkadot/BABE/Babe/#6-practical-results> pub const MILLISECS_PER_BLOCK: u64 = 12000; // Time is measured by number of blocks. pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber); pub const HOURS: BlockNumber = MINUTES * 60; pub const DAYS: BlockNumber = HOURS * 24; pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK; pub const SECS_PER_BLOCK: Moment = MILLISECS_PER_BLOCK / 1000; pub const EPOCH_DURATION_IN_BLOCKS: BlockNumber = 4 * HOURS; } pub mod chain { pub use crate::{AssetId, Balance}; pub use frame_support::weights::{constants::WEIGHT_PER_SECOND, Weight}; /// Core asset id pub const CORE_ASSET_ID: AssetId = 0; /// Max fraction of pool to buy in single transaction pub const MAX_OUT_RATIO: u128 = 3; /// Max fraction of pool to sell in single transaction pub const MAX_IN_RATIO: u128 = 3; /// Trading limit pub const MIN_TRADING_LIMIT: Balance = 1000; /// Minimum pool liquidity pub const MIN_POOL_LIQUIDITY: Balance = 1000; /// We allow for pub const MAXIMUM_BLOCK_WEIGHT: Weight = WEIGHT_PER_SECOND / 2; } #[cfg(test)] mod tests { use super::time::{DAYS, EPOCH_DURATION_IN_BLOCKS, HOURS, MILLISECS_PER_BLOCK, MINUTES, SECS_PER_BLOCK}; #[test] // This function tests that time units are set up correctly fn time_units_work() { // 24 hours in a day assert_eq!(DAYS / 24, HOURS); // 60 minuts in an hour assert_eq!(HOURS / 60, MINUTES); // 1 minute = 60s = 5 blocks 12s each assert_eq!(MINUTES, 5); // 6s per block assert_eq!(SECS_PER_BLOCK, 12); // 1s = 1000ms assert_eq!(MILLISECS_PER_BLOCK / 1000, SECS_PER_BLOCK); // Extra check for epoch time because changing it bricks the block production and requires regenesis assert_eq!(EPOCH_DURATION_IN_BLOCKS, 4 * HOURS); } }
use crate::database::Database; use crate::entities::aggregation::NewAggregationStrategy; use crate::entities::point::{Point, QueryOptions}; use crate::entities::series::RetentionPolicy; use bincode::serialize; use chrono::prelude::*; use chrono::Duration; use rocksdb::WriteBatch; use std::str; use std::sync::{Arc, RwLock, RwLockWriteGuard}; use std::thread; use std::time::Instant; use tokio::prelude::*; use tokio::timer::Interval; #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] pub struct JanitorConfig { interval: String, } impl Default for JanitorConfig { fn default() -> JanitorConfig { JanitorConfig { interval: "5 minutes".to_string(), } } } pub fn start_janitor( config: &Option<JanitorConfig>, db: Arc<RwLock<Database>>, ) -> Result<(), &str> { let config = config.as_ref().map_or_else(Default::default, Clone::clone); let interval = crate::entities::duration::Duration::from_string(&config.interval) .ok_or("Invalid duration for interval")?; thread::spawn(move || { let duration = Duration::from(&interval).to_std().unwrap(); let interval = Interval::new(Instant::now() + duration, duration); let task = interval .for_each(move |_| { info!("Running janitor"); let mut db_mut = db.write().unwrap(); let series = db_mut.list_series().unwrap(); let series = series.into_iter().filter_map(|series| { let name = series.name; series.retention_policy.map(|policy| (name, policy)) }); series.for_each(|(series_name, policy)| { debug!("Running janitor on series {}", series_name); garbage_collect_series(&mut db_mut, &series_name, &policy).unwrap(); compact_series(&mut db_mut, &series_name, policy).unwrap(); }); future::done(Ok(())) }) .map_err(|e| panic!("interval errored; err={:?}", e)); tokio::run(task); }); Ok(()) } fn garbage_collect_series( db: &mut RwLockWriteGuard<Database>, series_name: &str, policy: &RetentionPolicy, ) -> Result<(), rocksdb::Error> { match policy.drop_after.as_ref() { Some(drop_after) => { let drop_until = Utc::now() - drop_after; trace!("Drop until {}", drop_until); db.delete_by_query( &series_name, Some(QueryOptions::with(|options| { options.until = Some(drop_until); })), ) } None => Ok(()), } } fn compact_series( db: &mut RwLockWriteGuard<Database>, series_name: &str, policy: RetentionPolicy, ) -> Result<(), rocksdb::Error> { policy .compact .into_iter() .try_fold(None, |since, compact| { let until = Some(Utc::now() - &compact.after); debug!("range {:?} -> {:?}", &since, &until); let aggregation_strategy = NewAggregationStrategy { over: compact.aggregate.over, function: compact.aggregate.function, }; let query_options = QueryOptions { since, until, aggregate: Some(aggregation_strategy.clone()), }; let mut batch = WriteBatch::default(); { let mut points = db.iter_points(&series_name, Some(query_options)); if let Some(first) = points.next() { let duration = (&aggregation_strategy.over).into(); let mut count = 1; let mut start_time = first.time; let mut value = first.value; for point in points { if point.time - start_time >= duration { let aggregated_point = Point { time: start_time, value: aggregation_strategy.function.finish(value, count), }; count = 1; start_time = point.time; value = point.value; debug!("creating aggregation {}", &start_time); batch.put( &format!("points::{}::{}", &series_name, &start_time).into_bytes(), &serialize(&aggregated_point).unwrap(), )?; } else { count += 1; value = aggregation_strategy.function.reduce(value, point.value); debug!("compacting {}", &point.time); batch.delete(&format!("points::{}::{}", &series_name, &point.time).into_bytes())?; } } debug!("creating aggregation2 {}", &start_time); batch.put( &format!("points::{}::{}", &series_name, &start_time).into_bytes(), &serialize(&Point { time: start_time, value: aggregation_strategy.function.finish(value, count), }) .unwrap(), )?; } } db.write(batch)?; Ok(until) })?; Ok(()) }
use clap::App; fn generate_manpage(app: &App) -> String { let mut lines = vec![]; let version = version::version(app).unwrap(); lines.push(format!(".TH {} 1 \"{}\"", app.get_name(), version)); lines.join("\n") } #[cfg(test)] mod tests { use crate::generate_man::generate_manpage; use clap::App; use std::borrow::Borrow; #[test] fn first_line_should_be_header() { let app = App::new("App".to_string()).version("v0.1.24"); let manpage = generate_manpage(app.borrow()); let lines: Vec<_> = manpage .lines() .take(1) .map(String::from) .collect::<Vec<_>>(); let line = lines.get(0).map(String::clone); assert_eq!(line, Some(".TH App 1 \"v0.1.24\"".into())); } } mod version { use clap::App; pub(crate) fn version(app: &App) -> Option<String> { let mut version_buffer: Vec<u8> = vec![]; app.write_version(&mut version_buffer).unwrap(); let version = String::from_utf8(version_buffer.to_vec()).unwrap(); let prefix = format!("{} ", app.get_name()); version.strip_prefix(&prefix).map(String::from) } #[cfg(test)] mod tests { use crate::generate_man::version::version; use clap::App; #[test] fn i_can_get_the_version_without_app_name() { let app = App::new("App".to_string()).version("v0.1.24"); let version = version(&app); assert_eq!(version, Some("v0.1.24".to_string())); } } }
//! Result and errors. use std::result; use failure::Fail; /// Internal results representation. pub type Result<T> = result::Result<T, Error>; /// Internal error representation. #[derive(Fail, Debug)] pub enum Error { /// Error thrown when a Generation is initialized with one or more invalid dimension. #[fail(display = "Generation's width and height must be equal or greater than 3.")] InvalidDimensionError, }
#[derive(VulkanoShader)] #[ty = "compute"] #[src = " #version 450 // TODO: 64 ? layout(local_size_x = 32, local_size_y = 32, local_size_z = 1) in; layout(set = 0, binding = 0) uniform usampler2D tmp_image; layout(set = 0, binding = 1) uniform usampler2D tmp_erase_image; /// It is important that this buffer is cleared for each frame. layout(set = 1, binding = 0) buffer TmpErased { uint data[]; } tmp_erased; layout(set = 1, binding = 1) buffer ErasedAmount { uint data; } erased_amount; void main() { uint erased = texture(tmp_erase_image, gl_GlobalInvocationID.xy).r; if (erased != 0) { uvec4 pixel = texture(tmp_image, gl_GlobalInvocationID.xy); uint group = pixel.r << 8 | pixel.g; tmp_erased.data[group] = 1; erased_amount.data += 1; } }"] struct _Dummy;
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { anyhow::Error, fidl_fuchsia_images as images, fidl_fuchsia_ui_gfx as ui_gfx, fuchsia_scenic as scenic, fuchsia_scenic, }; /// A struct that contains all the information needed to use an image with [`scenic`]. pub struct ImageResource { /// The path to the image that was loaded. pub path: String, /// The width of the image. pub width: f32, /// The height of the image. pub height: f32, /// The [`scenic::Material`] containing the image information that can added to a [`scenic::ShapeNode`]. pub material: scenic::Material, } impl ImageResource { /// Creates a new instance of `ImageResource` /// /// # Parameters /// - `image_path`: Path to the image file to load. /// - `session`: The [scenic::SessionPtr] to use for loading the image. /// /// # Returns /// The [`ImageResource`] containing the information for the requested image. /// /// # Errors /// - If image file could not be opened. /// - If the image file format can not be read. /// - If the system could not allocate memeory to store the loaded image. pub fn new(image_path: &str, session: scenic::SessionPtr) -> Result<Self, Error> { let decoder = png::Decoder::new(std::fs::File::open(image_path)?); let (info, mut reader) = decoder.read_info()?; let mut buf = vec![0; info.buffer_size()]; reader.next_frame(&mut buf)?; let px_size_bytes = std::mem::size_of::<u8>() * 4; // RGBA let (width, height) = (info.width, info.height); let size_bytes = width as usize * height as usize * px_size_bytes; let image_info = images::ImageInfo { transform: images::Transform::Normal, width, height, stride: width * px_size_bytes as u32, pixel_format: images::PixelFormat::Bgra8, color_space: images::ColorSpace::Srgb, tiling: images::Tiling::Linear, alpha_format: images::AlphaFormat::NonPremultiplied, }; let host_memory = scenic::HostMemory::allocate(session.clone(), size_bytes)?; let host_image = scenic::HostImage::new(&host_memory, 0, image_info); // swizzle RGBA to BGRA for i in (0..size_bytes).step_by(px_size_bytes) { let (r, g, b, a) = (buf[i], buf[i + 1], buf[i + 2], buf[i + 3]); buf[i] = b; buf[i + 1] = g; buf[i + 2] = r; buf[i + 3] = a; } host_image.mapping().write(&buf); let material = scenic::Material::new(session.clone()); material.set_texture(Some(&host_image)); material.set_color(ui_gfx::ColorRgba { red: 255, green: 255, blue: 255, alpha: 250 }); Ok(ImageResource { path: image_path.to_owned(), width: width as f32, height: height as f32, material, }) } }
use std::env; use std::fs; use regex::Regex; fn main() { let args: Vec<String> = env::args().collect(); let filename = &args[1]; let contents = fs::read_to_string(filename) .expect("Something went wrong reading the file"); let split_contents = contents.lines(); let passwords: Vec<&str> = split_contents.collect(); let mut num_valid = 0; for password in passwords { let re = Regex::new(r"(\d*)-(\d*)\s(\w):\s(\w*)").unwrap(); for cap in re.captures_iter(password) { let first = &cap[1].parse::<usize>().unwrap(); let second = &cap[2].parse::<usize>().unwrap(); let char = &cap[3]; let password = &cap[4]; if valid(*first, *second, char, password) { num_valid += 1; } } } println!("valid passwords: {}", num_valid); } /* part one fn valid(min: usize, max: usize, char: &str, text: &str) -> bool { let formatted = format!(r"({})", char); let re = Regex::new(formatted.as_str()); let num_caps = match re { Ok(regex) => { regex.find_iter(text).count() } Err(_) => panic!("couldn't parse regex"), }; // println!("number of {}: {}", char, num_caps); return min <= num_caps && num_caps <= max } */ fn valid(first: usize, second: usize, char: &str, text: &str) -> bool { let char: char = char.parse::<char>().unwrap(); let first_char = text.as_bytes()[first-1] as char; let second_char = text.as_bytes()[second-1] as char; let valid = (first_char == char && second_char != char) || (first_char != char && second_char == char); println!("{} | {}({})-{}({}) {}: {}", valid, first_char, first, second_char, second, char, text); return valid }
#![cfg(feature = "derive")] #![cfg(feature = "std")] use tabled::Tabled; // https://users.rust-lang.org/t/create-a-struct-from-macro-rules/19829 macro_rules! test_tuple { ( $test_name:ident, t: $(#[$struct_attr:meta])* { $( $(#[$attr:meta])* $ty:ty)* }, init: { $($init:expr)* }, expected: $headers:expr, $fields:expr, $(pre: { $($init_block:stmt)* })? ) => { #[test] fn $test_name() { $($($init_block)*)? #[derive(Tabled)] struct TestType( $( $(#[$attr])* $ty, )* ); let value = TestType($($init,)*); let fields: Vec<&'static str> = $fields.to_vec(); let headers: Vec<&'static str> = $headers.to_vec(); assert_eq!(value.fields(), fields); assert_eq!(TestType::headers(), headers); assert_eq!(<TestType as Tabled>::LENGTH, headers.len()); assert_eq!(<TestType as Tabled>::LENGTH, fields.len()); } }; } macro_rules! test_enum { ( $test_name:ident, t: $(#[$struct_attr:meta])* { $( $(#[$var_attr:meta])* $var:ident $({ $( $(#[$attr:meta])* $field:ident: $ty:ty),* $(,)? })? $(( $( $(#[$attr2:meta])* $ty2:ty),* $(,)? ))? )* }, $(pre: { $($init_block:stmt)* })? headers: $headers:expr, tests: $($init:expr => $expected:expr,)* ) => { #[allow(dead_code, unused_imports)] #[test] fn $test_name() { $($($init_block)*)? #[derive(Tabled)] $(#[$struct_attr])* enum TestType { $( $(#[$var_attr])* $var $({ $( $(#[$attr])* $field: $ty,)* })? $(( $( $(#[$attr2])* $ty2,)* ))? ),* } let headers: Vec<&'static str> = $headers.to_vec(); assert_eq!(TestType::headers(), headers); assert_eq!(<TestType as Tabled>::LENGTH, headers.len()); { use TestType::*; $( let variant = $init; let fields: Vec<&'static str> = $expected.to_vec(); assert_eq!(variant.fields(), fields); )* } } }; } macro_rules! test_struct { ( $test_name:ident, t: $(#[$struct_attr:meta])* { $( $(#[$attr:meta])* $field:ident: $ty:ty),* $(,)?} $(pre: { $($init_block:stmt)* })? init: { $( $val_field:ident: $val:expr),* $(,)?} expected: $headers:expr, $fields:expr $(,)? ) => { #[allow(dead_code, unused_imports)] #[test] fn $test_name() { $($($init_block)*)? #[derive(Tabled)] $(#[$struct_attr])* struct TestType { $( $(#[$attr])* $field: $ty, )* } let value = TestType { $($val_field: $val,)* }; let fields: Vec<&'static str> = $fields.to_vec(); let headers: Vec<&'static str> = $headers.to_vec(); assert_eq!(TestType::headers(), headers); assert_eq!(value.fields(), fields); assert_eq!(<TestType as Tabled>::LENGTH, headers.len()); assert_eq!(<TestType as Tabled>::LENGTH, fields.len()); } }; } #[allow(non_camel_case_types)] type sstr = &'static str; mod tuple { use super::*; test_tuple!(basic, t: { u8 sstr }, init: { 0 "v2" }, expected: ["0", "1"], ["0", "v2"],); test_tuple!(empty, t: { }, init: { }, expected: [], [],); test_tuple!(rename, t: { u8 #[tabled(rename = "field 2")] sstr }, init: { 0 "123" }, expected: ["0", "field 2"], ["0", "123"],); test_tuple!(skip_0, t: { #[tabled(skip)] u8 #[tabled(rename = "field 2", skip)] sstr sstr }, init: { 0 "v2" "123" }, expected: ["2"], ["123"],); test_tuple!(skip_1, t: { #[tabled(skip)] u8 #[tabled(skip)] #[tabled(rename = "field 2")] sstr sstr }, init: { 0 "v2" "123" }, expected: ["2"], ["123"],); test_tuple!(order_0, t: { #[tabled(order = 0)] u8 u8 u8}, init: { 0 1 2 }, expected: ["0", "1", "2"], ["0", "1", "2"],); test_tuple!(order_1, t: { #[tabled(order = 1)] u8 u8 u8}, init: { 0 1 2 }, expected: ["1", "0", "2"], ["1", "0", "2"],); test_tuple!(order_2, t: { #[tabled(order = 2)] u8 u8 u8}, init: { 0 1 2 }, expected: ["1", "2", "0"], ["1", "2", "0"],); test_tuple!(order_3, t: { u8 #[tabled(order = 0)] u8 u8}, init: { 0 1 2 }, expected: ["1", "0", "2"], ["1", "0", "2"],); test_tuple!(order_4, t: { u8 #[tabled(order = 1)] u8 u8}, init: { 0 1 2 }, expected: ["0", "1", "2"], ["0", "1", "2"],); test_tuple!(order_5, t: { u8 #[tabled(order = 2)] u8 u8}, init: { 0 1 2 }, expected: ["0", "2", "1"], ["0", "2", "1"],); test_tuple!(order_6, t: { u8 u8 #[tabled(order = 0)] u8}, init: { 0 1 2 }, expected: ["2", "0", "1"], ["2", "0", "1"],); test_tuple!(order_7, t: { u8 u8 #[tabled(order = 1)] u8}, init: { 0 1 2 }, expected: ["0", "2", "1"], ["0", "2", "1"],); test_tuple!(order_8, t: { u8 u8 #[tabled(order = 2)] u8}, init: { 0 1 2 }, expected: ["0", "1", "2"], ["0", "1", "2"],); test_tuple!(order_9, t: { #[tabled(order = 2)] u8 u8 #[tabled(order = 0)] u8}, init: { 0 1 2 }, expected: ["2", "1", "0"], ["2", "1", "0"],); test_tuple!(order_10, t: { #[tabled(order = 2)] u8 #[tabled(order = 1)] u8 u8}, init: { 0 1 2 }, expected: ["2", "1", "0"], ["2", "1", "0"],); test_tuple!(order_11, t: { #[tabled(order = 2)] u8 #[tabled(order = 2)] u8 #[tabled(order = 1)] u8}, init: { 0 1 2 }, expected: ["0", "2", "1"], ["0", "2", "1"],); test_tuple!(order_12, t: { #[tabled(order = 2)] u8 #[tabled(order = 2)] u8 #[tabled(order = 2)] u8}, init: { 0 1 2 }, expected: ["0", "1", "2"], ["0", "1", "2"],); test_tuple!(order_13, t: { #[tabled(order = 1)] u8 #[tabled(order = 1)] u8 #[tabled(order = 1)] u8}, init: { 0 1 2 }, expected: ["0", "2", "1"], ["0", "2", "1"],); test_tuple!(order_14, t: { #[tabled(order = 2)] u8 #[tabled(order = 1)] u8 #[tabled(order = 0)] u8}, init: { 0 1 2 }, expected: ["2", "1", "0"], ["2", "1", "0"],); test_tuple!(rename_all, t: #[tabled(rename_all = "UPPERCASE")] { u8 sstr}, init: { 0 "123" }, expected: ["0", "1"], ["0", "123"],); test_tuple!(rename_all_field, t: { u8 #[tabled(rename_all = "UPPERCASE")] sstr}, init: { 0 "123" }, expected: ["0", "1"], ["0", "123"],); test_tuple!(rename_all_field_with_rename_0, t: { u8 #[tabled(rename_all = "UPPERCASE", rename = "Something")] sstr}, init: { 0 "123" }, expected: ["0", "Something"], ["0", "123"],); test_tuple!(rename_all_field_with_rename_1, t: { u8 #[tabled(rename = "Something")] #[tabled(rename_all = "UPPERCASE")] sstr}, init: { 0 "123" }, expected: ["0", "Something"], ["0", "123"],); test_tuple!( display_option, t: { u8 #[tabled(display_with = "display_option")] Option<sstr> }, init: { 0 Some("v2") }, expected: ["0", "1"], ["0", "some v2"], pre: { fn display_option(o: &Option<sstr>) -> String { match o { Some(s) => format!("some {s}"), None => "none".to_string(), } } } ); test_tuple!( display_option_args, t: { u8 #[tabled(display_with("display_option", 1, "234"))] Option<sstr> }, init: { 0 Some("v2") }, expected: ["0", "1"], ["0", "some 1 234"], pre: { fn display_option(val: usize, text: &str) -> String { format!("some {val} {text}") } } ); test_tuple!( display_option_self, t: { u8 #[tabled(display_with = "Self::display_option")] Option<sstr> }, init: { 0 Some("v2") }, expected: ["0", "1"], ["0", "some v2"], pre: { impl TestType { fn display_option(o: &Option<sstr>) -> String { match o { Some(s) => format!("some {s}"), None => "none".to_string(), } } } } ); test_tuple!( display_option_self_2, t: { u8 #[tabled(display_with("Self::display_option", self))] Option<sstr> }, init: { 0 Some("v2") }, expected: ["0", "1"], ["0", "some v2"], pre: { impl TestType { fn display_option(o: &TestType) -> String { match o.1 { Some(s) => format!("some {s}"), None => "none".to_string(), } } } } ); test_tuple!( display_option_self_3, t: { u8 #[tabled(display_with("display_option", self))] Option<sstr> }, init: { 0 Some("v2") }, expected: ["0", "1"], ["0", "some v2"], pre: { fn display_option(o: &TestType) -> String { match o.1 { Some(s) => format!("some {s}"), None => "none".to_string(), } } } ); // #[test] // fn order_compile_fail_when_order_is_bigger_then_count_fields() { // #[derive(Tabled)] // struct St(#[tabled(order = 3)] u8, u8, u8); // } } mod enum_ { use super::*; test_enum!( basic, t: { Security Embedded Frontend Unknown }, headers: ["Security", "Embedded", "Frontend", "Unknown"], tests: Security => ["+", "", "", ""], Embedded => ["", "+", "", ""], Frontend => ["", "", "+", ""], Unknown => ["", "", "", "+"], ); test_enum!( diverse, t: { A { a: u8, b: i32 } B(sstr) K }, headers: ["A", "B", "K"], tests: A { a: 1, b: 2 } => ["+", "", ""], B("") => ["", "+", ""], K => ["", "", "+"], ); test_enum!( rename_variant, t: { #[tabled(rename = "Variant 1")] A { a: u8, b: i32 } #[tabled(rename = "Variant 2")] B(sstr) K }, headers: ["Variant 1", "Variant 2", "K"], tests: A { a: 1, b: 2 } => ["+", "", ""], B("") => ["", "+", ""], K => ["", "", "+"], ); test_enum!( skip_variant, t: { A { a: u8, b: i32 } #[tabled(skip)] B(sstr) K }, headers: ["A", "K"], tests: A { a: 1, b: 2 } => ["+", ""], B("") => ["", ""], K => ["", "+"], ); test_enum!( inline_variant, t: { #[tabled(inline("Auto::"))] Auto { #[tabled(rename = "mod")] model: sstr, engine: sstr } #[tabled(inline)] Bikecycle( #[tabled(rename = "name")] sstr, #[tabled(inline)] Bike ) Skateboard }, pre: { #[derive(Tabled)] struct Bike { brand: sstr, price: f32 } } headers: ["Auto::mod", "Auto::engine", "name", "brand", "price", "Skateboard"], tests: Skateboard => ["", "", "", "", "", "+"], Auto { model: "Mini", engine: "v8" } => ["Mini", "v8", "", "", "", ""], Bikecycle("A bike", Bike { brand: "Canyon", price: 2000.0 })=> ["", "", "A bike", "Canyon", "2000", ""], ); test_enum!( inline_field_with_display_function, t: { #[tabled(inline("backend::"))] Backend { #[tabled(display_with = "display", rename = "name")] value: sstr } Frontend }, pre: { fn display(_: sstr) -> String { "asd".to_string() } } headers: ["backend::name", "Frontend"], tests: Backend { value: "123" } => ["asd", ""], Frontend => ["", "+"], ); test_enum!( inline_field_with_display_self_function, t: { #[tabled(inline("backend::"))] Backend { #[tabled()] #[tabled(display_with("display", self), rename = "name")] value: sstr } Frontend }, pre: { fn display<T>(_: &T) -> String { "asd".to_string() } } headers: ["backend::name", "Frontend"], tests: Backend { value: "123" } => ["asd", ""], Frontend => ["", "+"], ); test_enum!( with_display, t: { #[tabled(inline)] A(#[tabled(display_with = "format::<4>")] sstr) B }, pre: { fn format<const ID: usize>(_: sstr) -> String { ID.to_string() } } headers: ["0", "B"], tests: A("") => ["4", ""], B => ["", "+"], ); test_enum!( with_display_self, t: { #[tabled(inline)] A(#[tabled(display_with("Self::format::<4>", self))] sstr) B }, pre: { impl TestType { fn format<const ID: usize>(&self) -> String { ID.to_string() } } } headers: ["0", "B"], tests: A("") => ["4", ""], B => ["", "+"], ); test_enum!( rename_all_variant, t: { #[tabled(rename_all = "snake_case")] VariantName1 { a: u8, b: i32 } #[tabled(rename_all = "UPPERCASE")] VariantName2(String) K }, headers: ["variant_name1", "VARIANTNAME2", "K"], tests: ); test_enum!( rename_all_enum, t: #[tabled(rename_all = "snake_case")] { VariantName1 { a: u8, b: i32 } VariantName2(String) K }, headers: ["variant_name1", "variant_name2", "k"], tests: ); test_enum!( rename_all_enum_inherited_inside_struct_enum, t: #[tabled(rename_all = "snake_case")] { #[tabled(inline)] VariantName1 { some_field_1: u8, some_field_2: i32 } VariantName2(String) K }, headers: ["some_field_1", "some_field_2", "variant_name2", "k"], tests: ); test_enum!( rename_all_enum_inherited_inside_struct_override_by_rename_enum, t: #[tabled(rename_all = "snake_case")] { #[tabled(inline)] VariantName1 { #[tabled(rename = "f1")] some_field_1: u8, #[tabled(rename = "f2")] some_field_2: i32, } VariantName2(String) K }, headers: ["f1", "f2", "variant_name2", "k"], tests: ); test_enum!( rename_all_enum_inherited_inside_struct_override_by_rename_all_enum, t: #[tabled(rename_all = "snake_case")] { #[tabled(inline)] VariantName1 { #[tabled(rename_all = "UPPERCASE")] some_field_1: u8, #[tabled(rename_all = "CamelCase")] some_field_2: i32, } VariantName2(String) K }, headers: ["SOMEFIELD1", "someField2", "variant_name2", "k"], tests: ); test_enum!( rename_all_variant_inherited_inside_struct_enum, t: #[tabled(rename_all = "snake_case")] { #[tabled(inline)] #[tabled(rename_all = "snake_case")] VariantName1 { some_field_1: u8, some_field_2: i32, } VariantName2(String) K }, headers: ["some_field_1", "some_field_2", "variant_name2", "k"], tests: ); test_enum!( rename_all_variant_inherited_inside_struct_enum_overridden_by_rename, t: #[tabled(rename_all = "snake_case")] { #[tabled(inline, rename_all = "snake_case")] VariantName1 { #[tabled(rename = "f1")] some_field_1: u8, #[tabled(rename = "f2")] some_field_2: i32, } VariantName2(String) K }, headers: ["f1", "f2", "variant_name2", "k"], tests: ); test_enum!( rename_all_variant_inherited_inside_struct_override_by_rename_all_enum, t: #[tabled(rename_all = "snake_case")] { #[tabled(rename_all = "snake_case", inline)] VariantName1 { #[tabled(rename_all = "UPPERCASE")] some_field_1: u8, #[tabled(rename_all = "CamelCase")] some_field_2: i32, } VariantName2(String) K }, headers: ["SOMEFIELD1", "someField2", "variant_name2", "k"], tests: ); test_enum!( inline_enum_as_whole, t: #[tabled(inline)] { AbsdEgh { a: u8, b: i32 } B(String) K }, headers: ["TestType"], tests: AbsdEgh { a: 0, b: 0 } => ["AbsdEgh"], B(String::new()) => ["B"], K => ["K"], ); test_enum!( inline_enum_as_whole_and_rename, t: #[tabled(inline, rename_all = "snake_case")] { AbsdEgh { a: u8, b: i32 } B(String) K }, headers: ["TestType"], tests: AbsdEgh { a: 0, b: 0 } => ["absd_egh"], B(String::new()) => ["b"], K => ["k"], ); test_enum!( inline_enum_as_whole_and_rename_inner, t: #[tabled(inline)] { #[tabled(rename_all = "snake_case")] AbsdEgh { a: u8, b: i32 } #[tabled(rename_all = "lowercase")] B(String) K }, headers: ["TestType"], tests: AbsdEgh { a: 0, b: 0 } => ["absd_egh"], B(String::new()) => ["b"], K => ["K"], ); test_enum!( inline_enum_name, t: #[tabled(inline("A struct name"))] { AbsdEgh { a: u8, b: i32 } B(String) K }, headers: ["A struct name"], tests: AbsdEgh { a: 0, b: 0 } => ["AbsdEgh"], B(String::new()) => ["B"], K => ["K"], ); test_enum!( enum_display_with_variant, t: { #[tabled(display_with = "display_variant1")] AbsdEgh { a: u8, b: i32 } #[tabled(display_with = "display_variant2::<200>")] B(String) #[tabled(display_with = "some::bar::display_variant1")] K }, pre: { fn display_variant1() -> &'static str { "Hello World" } fn display_variant2<const VAL: usize>() -> String { format!("asd {VAL}") } pub mod some { pub mod bar { pub fn display_variant1() -> &'static str { "Hello World 123" } } } } headers: ["AbsdEgh", "B", "K"], tests: AbsdEgh { a: 0, b: 0 } => ["Hello World", "", ""], B(String::new()) => ["", "asd 200", ""], K => ["", "", "Hello World 123"], ); test_enum!( enum_display_with_self_variant, t: { #[tabled(display_with("display_variant1", self))] AbsdEgh { a: u8, b: i32 } #[tabled(display_with("display_variant2::<200, _>", self))] B(String) #[tabled(display_with("some::bar::display_variant1", self))] K }, pre: { fn display_variant1<D>(_: &D) -> &'static str { "Hello World" } fn display_variant2<const VAL: usize, D>(_: &D) -> String { format!("asd {VAL}") } pub mod some { pub mod bar { pub fn display_variant1<D>(_: &D) -> &'static str { "Hello World 123" } } } } headers: ["AbsdEgh", "B", "K"], tests: AbsdEgh { a: 0, b: 0 } => ["Hello World", "", ""], B(String::new()) => ["", "asd 200", ""], K => ["", "", "Hello World 123"], ); test_enum!( enum_display_with_arguments, t: { #[tabled(display_with("display1", 1, 2, self))] AbsdEgh { a: u8, b: i32 } #[tabled(display_with("display2::<200>", "Hello World"))] B(String) #[tabled(display_with("display1", 100, 200, self))] K }, pre: { fn display1<D>(val: usize, val2: usize, _: &D) -> String { format!("{val} {val2}") } fn display2<const VAL: usize>(val: &str) -> String { format!("asd {VAL} {val}") } } headers: ["AbsdEgh", "B", "K"], tests: AbsdEgh { a: 0, b: 0 } => ["1 2", "", ""], B(String::new()) => ["", "asd 200 Hello World", ""], K => ["", "", "100 200"], ); test_enum!(order_0, t: { #[tabled(order = 0)] V1(u8) V2(u8) V3(u8) }, headers: ["V1", "V2", "V3"], tests: V1(0) => ["+", "", ""], V2(0) => ["", "+", ""], V3(0) => ["", "", "+"],); test_enum!(order_1, t: { #[tabled(order = 1)] V1(u8) V2(u8) V3(u8) }, headers: ["V2", "V1", "V3"], tests: V1(0) => ["", "+", ""], V2(0) => ["+", "", ""], V3(0) => ["", "", "+"],); test_enum!(order_2, t: { #[tabled(order = 2)] V1(u8) V2(u8) V3(u8) }, headers: ["V2", "V3", "V1"], tests: V1(0) => ["", "", "+"], V2(0) => ["+", "", ""], V3(0) => ["", "+", ""],); test_enum!(order_3, t: { V1(u8) #[tabled(order = 0)] V2(u8) V3(u8) }, headers: ["V2", "V1", "V3"], tests: V1(0) => ["", "+", ""], V2(0) => ["+", "", ""], V3(0) => ["", "", "+"],); test_enum!(order_4, t: { V1(u8) #[tabled(order = 1)] V2(u8) V3(u8) }, headers: ["V1", "V2", "V3"], tests: V1(0) => ["+", "", ""], V2(0) => ["", "+", ""], V3(0) => ["", "", "+"],); test_enum!(order_5, t: { V1(u8) #[tabled(order = 2)] V2(u8) V3(u8) }, headers: ["V1", "V3", "V2"], tests: V1(0) => ["+", "", ""], V2(0) => ["", "", "+"], V3(0) => ["", "+", ""],); test_enum!(order_6, t: { V1(u8) V2(u8) #[tabled(order = 0)] V3(u8) }, headers: ["V3", "V1", "V2"], tests: V1(0) => ["", "+", ""], V2(0) => ["", "", "+"], V3(0) => ["+", "", ""],); test_enum!(order_7, t: { V1(u8) V2(u8) #[tabled(order = 1)] V3(u8) }, headers: ["V1", "V3", "V2"], tests: V1(0) => ["+", "", ""], V2(0) => ["", "", "+"], V3(0) => ["", "+", ""],); test_enum!(order_8, t: { V1(u8) V2(u8) #[tabled(order = 2)] V3(u8) }, headers: ["V1", "V2", "V3"], tests: V1(0) => ["+", "", ""], V2(0) => ["", "+", ""], V3(0) => ["", "", "+"],); test_enum!(order_9, t: { #[tabled(order = 2)] V1(u8) V2(u8) #[tabled(order = 0)] V3(u8) }, headers: ["V3", "V2", "V1"], tests: V1(0) => ["", "", "+"], V2(0) => ["", "+", ""], V3(0) => ["+", "", ""],); test_enum!(order_10, t: { #[tabled(order = 2)] V1(u8) V2(u8) #[tabled(order = 1)] V3(u8) }, headers: ["V2", "V3", "V1"], tests: V1(0) => ["", "", "+"], V2(0) => ["+", "", ""], V3(0) => ["", "+", ""],); test_enum!(order_11, t: { #[tabled(order = 2)] V1(u8) #[tabled(order = 2)] V2(u8) #[tabled(order = 1)] V3(u8) }, headers: ["V1", "V3", "V2"], tests: V1(0) => ["+", "", ""], V2(0) => ["", "", "+"], V3(0) => ["", "+", ""],); test_enum!(order_12, t: { #[tabled(order = 2)] V1(u8) #[tabled(order = 1)] V2(u8) #[tabled(order = 0)] V3(u8) }, headers: ["V3", "V2", "V1"], tests: V1(0) => ["", "", "+"], V2(0) => ["", "+", ""], V3(0) => ["+", "", ""],); test_enum!(order_13, t: { #[tabled(order = 0)] V1(u8) #[tabled(order = 0)] V2(u8) #[tabled(order = 0)] V3(u8) }, headers: ["V3", "V1", "V2"], tests: V1(0) => ["", "+", ""], V2(0) => ["", "", "+"], V3(0) => ["+", "", ""],); test_enum!(order_14, t: { #[tabled(order = 1)] V1(u8) #[tabled(order = 1)] V2(u8) #[tabled(order = 1)] V3(u8) }, headers: ["V1", "V3", "V2"], tests: V1(0) => ["+", "", ""], V2(0) => ["", "", "+"], V3(0) => ["", "+", ""],); test_enum!(order_15, t: { #[tabled(order = 2)] V1(u8) #[tabled(order = 2)] V2(u8) #[tabled(order = 2)] V3(u8) }, headers: ["V1", "V2", "V3"], tests: V1(0) => ["+", "", ""], V2(0) => ["", "+", ""], V3(0) => ["", "", "+"],); test_enum!(order_0_inlined, t: #[tabled(inline)] { #[tabled(order = 1)] V1(u8) V2(u8) V3(u8) }, headers: ["TestType"], tests: V1(0) => ["V1"], V2(0) => ["V2"], V3(0) => ["V3"],); } mod unit { use super::*; #[test] fn basic() { #[derive(Tabled)] struct St; let st = St; assert!(st.fields().is_empty()); assert!(St::headers().is_empty()); assert_eq!(St::LENGTH, 0); } } mod structure { use super::*; test_struct!(empty, t: { } init: { } expected: [], []); test_struct!(general, t: { f1: u8, f2: sstr } init: { f1: 0, f2: "v2" } expected: ["f1", "f2"], ["0", "v2"]); test_struct!(rename, t: { #[tabled(rename = "field 1")] f1: u8, #[tabled(rename = "field 2")] f2: sstr } init: { f1: 0, f2: "v2" } expected: ["field 1", "field 2"], ["0", "v2"]); test_struct!(skip, t: { #[tabled(skip)] f1: u8, #[tabled(rename = "field 2", skip)] f2: sstr, f3: sstr } init: { f1: 0, f2: "v2", f3: "123" } expected: ["f3"], ["123"]); test_struct!(skip_true, t: { #[tabled(skip = true)] f1: u8, #[tabled(rename = "field 2", skip = true)] f2: sstr, f3: sstr } init: { f1: 0, f2: "v2", f3: "123" } expected: ["f3"], ["123"]); test_struct!( inline, t: { #[tabled(inline = true)] id: u8, name: sstr, #[tabled(inline)] ed: Education } pre: { #[derive(Tabled)] struct Education { uni: sstr, graduated: bool } } init: { id: 0, name: "Maxim", ed: Education { uni: "BNTU", graduated: true }} expected: ["u8", "name","uni","graduated"], ["0", "Maxim", "BNTU", "true"] ); test_struct!( inline_with_prefix, t: { #[tabled(rename = "it's an ignored option", inline)] id: u8, name: sstr, #[tabled(inline("education::"))] ed: Education, } pre: { #[derive(Tabled)] struct Education { uni: sstr, graduated: bool } } init: { id: 0, name: "Maxim", ed: Education { uni: "BNTU", graduated: true }} expected: ["u8", "name","education::uni","education::graduated"], ["0", "Maxim", "BNTU", "true"] ); test_struct!( display_with, t: { f1: u8, #[tabled(display_with = "display_option")] f2: Option<sstr>, } pre: { fn display_option(o: &Option<sstr>) -> String { match o { Some(s) => format!("some {s}"), None => "none".to_string(), } } } init: { f1: 0, f2: Some("v2") } expected: ["f1", "f2"], ["0", "some v2"] ); test_struct!( display_with_args, t: { f1: u8, #[tabled(display_with("display_option", 1, 2, 3))] f2: Option<sstr>, } pre: { fn display_option(v1: usize, v2: usize, v3: usize) -> String { format!("{v1} {v2} {v3}") } } init: { f1: 0, f2: Some("v2") } expected: ["f1", "f2"], ["0", "1 2 3"] ); test_struct!( display_with_self_static_method, t: { f1: u8, #[tabled(display_with = "Self::display_option")] f2: Option<sstr>, } pre: { impl TestType { fn display_option(o: &Option<sstr>) -> String { match o { Some(s) => format!("some {s}"), None => "none".to_string(), } } } } init: { f1: 0, f2: Some("v2") } expected: ["f1", "f2"], ["0", "some v2"] ); test_struct!( display_with_self_static_method_2, t: { f1: u8, #[tabled(display_with("Self::display_option", self))] f2: Option<sstr>, } pre: { impl TestType { fn display_option(o: &TestType) -> String { match o.f2 { Some(s) => format!("some {s}"), None => "none".to_string(), } } } } init: { f1: 0, f2: Some("v2") } expected: ["f1", "f2"], ["0", "some v2"] ); test_struct!( display_with_self_2_self_static_method_2, t: { f1: u8, #[tabled(display_with("Self::display_option", self))] f2: Option<sstr>, } pre: { impl TestType { fn display_option(&self) -> String { match self.f2 { Some(s) => format!("some {s}"), None => "none".to_string(), } } } } init: { f1: 0, f2: Some("v2") } expected: ["f1", "f2"], ["0", "some v2"] ); test_struct!( display_with_self_2_self_static_method, t: { f1: u8, #[tabled(display_with("display_option", self))] f2: Option<sstr>, } pre: { fn display_option(o: &TestType) -> String { match o.f2 { Some(s) => format!("some {s}"), None => "none".to_string(), } } } init: { f1: 0, f2: Some("v2") } expected: ["f1", "f2"], ["0", "some v2"] ); test_struct!(order_0, t: { #[tabled(order = 0)] f0: u8, f1: u8, f2: u8 } init: { f0: 0, f1: 1, f2: 2 } expected: ["f0", "f1", "f2"], ["0", "1", "2"]); test_struct!(order_1, t: { #[tabled(order = 1)] f0: u8, f1: u8, f2: u8 } init: { f0: 0, f1: 1, f2: 2 } expected: ["f1", "f0", "f2"], ["1", "0", "2"]); test_struct!(order_2, t: { #[tabled(order = 2)] f0: u8, f1: u8, f2: u8 } init: { f0: 0, f1: 1, f2: 2 } expected: ["f1", "f2", "f0"], ["1", "2", "0"]); test_struct!(order_3, t: { f0: u8, #[tabled(order = 0)] f1: u8, f2: u8 } init: { f0: 0, f1: 1, f2: 2 } expected: ["f1", "f0", "f2"], ["1", "0", "2"]); test_struct!(order_4, t: { f0: u8, #[tabled(order = 1)] f1: u8, f2: u8 } init: { f0: 0, f1: 1, f2: 2 } expected: ["f0", "f1", "f2"], ["0", "1", "2"]); test_struct!(order_5, t: { f0: u8, #[tabled(order = 2)] f1: u8, f2: u8 } init: { f0: 0, f1: 1, f2: 2 } expected: ["f0", "f2", "f1"], ["0", "2", "1"]); test_struct!(order_6, t: { f0: u8, f1: u8, #[tabled(order = 0)] f2: u8 } init: { f0: 0, f1: 1, f2: 2 } expected: ["f2", "f0", "f1"], ["2", "0", "1"]); test_struct!(order_7, t: { f0: u8, f1: u8, #[tabled(order = 1)] f2: u8 } init: { f0: 0, f1: 1, f2: 2 } expected: ["f0", "f2", "f1"], ["0", "2", "1"]); test_struct!(order_8, t: { f0: u8, f1: u8, #[tabled(order = 2)] f2: u8 } init: { f0: 0, f1: 1, f2: 2 } expected: ["f0", "f1", "f2"], ["0", "1", "2"]); test_struct!(order_9, t: { #[tabled(order = 2)] f0: u8, f1: u8, #[tabled(order = 0)] f2: u8 } init: { f0: 0, f1: 1, f2: 2 } expected: ["f2", "f1", "f0"], ["2", "1", "0"]); test_struct!(order_10, t: { #[tabled(order = 2)] f0: u8, #[tabled(order = 1)] f1: u8, f2: u8 } init: { f0: 0, f1: 1, f2: 2 } expected: ["f2", "f1", "f0"], ["2", "1", "0"]); test_struct!(order_11, t: { #[tabled(order = 2)] f0: u8, #[tabled(order = 2)] f1: u8, #[tabled(order = 1)] f2: u8 } init: { f0: 0, f1: 1, f2: 2 } expected: ["f0", "f2", "f1"], ["0", "2", "1"]); test_struct!(order_12, t: { #[tabled(order = 2)] f0: u8, #[tabled(order = 1)] f1: u8, #[tabled(order = 0)] f2: u8 } init: { f0: 0, f1: 1, f2: 2 } expected: ["f2", "f1", "f0"], ["2", "1", "0"]); test_struct!( rename_all, t: #[tabled(rename_all = "UPPERCASE")] { f1: u8, f2: sstr } init: { f1: 0, f2: "v2" } expected: ["F1", "F2"], ["0", "v2"] ); test_struct!( rename_all_override_in_field_by_rename, t: #[tabled(rename_all = "UPPERCASE")] { #[tabled(rename = "213213")] f1: u8, f2: sstr } init: { f1: 0, f2: "v2" } expected: ["213213", "F2"], ["0", "v2"] ); test_struct!( rename_all_override_in_field_by_rename_all, t: #[tabled(rename_all = "UPPERCASE")] { #[tabled(rename_all = "lowercase")] f1: u8, f2: sstr } init: { f1: 0, f2: "v2" } expected: ["f1", "F2"], ["0", "v2"] ); test_struct!( rename_all_field, t: { #[tabled(rename_all = "lowercase")] f1: u8, #[tabled(rename_all = "UPPERCASE")] f2: sstr } init: { f1: 0, f2: "v2" } expected: ["f1", "F2"], ["0", "v2"] ); test_struct!( rename_all_field_overridden_by_rename, t: { #[tabled(rename_all = "lowercase", rename = "Hello")] f1: u8, #[tabled(rename_all = "UPPERCASE")] f2: sstr } init: { f1: 0, f2: "v2" } expected: ["Hello", "F2"], ["0", "v2"] ); // #[test] // fn order_compile_fail_when_order_is_bigger_then_count_fields() { // #[derive(Tabled)] // struct St { // #[tabled(order = 3)] // f0: u8, // f1: u8, // f2: u8, // } // } } test_tuple!(skipped_fields_not_implement_display_tuple, t: { #[tabled(skip)] () sstr }, init: { () "123" }, expected: ["1"], ["123"],); test_struct!(skipped_fields_not_implement_display_struct, t: { #[tabled(skip)] _unit: (), s: sstr } init: { _unit: (), s: "123" } expected: ["s"], ["123"],); test_struct!( skipped_fields_not_implement_display_struct_in_inline, t: { s: sstr, #[tabled(inline)] f: S1 } pre: { #[derive(Tabled)] struct S1 { #[tabled(skip)] _unit: (), s: sstr, } } init: { s: "123", f: S1 { _unit: (), s: "..." } } expected: ["s", "s"], ["123", "..."], ); test_enum!( skipped_fields_not_implement_display_enum, t: { #[tabled(inline("A::"))] A { name: sstr } #[tabled(inline("B::"))] B { issue: usize, name: sstr, #[tabled(skip)] _gem: (), } #[tabled(inline("C::"))] C(usize, #[tabled(skip)] (), sstr) D }, headers: ["A::name", "B::issue", "B::name", "C::0", "C::2", "D"], tests: A { name: "nrdxp" } => ["nrdxp", "", "", "", "", ""], B { _gem: (), issue: 32, name: "nrdxp" } => ["", "32", "nrdxp", "", "", ""], C(32, (), "nrdxp") => ["", "", "", "32", "nrdxp", ""], D => ["", "", "", "", "", "+"], ); test_struct!( ignore_display_with_when_used_with_inline, t: { f1: sstr, f2: sstr, #[tabled(display_with = "print", inline)] f3: usize } init: { f1: "123", f2: "456", f3: 789 } expected: ["f1", "f2", "usize"], ["123", "456", "789"], ); test_struct!( ignore_display_with_when_used_with_inline_2, t: { f1: sstr, f2: sstr, #[tabled(display_with = "print", )] #[tabled(inline)] f3: usize } init: { f1: "123", f2: "456", f3: 789 } expected: ["f1", "f2", "usize"], ["123", "456", "789"], ); test_struct!( display_with_and_rename, t: { f1: sstr, f2: sstr, #[tabled(display_with = "print", rename = "asd")] f3: usize } pre: { #[allow(dead_code)] fn print<T>(_: T) -> String { String::new() } } init: { f1: "123", f2: "456", f3: 789 } expected: ["f1", "f2", "asd"], ["123", "456", ""], ); test_struct!( display_with_and_rename_2, t: { f1: sstr, f2: sstr, #[tabled(display_with = "print")] #[tabled(rename = "asd")] f3: usize } pre: { #[allow(dead_code)] fn print<T>(_: T) -> String { String::new() } } init: { f1: "123", f2: "456", f3: 789 } expected: ["f1", "f2", "asd"], ["123", "456", ""], ); test_struct!( display_with_and_rename_all, t: { f1: sstr, f2: sstr, #[tabled(display_with = "print", rename_all = "UPPERCASE")] f3: usize } pre: { #[allow(dead_code)] fn print<T>(_: T) -> String { String::new() } } init: { f1: "123", f2: "456", f3: 789 } expected: ["f1", "f2", "F3"], ["123", "456", ""], ); #[test] fn rename_all_variants() { macro_rules! test_case { ( $name:ident, $case:expr ) => { #[derive(Tabled)] #[tabled(rename_all = $case)] struct $name { field: usize, } }; } test_case!(S1, "UPPERCASE"); test_case!(S2, "lowercase"); test_case!(S3, "camelCase"); test_case!(S4, "PascalCase"); test_case!(S5, "snake_case"); test_case!(S6, "SCREAMING_SNAKE_CASE"); test_case!(S7, "kebab-case"); test_case!(S8, "verbatimcase"); } // #[test] // fn wrong_rename_all_panic_when_used_as_not_first() { // #[derive(Tabled)] // #[tabled(rename_all = "UPPERCASE")] // #[tabled(rename_all = "some wrong case")] // struct Struct1 { // field: usize, // } // let st = Struct1 { field: 789 }; // assert_eq!(Struct1::headers(), vec!["FIELD"],); // assert_eq!(st.fields(), vec!["789"]); // #[derive(Tabled)] // #[tabled(rename_all = "UPPERCASE", rename_all = "some wrong case")] // struct Struct2 { // field: usize, // } // let st = Struct2 { field: 789 }; // assert_eq!(Struct1::headers(), vec!["FIELD"],); // assert_eq!(st.fields(), vec!["789"]); // } #[test] fn rename_all_gets_last_value() { #[derive(Tabled)] #[tabled(rename_all = "UPPERCASE")] #[tabled(rename_all = "PascalCase")] struct Struct1 { field: usize, } let st = Struct1 { field: 789 }; assert_eq!(Struct1::headers(), vec!["Field"],); assert_eq!(st.fields(), vec!["789"]); #[derive(Tabled)] #[tabled(rename_all = "UPPERCASE", rename_all = "PascalCase")] struct Struct2 { field: usize, } let st = Struct2 { field: 789 }; assert_eq!(Struct1::headers(), vec!["Field"],); assert_eq!(st.fields(), vec!["789"]); } #[test] fn test_order_skip_usage() { #[derive(Tabled, Default)] pub struct Example { #[tabled(skip)] #[allow(dead_code)] id: usize, name: String, #[tabled(order = 0)] details: String, } #[derive(Tabled, Default)] pub struct Example2 { #[tabled(skip)] #[allow(dead_code)] id: usize, name: String, #[tabled(order = 1)] details: String, } assert_eq!(Example::headers(), vec!["details", "name"],); assert_eq!(Example::default().fields(), vec!["", ""]); } #[test] fn test_skip_enum_0() { #[allow(dead_code)] #[derive(Tabled)] enum Letters { Vowels { character: char, lang: u8, }, Consonant(char), #[tabled(skip)] Digit, } assert_eq!(Letters::headers(), vec!["Vowels", "Consonant"]); assert_eq!(Letters::Consonant('c').fields(), vec!["", "+"]); assert_eq!(Letters::Digit.fields(), vec!["", ""]); } mod __ { #[test] fn dont_import_the_trait() { #[derive(tabled::Tabled)] struct __; } }
use std::{borrow::Cow, collections::HashMap, sync::Arc, time::Duration}; use bson::Document; use serde::Deserialize; use crate::{ bson::{doc, Bson}, coll::options::FindOptions, error::{CommandError, Error, ErrorKind}, event::cmap::CmapEvent, hello::LEGACY_HELLO_COMMAND_NAME, options::{AuthMechanism, ClientOptions, Credential, ListDatabasesOptions, ServerAddress}, runtime, selection_criteria::{ReadPreference, ReadPreferenceOptions, SelectionCriteria}, test::{ log_uncaptured, util::TestClient, Event, EventHandler, FailCommandOptions, FailPoint, FailPointMode, SdamEvent, CLIENT_OPTIONS, SERVER_API, }, Client, ServerType, }; #[derive(Debug, Deserialize)] struct ClientMetadata { pub driver: DriverMetadata, #[serde(rename = "os")] pub _os: Document, // included here to ensure it's included in the metadata pub platform: String, } #[derive(Debug, Deserialize)] struct DriverMetadata { pub name: String, pub version: String, } #[cfg_attr(feature = "tokio-runtime", tokio::test)] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn metadata_sent_in_handshake() { let client = TestClient::new().await; // skip on other topologies due to different currentOp behavior if !client.is_standalone() || !client.is_replica_set() { log_uncaptured("skipping metadata_sent_in_handshake due to unsupported topology"); return; } let result = client .database("admin") .run_command( doc! { "currentOp": 1, "command.currentOp": { "$exists": true } }, None, ) .await .unwrap(); let metadata_document = result.get_array("inprog").unwrap()[0] .as_document() .unwrap() .get_document("clientMetadata") .unwrap() .clone(); let metadata: ClientMetadata = bson::from_document(metadata_document).unwrap(); assert_eq!(metadata.driver.name, "mongo-rust-driver"); assert_eq!(metadata.driver.version, env!("CARGO_PKG_VERSION")); #[cfg(feature = "tokio-runtime")] { assert!( metadata.platform.contains("tokio"), "platform should contain tokio: {}", metadata.platform ); } #[cfg(feature = "async-std-runtime")] { assert!( metadata.platform.contains("async-std"), "platform should contain async-std: {}", metadata.platform ); } #[cfg(any(feature = "sync", feature = "tokio-sync"))] { assert!( metadata.platform.contains("sync"), "platform should contain sync: {}", metadata.platform ); } } #[cfg_attr(feature = "tokio-runtime", tokio::test)] #[cfg_attr(feature = "async-std-runtime", async_std::test)] #[function_name::named] async fn connection_drop_during_read() { let mut options = CLIENT_OPTIONS.get().await.clone(); options.max_pool_size = Some(1); let client = Client::with_options(options.clone()).unwrap(); let db = client.database("test"); db.collection(function_name!()) .insert_one(doc! { "x": 1 }, None) .await .unwrap(); let _: Result<_, _> = runtime::timeout( Duration::from_millis(50), db.run_command( doc! { "count": function_name!(), "query": { "$where": "sleep(100) && true" } }, None, ), ) .await; runtime::delay_for(Duration::from_millis(200)).await; let build_info_response = db.run_command(doc! { "buildInfo": 1 }, None).await.unwrap(); // Ensure that the response to `buildInfo` is read, not the response to `count`. assert!(build_info_response.get("version").is_some()); } #[cfg_attr(feature = "tokio-runtime", tokio::test)] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn server_selection_timeout_message() { if CLIENT_OPTIONS.get().await.repl_set_name.is_none() { log_uncaptured("skipping server_selection_timeout_message due to missing replica set name"); return; } let mut tag_set = HashMap::new(); tag_set.insert("asdfasdf".to_string(), "asdfadsf".to_string()); let unsatisfiable_read_preference = ReadPreference::Secondary { options: ReadPreferenceOptions::builder() .tag_sets(vec![tag_set]) .build(), }; let mut options = CLIENT_OPTIONS.get().await.clone(); options.server_selection_timeout = Some(Duration::from_millis(500)); let client = Client::with_options(options.clone()).unwrap(); let db = client.database("test"); let error = db .run_command( doc! { "ping": 1 }, SelectionCriteria::ReadPreference(unsatisfiable_read_preference), ) .await .expect_err("should fail with server selection timeout error"); let error_description = format!("{}", error); for host in options.hosts.iter() { assert!(error_description.contains(format!("{}", host).as_str())); } } #[cfg_attr(feature = "tokio-runtime", tokio::test)] #[cfg_attr(feature = "async-std-runtime", async_std::test)] #[function_name::named] async fn list_databases() { let expected_dbs = &[ format!("{}1", function_name!()), format!("{}2", function_name!()), format!("{}3", function_name!()), ]; let client = TestClient::new().await; for name in expected_dbs { client.database(name).drop(None).await.unwrap(); } let prev_dbs = client.list_databases(None, None).await.unwrap(); for name in expected_dbs { assert!(!prev_dbs.iter().any(|doc| doc.name.as_str() == name)); let db = client.database(name); db.collection("foo") .insert_one(doc! { "x": 1 }, None) .await .unwrap(); } let new_dbs = client.list_databases(None, None).await.unwrap(); let new_dbs: Vec<_> = new_dbs .into_iter() .filter(|db_spec| expected_dbs.contains(&db_spec.name)) .collect(); assert_eq!(new_dbs.len(), expected_dbs.len()); for name in expected_dbs { let db_doc = new_dbs .iter() .find(|db_spec| db_spec.name.as_str() == name) .unwrap(); assert!(db_doc.size_on_disk > 0); assert!(!db_doc.empty); } } #[cfg_attr(feature = "tokio-runtime", tokio::test)] #[cfg_attr(feature = "async-std-runtime", async_std::test)] #[function_name::named] async fn list_database_names() { let client = TestClient::new().await; let expected_dbs = &[ format!("{}1", function_name!()), format!("{}2", function_name!()), format!("{}3", function_name!()), ]; for name in expected_dbs { client.database(name).drop(None).await.unwrap(); } let prev_dbs = client.list_database_names(None, None).await.unwrap(); for name in expected_dbs { assert!(!prev_dbs.iter().any(|db_name| db_name == name)); let db = client.database(name); db.collection("foo") .insert_one(doc! { "x": 1 }, None) .await .unwrap(); } let new_dbs = client.list_database_names(None, None).await.unwrap(); for name in expected_dbs { assert_eq!(new_dbs.iter().filter(|db_name| db_name == &name).count(), 1); } } #[cfg_attr(feature = "tokio-runtime", tokio::test)] #[cfg_attr(feature = "async-std-runtime", async_std::test)] #[function_name::named] async fn list_authorized_databases() { let client = TestClient::new().await; if client.server_version_lt(4, 0) || !client.auth_enabled() { log_uncaptured("skipping list_authorized_databases due to test configuration"); return; } let dbs = &[ format!("{}1", function_name!()), format!("{}2", function_name!()), ]; for name in dbs { client .database(name) .create_collection("coll", None) .await .unwrap(); client .create_user( &format!("user_{}", name), "pwd", &[Bson::from(doc! { "role": "readWrite", "db": name })], &[AuthMechanism::ScramSha256], None, ) .await .unwrap(); } for name in dbs { let mut options = CLIENT_OPTIONS.get().await.clone(); let credential = Credential::builder() .username(format!("user_{}", name)) .password(String::from("pwd")) .build(); options.credential = Some(credential); let client = Client::with_options(options).unwrap(); let options = ListDatabasesOptions::builder() .authorized_databases(true) .build(); let result = client.list_database_names(None, options).await.unwrap(); assert_eq!(result.len(), 1); assert_eq!(result.get(0).unwrap(), name); } for name in dbs { client.database(name).drop(None).await.unwrap(); } } fn is_auth_error(error: Error) -> bool { matches!(*error.kind, ErrorKind::Authentication { .. }) } /// Performs an operation that requires authentication and verifies that it either succeeded or /// failed with an authentication error according to the `should_succeed` parameter. async fn auth_test(client: Client, should_succeed: bool) { let result = client.list_database_names(None, None).await; if should_succeed { result.expect("operation should have succeeded"); } else { assert!(is_auth_error(result.unwrap_err())); } } /// Attempts to authenticate using the given username/password, optionally specifying a mechanism /// via the `ClientOptions` api. /// /// Asserts that the authentication's success matches the provided parameter. async fn auth_test_options( user: &str, password: &str, mechanism: Option<AuthMechanism>, success: bool, ) { let mut options = CLIENT_OPTIONS.get().await.clone(); options.max_pool_size = Some(1); options.credential = Credential { username: Some(user.to_string()), password: Some(password.to_string()), mechanism, ..Default::default() } .into(); auth_test(Client::with_options(options).unwrap(), success).await; } /// Attempts to authenticate using the given username/password, optionally specifying a mechanism /// via the URI api. /// /// Asserts that the authentication's success matches the provided parameter. async fn auth_test_uri( user: &str, password: &str, mechanism: Option<AuthMechanism>, should_succeed: bool, ) { // A server API version cannot be set in the connection string. if SERVER_API.is_some() { log_uncaptured("Skipping URI auth test due to server API version being set"); return; } let host = CLIENT_OPTIONS .get() .await .hosts .iter() .map(ToString::to_string) .collect::<Vec<String>>() .join(","); let mechanism_str = match mechanism { Some(mech) => Cow::Owned(format!("&authMechanism={}", mech.as_str())), None => Cow::Borrowed(""), }; let mut uri = format!( "mongodb://{}:{}@{}/?maxPoolSize=1{}", user, password, host, mechanism_str.as_ref() ); if let Some(ref tls_options) = CLIENT_OPTIONS.get().await.tls_options() { if let Some(true) = tls_options.allow_invalid_certificates { uri.push_str("&tlsAllowInvalidCertificates=true"); } if let Some(ref ca_file_path) = tls_options.ca_file_path { uri.push_str("&tlsCAFile="); uri.push_str( &percent_encoding::utf8_percent_encode( ca_file_path.to_str().unwrap(), percent_encoding::NON_ALPHANUMERIC, ) .to_string(), ); } if let Some(ref cert_key_file_path) = tls_options.cert_key_file_path { uri.push_str("&tlsCertificateKeyFile="); uri.push_str( &percent_encoding::utf8_percent_encode( cert_key_file_path.to_str().unwrap(), percent_encoding::NON_ALPHANUMERIC, ) .to_string(), ); } } if let Some(true) = CLIENT_OPTIONS.get().await.load_balanced { uri.push_str("&loadBalanced=true"); } auth_test( Client::with_uri_str(uri.as_str()).await.unwrap(), should_succeed, ) .await; } /// Tries to authenticate with the given credentials using the given mechanisms, both by explicitly /// specifying each mechanism and by relying on mechanism negotiation. /// /// If only one mechanism is supplied, this will also test that using the other SCRAM mechanism will /// fail. async fn scram_test( client: &TestClient, username: &str, password: &str, mechanisms: &[AuthMechanism], ) { for mechanism in mechanisms { auth_test_uri(username, password, Some(mechanism.clone()), true).await; auth_test_uri(username, password, None, true).await; auth_test_options(username, password, Some(mechanism.clone()), true).await; auth_test_options(username, password, None, true).await; } // If only one scram mechanism is specified, verify the other doesn't work. if mechanisms.len() == 1 && client.server_version_gte(4, 0) { let other = match mechanisms[0] { AuthMechanism::ScramSha1 => AuthMechanism::ScramSha256, _ => AuthMechanism::ScramSha1, }; auth_test_uri(username, password, Some(other.clone()), false).await; auth_test_options(username, password, Some(other), false).await; } } #[cfg_attr(feature = "tokio-runtime", tokio::test)] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn scram_sha1() { let client = TestClient::new().await; if !client.auth_enabled() { log_uncaptured("skipping scram_sha1 due to missing authentication"); return; } client .create_user( "sha1", "sha1", &[Bson::from("root")], &[AuthMechanism::ScramSha1], None, ) .await .unwrap(); scram_test(&client, "sha1", "sha1", &[AuthMechanism::ScramSha1]).await; } #[cfg_attr(feature = "tokio-runtime", tokio::test)] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn scram_sha256() { let client = TestClient::new().await; if client.server_version_lt(4, 0) || !client.auth_enabled() { log_uncaptured("skipping scram_sha256 due to test configuration"); return; } client .create_user( "sha256", "sha256", &[Bson::from("root")], &[AuthMechanism::ScramSha256], None, ) .await .unwrap(); scram_test(&client, "sha256", "sha256", &[AuthMechanism::ScramSha256]).await; } #[cfg_attr(feature = "tokio-runtime", tokio::test)] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn scram_both() { let client = TestClient::new().await; if client.server_version_lt(4, 0) || !client.auth_enabled() { log_uncaptured("skipping scram_both due to test configuration"); return; } client .create_user( "both", "both", &[Bson::from("root")], &[AuthMechanism::ScramSha1, AuthMechanism::ScramSha256], None, ) .await .unwrap(); scram_test( &client, "both", "both", &[AuthMechanism::ScramSha1, AuthMechanism::ScramSha256], ) .await; } #[cfg_attr(feature = "tokio-runtime", tokio::test)] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn scram_missing_user_uri() { let client = TestClient::new().await; if !client.auth_enabled() { log_uncaptured("skipping scram_missing_user_uri due to missing authentication"); return; } auth_test_uri("adsfasdf", "ASsdfsadf", None, false).await; } #[cfg_attr(feature = "tokio-runtime", tokio::test)] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn scram_missing_user_options() { let client = TestClient::new().await; if !client.auth_enabled() { log_uncaptured("skipping scram_missing_user_options due to missing authentication"); return; } auth_test_options("sadfasdf", "fsdadsfasdf", None, false).await; } #[cfg_attr(feature = "tokio-runtime", tokio::test)] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn saslprep() { let client = TestClient::new().await; if client.server_version_lt(4, 0) || !client.auth_enabled() { log_uncaptured("skipping saslprep due to test configuration"); return; } client .create_user( "IX", "IX", &[Bson::from("root")], &[AuthMechanism::ScramSha256], None, ) .await .unwrap(); client .create_user( "\u{2168}", "\u{2163}", &[Bson::from("root")], &[AuthMechanism::ScramSha256], None, ) .await .unwrap(); auth_test_options("IX", "IX", None, true).await; auth_test_options("IX", "I\u{00AD}X", None, true).await; auth_test_options("\u{2168}", "IV", None, true).await; auth_test_options("\u{2168}", "I\u{00AD}V", None, true).await; auth_test_uri("IX", "IX", None, true).await; auth_test_uri("IX", "I%C2%ADX", None, true).await; auth_test_uri("%E2%85%A8", "IV", None, true).await; auth_test_uri("%E2%85%A8", "I%C2%ADV", None, true).await; } #[cfg_attr(feature = "tokio-runtime", tokio::test)] #[cfg_attr(feature = "async-std-runtime", async_std::test)] #[function_name::named] async fn x509_auth() { let username = match std::env::var("MONGO_X509_USER") { Ok(user) => user, Err(_) => return, }; let client = TestClient::new().await; let drop_user_result = client .database("$external") .run_command(doc! { "dropUser": &username }, None) .await; match drop_user_result.map_err(|e| *e.kind) { Err(ErrorKind::Command(CommandError { code: 11, .. })) | Ok(_) => {} e @ Err(_) => { e.unwrap(); } }; client .create_user( &username, None, &[doc! { "role": "readWrite", "db": function_name!() }.into()], &[AuthMechanism::MongoDbX509], "$external", ) .await .unwrap(); let mut options = CLIENT_OPTIONS.get().await.clone(); options.credential = Some( Credential::builder() .mechanism(AuthMechanism::MongoDbX509) .build(), ); let client = TestClient::with_options(Some(options)).await; client .database(function_name!()) .collection::<Document>(function_name!()) .find_one(None, None) .await .unwrap(); } #[cfg_attr(feature = "tokio-runtime", tokio::test)] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn plain_auth() { if std::env::var("MONGO_PLAIN_AUTH_TEST").is_err() { log_uncaptured("skipping plain_auth due to environment variable MONGO_PLAIN_AUTH_TEST"); return; } let options = ClientOptions::builder() .hosts(vec![ServerAddress::Tcp { host: "ldaptest.10gen.cc".into(), port: None, }]) .credential( Credential::builder() .mechanism(AuthMechanism::Plain) .username("drivers-team".to_string()) .password("mongor0x$xgen".to_string()) .build(), ) .build(); let client = Client::with_options(options).unwrap(); let coll = client.database("ldap").collection("test"); let doc = coll.find_one(None, None).await.unwrap().unwrap(); #[derive(Debug, Deserialize, PartialEq)] struct TestDocument { ldap: bool, authenticated: String, } let doc: TestDocument = bson::from_document(doc).unwrap(); assert_eq!( doc, TestDocument { ldap: true, authenticated: "yeah".into() } ); } /// Test verifies that retrying a commitTransaction operation after a checkOut /// failure works. #[cfg_attr(feature = "tokio-runtime", tokio::test(flavor = "multi_thread"))] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn retry_commit_txn_check_out() { let setup_client = TestClient::new().await; if !setup_client.is_replica_set() { log_uncaptured("skipping retry_commit_txn_check_out due to non-replicaset topology"); return; } if !setup_client.supports_transactions() { log_uncaptured("skipping retry_commit_txn_check_out due to lack of transaction support"); return; } if !setup_client.supports_fail_command_appname_initial_handshake() { log_uncaptured( "skipping retry_commit_txn_check_out due to insufficient failCommand support", ); return; } if setup_client.supports_streaming_monitoring_protocol() { log_uncaptured("skipping retry_commit_txn_check_out due to streaming protocol support"); return; } // ensure namespace exists setup_client .database("retry_commit_txn_check_out") .collection("retry_commit_txn_check_out") .insert_one(doc! {}, None) .await .unwrap(); let mut options = CLIENT_OPTIONS.get().await.clone(); let handler = Arc::new(EventHandler::new()); options.cmap_event_handler = Some(handler.clone()); options.sdam_event_handler = Some(handler.clone()); options.heartbeat_freq = Some(Duration::from_secs(120)); options.app_name = Some("retry_commit_txn_check_out".to_string()); let client = Client::with_options(options).unwrap(); let mut session = client.start_session(None).await.unwrap(); session.start_transaction(None).await.unwrap(); // transition transaction to "in progress" so that the commit // actually executes an operation. client .database("retry_commit_txn_check_out") .collection("retry_commit_txn_check_out") .insert_one_with_session(doc! {}, None, &mut session) .await .unwrap(); // enable a fail point that clears the connection pools so that // commitTransaction will create a new connection during check out. let fp = FailPoint::fail_command( &["ping"], FailPointMode::Times(1), FailCommandOptions::builder().error_code(11600).build(), ); let _guard = setup_client.enable_failpoint(fp, None).await.unwrap(); let mut subscriber = handler.subscribe(); client .database("foo") .run_command(doc! { "ping": 1 }, None) .await .unwrap_err(); // failing with a state change error will request an immediate check // wait for the mark unknown and subsequent succeeded heartbeat let mut primary = None; subscriber .wait_for_event(Duration::from_secs(1), |e| { if let Event::Sdam(SdamEvent::ServerDescriptionChanged(event)) = e { if event.is_marked_unknown_event() { primary = Some(event.address.clone()); return true; } } false }) .await .expect("should see marked unknown event"); // If this test were run when using the streaming protocol, this assertion would never succeed. // This is because the monitors are waiting for the next heartbeat from the server for // heartbeatFrequencyMS (which is 2 minutes) and ignore the immediate check requests from the // ping command in the meantime due to already being in the middle of their checks. subscriber .wait_for_event(Duration::from_secs(1), |e| { if let Event::Sdam(SdamEvent::ServerDescriptionChanged(event)) = e { if &event.address == primary.as_ref().unwrap() && event.previous_description.server_type() == ServerType::Unknown { return true; } } false }) .await .expect("should see mark available event"); // enable a failpoint on the handshake to cause check_out // to fail with a retryable error let fp = FailPoint::fail_command( &[LEGACY_HELLO_COMMAND_NAME, "hello"], FailPointMode::Times(1), FailCommandOptions::builder() .error_code(11600) .app_name("retry_commit_txn_check_out".to_string()) .build(), ); let _guard2 = setup_client.enable_failpoint(fp, None).await.unwrap(); // finally, attempt the commit. // this should succeed due to retry session.commit_transaction().await.unwrap(); // ensure the first check out attempt fails subscriber .wait_for_event(Duration::from_secs(1), |e| { matches!(e, Event::Cmap(CmapEvent::ConnectionCheckoutFailed(_))) }) .await .expect("should see check out failed event"); // ensure the second one succeeds subscriber .wait_for_event(Duration::from_secs(1), |e| { matches!(e, Event::Cmap(CmapEvent::ConnectionCheckedOut(_))) }) .await .expect("should see checked out event"); } /// Verifies that `Client::shutdown` succeeds. #[cfg_attr(feature = "tokio-runtime", tokio::test)] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn manual_shutdown_with_nothing() { let client = Client::test_builder().build().await.into_client(); client.shutdown().await; } /// Verifies that `Client::shutdown` succeeds when resources have been dropped. #[cfg_attr(feature = "tokio-runtime", tokio::test)] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn manual_shutdown_with_resources() { let events = Arc::new(EventHandler::new()); let client = Client::test_builder() .event_handler(Arc::clone(&events)) .build() .await; if !client.supports_transactions() { log_uncaptured("Skipping manual_shutdown_with_resources: no transaction support"); return; } let db = client.database("shutdown_test"); db.drop(None).await.unwrap(); let coll = db.collection::<Document>("test"); coll.insert_many([doc! {}, doc! {}], None).await.unwrap(); let bucket = db.gridfs_bucket(None); // Scope to force drop of resources { // Exhausted cursors don't need cleanup, so make sure there's more than one batch to fetch let _cursor = coll .find(None, FindOptions::builder().batch_size(1).build()) .await .unwrap(); // Similarly, sessions need an in-progress transaction to have cleanup. let mut session = client.start_session(None).await.unwrap(); if session.start_transaction(None).await.is_err() { // Transaction start can transiently fail; if so, just bail out of the test. log_uncaptured("Skipping manual_shutdown_with_resources: transaction start failed"); return; } if coll .insert_one_with_session(doc! {}, None, &mut session) .await .is_err() { // Likewise for transaction operations. log_uncaptured("Skipping manual_shutdown_with_resources: transaction operation failed"); return; } let _stream = bucket.open_upload_stream("test", None); } let is_sharded = client.is_sharded(); client.into_client().shutdown().await; if !is_sharded { // killCursors doesn't always execute on sharded clusters due to connection pinning assert!(!events .get_command_started_events(&["killCursors"]) .is_empty()); } assert!(!events .get_command_started_events(&["abortTransaction"]) .is_empty()); assert!(!events.get_command_started_events(&["delete"]).is_empty()); } /// Verifies that `Client::shutdown_immediate` succeeds. #[cfg_attr(feature = "tokio-runtime", tokio::test)] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn manual_shutdown_immediate_with_nothing() { let client = Client::test_builder().build().await.into_client(); client.shutdown_immediate().await; } /// Verifies that `Client::shutdown_immediate` succeeds without waiting for resources. #[cfg_attr(feature = "tokio-runtime", tokio::test)] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn manual_shutdown_immediate_with_resources() { let events = Arc::new(EventHandler::new()); let client = Client::test_builder() .event_handler(Arc::clone(&events)) .build() .await; if !client.supports_transactions() { log_uncaptured("Skipping manual_shutdown_immediate_with_resources: no transaction support"); return; } let db = client.database("shutdown_test"); db.drop(None).await.unwrap(); let coll = db.collection::<Document>("test"); coll.insert_many([doc! {}, doc! {}], None).await.unwrap(); let bucket = db.gridfs_bucket(None); // Resources are scoped to past the `shutdown_immediate`. // Exhausted cursors don't need cleanup, so make sure there's more than one batch to fetch let _cursor = coll .find(None, FindOptions::builder().batch_size(1).build()) .await .unwrap(); // Similarly, sessions need an in-progress transaction to have cleanup. let mut session = client.start_session(None).await.unwrap(); session.start_transaction(None).await.unwrap(); coll.insert_one_with_session(doc! {}, None, &mut session) .await .unwrap(); let _stream = bucket.open_upload_stream("test", None); client.into_client().shutdown_immediate().await; assert!(events .get_command_started_events(&["killCursors"]) .is_empty()); assert!(events .get_command_started_events(&["abortTransaction"]) .is_empty()); assert!(events.get_command_started_events(&["delete"]).is_empty()); } // Verifies that `Client::warm_connection_pool` succeeds. #[cfg_attr(feature = "tokio-runtime", tokio::test)] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn warm_connection_pool() { let client = Client::test_builder() .options({ let mut opts = CLIENT_OPTIONS.get().await.clone(); opts.min_pool_size = Some(10); opts }) .build() .await; client.warm_connection_pool().await; // Validate that a command executes. client.list_database_names(None, None).await.unwrap(); }
use sorbet::tap::Monitor; use std::thread::sleep; use std::time::Duration; fn main() { let mut monitor = Monitor::new().repeat(false).pressed(true); let mut count = 1; let _ = monitor.spawn(); 'demo: loop { println!("Loop #{}", count); while let Some(event) = monitor.next() { println!("Monitor Event: {:?}", event); } count += 1; if count == 15 { break 'demo; } sleep(Duration::from_secs(1)); } }
pub mod point; pub mod rect; pub type Point<T> = point::Point<T>; pub type Rect<T> = rect::Rect<T>; pub trait One { fn one() -> Self; } impl One for f32 { fn one() -> f32 { f32::default() + 1.0 } } impl One for f64 { fn one() -> f64 { f64::default() + 1.0 } } impl One for i16 { fn one() -> i16 { i16::default() + 1 } } impl One for i32 { fn one() -> i32 { i32::default() + 1 } } impl One for i64 { fn one() -> i64 { i64::default() + 1 } } impl One for i8 { fn one() -> i8 { i8::default() + 1 } } impl One for isize { fn one() -> isize { isize::default() + 1 } } impl One for u16 { fn one() -> u16 { u16::default() + 1 } } impl One for u32 { fn one() -> u32 { u32::default() + 1 } } impl One for u64 { fn one() -> u64 { u64::default() + 1 } } impl One for u8 { fn one() -> u8 { u8::default() + 1 } } impl One for usize { fn one() -> usize { usize::default() + 1 } }
use std::error::Error; use std::fmt::{Debug, Display, Formatter, Result as FmtResult}; use futures::future::SharedError; use asset::AssetSpec; /// Error type returned when loading an asset. /// Includes the `AssetSpec` and the error (`LoadError`). #[derive(Debug)] pub struct AssetError<A, F, S> { /// The specifier of the asset which failed to load pub asset: AssetSpec, /// The error that's been raised. pub error: LoadError<A, F, S>, } impl<A, F, S> AssetError<A, F, S> { pub(crate) fn new(asset: AssetSpec, error: LoadError<A, F, S>) -> Self { AssetError { asset, error } } } impl<A, F, S> Display for AssetError<A, F, S> where A: Display, F: Display, S: Display, { fn fmt(&self, f: &mut Formatter) -> FmtResult { write!( f, "Failed to load asset \"{}\" of format \"{:?}\" from storage with id \"{}\": {}", &self.asset.name, &self.asset.exts, &self.asset.store.id(), &self.error ) } } /// Combined error type which is produced when loading an /// asset. This error does not include information which asset /// failed to load. For that, please look at `AssetError`. #[derive(Clone, Debug)] pub enum LoadError<A, F, S> { /// The conversion from data -> asset failed. AssetError(A), /// The conversion from bytes -> data failed. FormatError(F), /// The storage was unable to retrieve the requested data. StorageError(S), } impl<A, F, S> Display for LoadError<A, F, S> where A: Display, F: Display, S: Display, { fn fmt(&self, f: &mut Formatter) -> FmtResult { match *self { LoadError::AssetError(ref e) => write!(f, "Failed to load asset: {}", e), LoadError::FormatError(ref e) => write!(f, "Failed to load data: {}", e), LoadError::StorageError(ref e) => write!(f, "Failed to load from storage: {}", e), } } } impl<A, F, S> Error for AssetError<A, F, S> where A: Error, F: Error, S: Error, { fn description(&self) -> &str { "Failed to load asset" } fn cause(&self) -> Option<&Error> { Some(&self.error) } } impl<A, F, S> Error for LoadError<A, F, S> where A: Error, F: Error, S: Error, { fn cause(&self) -> Option<&Error> { let cause: &Error = match *self { LoadError::AssetError(ref e) => e, LoadError::FormatError(ref e) => e, LoadError::StorageError(ref e) => e, }; Some(cause) } fn description(&self) -> &str { match *self { LoadError::AssetError(_) => "Failed to load asset", LoadError::FormatError(_) => "Failed to load data", LoadError::StorageError(_) => "Failed to load from storage", } } } /// An error type which cannot be instantiated. /// Used as a placeholder for associated error types if /// something cannot fail. #[derive(Debug)] pub enum NoError {} impl Display for NoError { fn fmt(&self, _: &mut Formatter) -> FmtResult { match *self {} } } impl Error for NoError { fn description(&self) -> &str { match *self {} } } /// Shared version of error pub struct SharedAssetError<E>(SharedError<E>); impl<E> AsRef<E> for SharedAssetError<E> { fn as_ref(&self) -> &E { &*self.0 } } impl<E> Error for SharedAssetError<E> where E: Error, { fn description(&self) -> &str { self.as_ref().description() } fn cause(&self) -> Option<&Error> { self.as_ref().cause() } } impl<E> Debug for SharedAssetError<E> where E: Debug, { fn fmt(&self, f: &mut Formatter) -> FmtResult { self.as_ref().fmt(f) } } impl<E> Display for SharedAssetError<E> where E: Display, { fn fmt(&self, f: &mut Formatter) -> FmtResult { self.as_ref().fmt(f) } } impl<E> From<SharedError<E>> for SharedAssetError<E> { fn from(err: SharedError<E>) -> Self { SharedAssetError(err) } }
#![feature(test)] use std::usize; extern crate console_error_panic_hook; use wasm_bindgen::prelude::*; extern crate web_sys; use crate::CameFrom::Match; use crate::CameFrom::SkipA; use crate::CameFrom::SkipB; extern crate test; use test::Bencher; #[wasm_bindgen] #[derive(Debug)] pub struct ScoredAlignment { score: isize, alignment: Vec<(Option<char>, Option<char>)>, } #[wasm_bindgen] impl ScoredAlignment { pub fn score(&self) -> isize { self.score } pub fn alignment(&self) -> String { self.alignment .iter() .map(|v| format!("{}{}", v.0.unwrap_or('_'), v.1.unwrap_or('_'))) .collect() } } pub trait ScoringRubric<T: PartialEq> { fn compare(&self, a: Option<&T>, b: Option<&T>) -> i8 { if a.is_some() != b.is_some() { -1 // gap in alignment } else { if a.unwrap() == b.unwrap() { 1 // match } else { -1 // mismatch } } } } struct SimpleScoringRubric {} impl<T: PartialEq> ScoringRubric<T> for SimpleScoringRubric {} #[derive(Clone, Copy, Debug)] pub enum CameFrom { Match, SkipA, SkipB, } #[wasm_bindgen] pub struct AlignmentTable { a: String, b: String, alignment_matrix: Vec<Option<(isize, CameFrom)>>, scoring_rubric: Box<dyn ScoringRubric<char>>, } #[wasm_bindgen] impl AlignmentTable { pub fn new(a: &str) -> AlignmentTable { init_panic_hook(); let blen = (a.len() as f32 * 1.25) as usize; let capacity = (1 + a.len()) * (1 + blen); let scratch: Vec<Option<(isize, CameFrom)>> = vec![None; capacity]; let mut ret = AlignmentTable { b: String::with_capacity(blen), a: a.to_string(), alignment_matrix: scratch, scoring_rubric: Box::new(SimpleScoringRubric {}), }; ret.initialize(); ret.align(0); ret } fn get_alignment_at(&self, (r, c): (usize, usize)) -> Option<(isize, CameFrom)> { self.alignment_matrix[r * (self.a.len() + 1) + c] } fn set_alignment_at(&mut self, (r, c): (usize, usize), v: (isize, CameFrom)) { self.alignment_matrix[r * (self.a.len() + 1) + c] = Some(v) } fn initialize(&mut self) { for c in 0..=self.a.len() { self.set_alignment_at((0, c), (-1 * (c as isize), SkipA)) } for r in 0..=self.b.len() { self.set_alignment_at((r, 0), (-1 * (r as isize), SkipB)) } } fn initialize_new_rows(&mut self, new_rows: usize) { for r in self.b.len() - new_rows..=self.b.len() { self.set_alignment_at((r, 0), (-1 * (r as isize), SkipB)) } } pub fn score_at(&self, row: usize, col: usize) -> isize { let ret = self.get_alignment_at((row, col)).unwrap().0; ret } pub fn replace_b(&mut self, bitems: &str) -> usize { let common_prefix = bitems .chars() .zip(self.b.chars()) .take_while(|(a, b)| a == b) .count(); self.b.truncate(common_prefix); self.b.push_str(&bitems[common_prefix..]); self.initialize_new_rows(bitems.len() - common_prefix); self.align(common_prefix); common_prefix } pub fn type_into_b(&mut self, bitems: &str) -> usize { self.b.push_str(bitems); self.initialize_new_rows(bitems.len()); self.align(self.b.len() - bitems.len()); self.b.len() } pub fn backspace_into_b(&mut self, count: usize) -> usize { for _c in 0..count { self.b.pop(); } self.b.len() } pub fn backword_into_b(&mut self, count: usize) -> usize { for _c in 0..count { while self.b.pop().unwrap_or('_') == ' ' {} while self.b.pop().unwrap_or(' ') != ' ' {} } if self.b.len() > 0 { self.b.push(' ') } self.b.len() } pub fn align(&mut self, previous_b_length: usize) -> Option<bool> { let start_from = previous_b_length + 1; for r in start_from..=self.b.len() { for c in 1..=self.a.len() { let a0 = self.a.as_bytes()[(c - 1)] as char; let b0 = self.b.as_bytes()[(r - 1)] as char; let a = Some(&a0); let b = Some(&b0); let advance_both = self.score_at(r - 1, c - 1) + self.scoring_rubric.compare(a, b) as isize; let advance_a = self.score_at(r, c - 1) + self.scoring_rubric.compare(a, None) as isize; let advance_b = self.score_at(r - 1, c) + self.scoring_rubric.compare(None, b) as isize; let best = *[ (advance_both, Match), (advance_a, SkipA), (advance_b, SkipB), ] .iter() .max_by_key(|v| v.0) .unwrap(); self.set_alignment_at((r, c), best); } } Some(true) // Some(()) isn't supported by wasm-bindgen } pub fn best_scored_alignment(&self) -> ScoredAlignment { let best_col = (0..=self.a.len()) .max_by_key(|&c| self.score_at(self.b.len(), c)) .unwrap(); let final_position = (self.b.len(), best_col); let mut current_position = final_position; let mut best_alignment = vec![]; while current_position != (0usize, 0usize) { let prev_step = self .get_alignment_at((current_position.0, current_position.1)) .unwrap() .1; match prev_step { Match => { best_alignment.push(( Some(self.a.as_bytes()[current_position.1 - 1] as char), Some(self.b.as_bytes()[current_position.0 - 1] as char), )); current_position = (current_position.0 - 1, current_position.1 - 1); } SkipA => { best_alignment.push(( Some(self.a.as_bytes()[current_position.1 - 1] as char), None, )); current_position = (current_position.0, current_position.1 - 1); } SkipB => { best_alignment.push(( None, Some(self.b.as_bytes()[current_position.0 - 1] as char), )); current_position = (current_position.0 - 1, current_position.1); } }; } let ret = ScoredAlignment { score: self.score_at(final_position.0, final_position.1), alignment: best_alignment.into_iter().rev().collect(), }; ret } } #[wasm_bindgen] pub fn init_panic_hook() { console_error_panic_hook::set_once(); } #[bench] fn late_chars(b: &mut test::Bencher) { let copy = "The male begins courtship by flying noisily, and then in a graceful, circular glide with its wings outstretched and head down. After landing, the male will go to the female with a puffed out breast, bobbing head, and loud calls. Once the pair is mated, they will often spend time preening each other's feathers."; let mut t = AlignmentTable::new(copy); b.iter(|| { for _i in 0..1000 { t.replace_b("The male begins courtship by flying noisily, and then in a graceful, circular glide with its wings outstretched and head down. After landing, the male will go to the female with a puffed out breast, bobbing head, and loud calls. Once the pair is mated, they will often spend time preening each other's "); t.replace_b("The male begins courtship by flying noisily, and then in a graceful, circular glide with its wings outstretched and head down. After landing, the male will go to the female with a puffed out breast, bobbing head, and loud calls. Once the pair is mated, they will often spend time preening each other's f"); } }) //t.type_into_b(" enabled"); } #[cfg(test)] mod tests { use crate::AlignmentTable; #[test] fn it_works() { let target = "If enacted"; let mut t = AlignmentTable::new(&target); t.type_into_b("If enabled"); //t.type_into_b(" enabled"); //let replaced = t.replace_b("If enabled"); println!( "SCoredAlign {} scopre {:?}", t.best_scored_alignment().score, t.best_scored_alignment().alignment() ); assert_eq!(t.best_scored_alignment().score, 6); //println!("Repalced {}", replaced); } }
use crate::api::BabylonApi; use crate::core::*; use crate::materials::*; use crate::math::*; use js_ffi::*; pub struct Sphere { position: Vector3<f64>, js_ref: JSObject, } impl Sphere { pub fn new(scene: &Scene, size: f64) -> Sphere { Sphere { position: Vector3::new(0.0, 0.0, 0.0), js_ref: BabylonApi::create_sphere(scene.get_js_ref(), size), } } pub fn get_position(&self) -> &Vector { &self.position } pub fn set_position(&mut self, p: Vector) { self.position = p; BabylonApi::set_position( &mut self.js_ref, self.position.x, self.position.y, self.position.z, ); } pub fn set_position_x(&mut self, v: f64) { self.position.x = v; BabylonApi::set_position( &mut self.js_ref, self.position.x, self.position.y, self.position.z, ); } pub fn set_position_y(&mut self, v: f64) { self.position.y = v; BabylonApi::set_position( &mut self.js_ref, self.position.x, self.position.y, self.position.z, ); } pub fn set_position_z(&mut self, v: f64) { self.position.z = v; BabylonApi::set_position( &mut self.js_ref, self.position.x, self.position.y, self.position.z, ); } pub fn set_material<T>(&mut self, mat: &T) where T: Material, { BabylonApi::set_material(&mut self.js_ref, mat.get_js_ref()); } } impl Drop for Sphere { fn drop(&mut self) { BabylonApi::dispose_mesh(&mut self.js_ref); release_object(&self.js_ref) } } pub struct Cube { position: Vector3<f64>, js_ref: JSObject, } impl Cube { pub fn new(scene: &Scene, width: f64, height: f64, depth: f64) -> Cube { Cube { position: Vector3::new(0.0, 0.0, 0.0), js_ref: BabylonApi::create_cube(scene.get_js_ref(), width, height, depth), } } pub fn get_position(&self) -> &Vector { &self.position } pub fn set_position(&mut self, p: Vector) { self.position = p; BabylonApi::set_position(&mut self.js_ref, p.x, p.y, p.z); } pub fn set_position_x(&mut self, v: f64) { self.position.x = v; BabylonApi::set_position( &mut self.js_ref, self.position.x, self.position.y, self.position.z, ); } pub fn set_position_y(&mut self, v: f64) { self.position.y = v; BabylonApi::set_position( &mut self.js_ref, self.position.x, self.position.y, self.position.z, ); } pub fn set_position_z(&mut self, v: f64) { self.position.z = v; BabylonApi::set_position( &mut self.js_ref, self.position.x, self.position.y, self.position.z, ); } pub fn set_material<T>(&mut self, mat: &T) where T: Material, { BabylonApi::set_material(&mut self.js_ref, mat.get_js_ref()); } } impl Drop for Cube { fn drop(&mut self) { BabylonApi::dispose_mesh(&mut self.js_ref); release_object(&self.js_ref) } } pub struct GLTF { position: Vector3<f64>, js_ref: JSObject, } impl GLTF { pub fn new(scene: &Scene, file: &str) -> GLTF { GLTF { position: Vector3::new(0.0, 0.0, 0.0), js_ref: BabylonApi::create_gltf(scene.get_js_ref(), file), } } pub fn get_position(&self) -> &Vector { &self.position } pub fn set_position(&mut self, p: Vector) { self.position = p; BabylonApi::set_position(&mut self.js_ref, p.x, p.y, p.z); } pub fn set_position_x(&mut self, v: f64) { self.position.x = v; BabylonApi::set_position( &mut self.js_ref, self.position.x, self.position.y, self.position.z, ); } pub fn set_position_y(&mut self, v: f64) { self.position.y = v; BabylonApi::set_position( &mut self.js_ref, self.position.x, self.position.y, self.position.z, ); } pub fn set_position_z(&mut self, v: f64) { self.position.z = v; BabylonApi::set_position( &mut self.js_ref, self.position.x, self.position.y, self.position.z, ); } pub fn set_scaling(&mut self, p: Vector) { self.position = p; BabylonApi::set_scaling(&mut self.js_ref, p.x, p.y, p.z); } } impl Drop for GLTF { fn drop(&mut self) { BabylonApi::dispose_mesh(&mut self.js_ref); release_object(&self.js_ref) } }
use std::collections::HashMap; use ::serde::Serialize; use rusqlite::{params, Connection}; #[derive(Clone, Debug, Serialize)] pub struct Account { pub guid: String, pub parent: Option<Box<Account>>, pub name: String } impl Account { pub fn is_expense(&self) -> bool { match self.parent { None => false, Some(ref p) if p.name.to_lowercase() == "expenses" => true, Some(ref p) => p.is_expense() } } pub fn qualified_name(&self) -> String { match self.parent { None => self.name.to_string(), Some(ref p) => format!("{}:{}", p.qualified_name(), self.name) } } } pub struct AccountDao<'a> { pub conn: &'a Connection } impl<'a> AccountDao<'a> { pub fn list(&self) -> Vec<Account> { struct DbAccount { guid: String, parent_guid: Option<String>, name: String } let mut stmt = self.conn.prepare("SELECT * from accounts").unwrap(); let db_accounts = stmt.query_map(params![], |row| { Ok(DbAccount { guid: row.get("guid").unwrap(), parent_guid: row.get("parent_guid").unwrap(), name: row.get("name").unwrap() }) }).unwrap().map(|r| r.unwrap()).collect::<Vec<_>>(); fn to_acct(db_acct: &DbAccount, by_guid: &HashMap<String, &DbAccount>) -> Account { let parent_acct = match db_acct.parent_guid { Some(ref p) => Some(Box::new(to_acct(by_guid.get(p).unwrap(), by_guid))), _ => None }; Account { guid: db_acct.guid.clone(), parent: parent_acct, name: db_acct.name.clone() } }; let by_guid: HashMap<String, &DbAccount> = db_accounts.iter().map( |a| (a.guid.clone(), a) ).collect(); db_accounts.iter().map(|da| to_acct(da, &by_guid)).collect() } }
extern crate piston; extern crate graphics; extern crate glutin_window; extern crate opengl_graphics; extern crate rand; extern crate find_folder; use opengl_graphics::{GlGraphics, Texture}; use std::f64; use models::vector::Vector; use self::rand::Rng; use game::Direction; //where is player in relation to enemy shoot in that direction pub const ENEMY_SIZE: f64 = 40.0; const ENEMY_SPEED: f64 = 5.0; const ENEMY_PROB_MOVEMENT: u32= 30; /// struct contains mutable settings for enemies /// pos: position in window /// alive: whether the enemy should be removed or not /// texture: contains the image for enemy /// size: size of enemy /// dir: direction the enemy is moving towards pub struct Enemy { pub pos: Vector, pub alive: bool, texture: Result<Texture, String>, pub size: f64, pub dir: Direction, } impl Enemy { /// creates a new enemy pub fn new(x: f64, y: f64 ) -> Self { Enemy { pos: Vector::new(x, y), alive: true, texture: Texture::from_path(find_folder::Search::ParentsThenKids(3, 3) .for_folder("assets") .unwrap() .join("enemy.png")), size: ENEMY_SIZE, dir: Direction::EAST, } } ///draws the enemy on the screen pub fn draw(&mut self, c: self::graphics::Context, gl: &mut GlGraphics) { use self::graphics::*; let transform = c.transform .trans(self.pos.x, self.pos.y) .trans(-ENEMY_SIZE / 2.0, -ENEMY_SIZE / 2.0); match self.texture { Ok(ref t) => image(t, transform, gl), _ => {} } } /// randomly picks whether the enemy should move toward the player pub fn update(&mut self, playerx:f64,playery:f64) { let num: u32 = rand::thread_rng().gen_range(1, ENEMY_PROB_MOVEMENT); if num == 3 { self.move_toward_player(playerx,playery); } } fn set_direction(&mut self, dx: f64, dy:f64){ if dx*dx > dy*dy { if dx > 0.0 { self.dir = Direction::WEST; } else { self.dir = Direction::EAST; } } else { if dy > 0.0 { self.dir = Direction::NORTH; } else { self.dir = Direction::SOUTH; } } } /// handles the movement toward the player fn move_toward_player(&mut self, playerx:f64,playery:f64) { let mut dx = self.pos.x - playerx; let mut dy = self.pos.y - playery; let dist = (dx*dx + dy*dy).sqrt(); dx = dx/dist; dy = dy/dist; self.set_direction(dx,dy); // if dy > 0.0 {println!("going up");} self.pos.x -= dx * ENEMY_SPEED; self.pos.y -= dy * ENEMY_SPEED; } ///checks for enemy collision with wall pub fn collides(&self, wall: &[f64;4]) -> bool { let collision_x: bool = self.pos.x + ENEMY_SIZE >= wall[0] && wall[0]+(wall[2]-wall[0]) >= self.pos.x; let collision_y: bool = self.pos.y + ENEMY_SIZE >= wall[1] && wall[1] + (wall[3]-wall[1]) >= self.pos.y; return collision_x && collision_y } } #[cfg(test)] mod berzerk_test { use piston::window::WindowSettings; use glutin_window::GlutinWindow as Window; use opengl_graphics::OpenGL; use super::*; //TODO: Find a way to make a test enemy that I could use in all the functions #[test] fn test_new_enemy() { // set up that is needed to make the enemy // required because I am using texture which depends on this set up let opengl = OpenGL::V3_2; //OpenGL function pointers must be loaded before creating the `Gl` backend //That is why this window is created let _window: Window = WindowSettings::new("create test", [500, 500]) .exit_on_esc(true) .build() .expect("Error creating window"); let _gl = GlGraphics::new(opengl); let _t_enemy = Enemy::new(0.0,100.0); } #[test] // I am testing this private function instead of the public update function // because this is where the logic is and update has a random chance of running this logic fn test_move_toward_player() { let opengl = OpenGL::V3_2; let _window: Window = WindowSettings::new("create test", [500, 500]) .exit_on_esc(true) .build() .expect("Error creating window"); let _gl = GlGraphics::new(opengl); let t_pos_before = 50.0; let mut t_enemy = Enemy::new(t_pos_before,t_pos_before); t_enemy.move_toward_player(10.0,10.0); assert!(t_enemy.pos.x < t_pos_before); assert!(t_enemy.pos.y < t_pos_before); } }
use crate::listnode::{ListNode, list_to_vec, arr_to_list}; pub fn reverse_between(head: Option<Box<ListNode>>, m: i32, n: i32) -> Option<Box<ListNode>> { let m = m as usize; let n = n as usize; if m == n { return head } let mut dummy = Box::new(ListNode { val: 0, next: head }); let mut p = &mut dummy; for counter in 0..m-1 { p = p.next.as_mut().unwrap(); } let tail_of_unchanged = p; let mut p0 = tail_of_unchanged.next.take().unwrap(); let mut p1 = p0.next.take().unwrap(); for _ in 0..n-m-1 { let mut p2 = p1.next.take().unwrap(); p1.next = Some(p0); p0 = p1; p1 = p2; } let head_of_second_unchanged = p1.next.take(); p1.next = Some(p0); p0 = p1; tail_of_unchanged.next = Some(p0); let mut tail_of_reversed = tail_of_unchanged; for _ in 0..=n-m { tail_of_reversed = tail_of_reversed.next.as_mut().unwrap(); } tail_of_reversed.next = head_of_second_unchanged; dummy.next } #[test] fn test_reverse_between() { assert_eq!(list_to_vec(reverse_between(arr_to_list(&[1, 2, 3, 4, 5]), 2, 4)), vec![1, 4, 3, 2, 5]); assert_eq!(list_to_vec(reverse_between(arr_to_list(&[1, 2]), 1, 2)), vec![2, 1]); }
use bigint::{Address, H256, U256}; use rlp::{Encodable, RlpStream}; #[derive(Debug)] pub struct Log { pub address: Address, pub data: U256, pub topics: Vec<H256>, } impl Encodable for Log { fn rlp_append(&self, s: &mut RlpStream) { s.begin_list(3); s.append(&self.address); s.append_list(&self.topics); s.append(&self.data); } }
#[cfg(test)] pub mod problem1; pub mod problem2; pub mod problem3; pub mod problem4; pub mod tests_provided; pub mod tests_student;
use rstest::rstest; use std::net::SocketAddr; pub mod utils; use utils::app; mod subscribe { use crate::utils::App; use super::*; use surf::Response; async fn do_request(address: &SocketAddr, body: &str) -> Response { surf::post(format!("http://{}/subscriptions", address)) .header("Content-Type", "application/x-www-form-urlencoded") .body(body) .send() .await .expect("Failed to execute request.") } #[derive(Clone, Debug, Eq, PartialEq)] struct User { pub name: String, pub email: String, } impl From<mongodb::bson::Document> for User { fn from(d: mongodb::bson::Document) -> Self { User { name: d.get_str("name").unwrap().to_owned(), email: d.get_str("email").unwrap().to_owned(), } } } #[rstest] async fn should_accept_a_valid_form_data(app: App) { let response = do_request( &app.address, "name=De%20Domenico&email=antonio_de_domenico%40gmail.com", ) .await; assert_eq!(200, response.status()); let user = app .db .collection("subscriptions") .find_one(None, None) .await .expect("Cannot fetch user"); assert_eq!( Some(User { name: "De Domenico".to_owned(), email: "antonio_de_domenico@gmail.com".to_owned() }), user.map(|d| d.into()) ); } #[rstest( body, case::missed_email("name=De%20Domenico"), case::missed_name("email=antonio_de_domenico%40gmail.com"), case::missed_both("") )] async fn should_returns_a_400_when_data_is_missing(app: App, body: &str) { let response = do_request(&app.address, body).await; assert_eq!(400, u16::from(response.status())); } }
use std::time::{Duration, Instant}; use crossbeam_channel::{self, Receiver, Sender}; use failure::Fallible; #[derive(Debug, Clone, PartialEq, Eq)] pub enum Command { Shutdown, VolumeUp, VolumeDown, } #[derive(Debug, Clone)] pub struct Config { pub shutdown_pin: Option<u32>, pub volume_up_pin: Option<u32>, pub volume_down_pin: Option<u32>, pub start_time: Option<Instant>, } pub struct Handle<T> { channel: Receiver<T>, } impl<T> Handle<T> { pub fn channel(&self) -> Receiver<T> { self.channel.clone() } } pub mod cdev_gpio { use std::collections::HashMap; use std::convert::From; use std::sync::{Arc, RwLock}; use gpio_cdev::{Chip, EventRequestFlags, Line, LineRequestFlags}; use serde::Deserialize; use slog_scope::{error, info, warn}; use super::*; #[derive(Debug, Clone)] pub struct CdevGpio<T: Clone> { map: HashMap<u32, Command>, chip: Arc<RwLock<Chip>>, config: Config, tx: Sender<T>, } #[derive(Deserialize, Debug, Clone)] pub struct EnvConfig { shutdown_pin: Option<u32>, volume_up_pin: Option<u32>, volume_down_pin: Option<u32>, } impl From<EnvConfig> for Config { fn from(env_config: EnvConfig) -> Self { let start_time = Some(Instant::now()); Config { shutdown_pin: env_config.shutdown_pin, volume_up_pin: env_config.volume_up_pin, volume_down_pin: env_config.volume_down_pin, start_time, } } } impl EnvConfig { pub fn new_from_env() -> Fallible<Self> { Ok(envy::from_env::<EnvConfig>()?) } } impl<T: Clone + Send + 'static> CdevGpio<T> { pub fn new_from_env<F>(msg_transformer: F) -> Fallible<Handle<T>> where F: Fn(Command) -> Option<T> + 'static + Send + Sync, { info!("Using CdevGpio based in Button Controller"); let env_config = EnvConfig::new_from_env()?; let config: Config = env_config.into(); let mut map = HashMap::new(); if let Some(shutdown_pin) = config.shutdown_pin { map.insert(shutdown_pin, Command::Shutdown); } if let Some(pin) = config.volume_up_pin { map.insert(pin, Command::VolumeUp); } if let Some(pin) = config.volume_down_pin { map.insert(pin, Command::VolumeDown); } let chip = Chip::new("/dev/gpiochip0") .map_err(|err| Error::IO(format!("Failed to open Chip: {:?}", err)))?; let (tx, rx) = crossbeam_channel::bounded(1); let mut gpio_cdev = Self { map, chip: Arc::new(RwLock::new(chip)), config, tx, }; gpio_cdev.run(msg_transformer)?; Ok(Handle { channel: rx }) } fn run_single_event_listener<F>( self, (line, line_id, cmd): (Line, u32, Command), msg_transformer: Arc<F>, ) -> Fallible<()> where F: Fn(Command) -> Option<T> + 'static + Send, { let mut n_received_during_shutdown_delay = 0; info!("Listening for GPIO events on line {}", line_id); for event in line .events( LineRequestFlags::INPUT, EventRequestFlags::FALLING_EDGE, "read-input", ) .map_err(|err| { Error::IO(format!( "Failed to request events from GPIO line {}: {}", line_id, err )) })? { info!("Received GPIO event {:?} on line {}", event, line_id); if cmd == Command::Shutdown { if let Some(start_time) = self.config.start_time { let now = Instant::now(); let dt: Duration = now - start_time; if dt < DELAY_BEFORE_ACCEPTING_SHUTDOWN_COMMANDS { warn!( "Ignoring shutdown event (time elapsed since start: {:?})", dt ); n_received_during_shutdown_delay += 1; continue; } } if n_received_during_shutdown_delay > 10 { warn!("Received too many shutdown events right after startup, shutdown functionality has been disabled"); continue; } } if let Some(cmd) = msg_transformer(cmd.clone()) { if let Err(err) = self.tx.send(cmd) { error!("Failed to transmit GPIO event: {}", err); } } else { info!("Dropped button command message: {:?}", cmd); } } Ok(()) } fn run<F>(&mut self, msg_transformer: F) -> Fallible<()> where F: Fn(Command) -> Option<T> + 'static + Send + Sync, { let chip = &mut *(self.chip.write().unwrap()); let msg_transformer = Arc::new(msg_transformer); // Spawn threads for requested GPIO lines. for (line_id, cmd) in self.map.iter() { info!("Listening for {:?} on GPIO line {}", cmd, line_id); let line_id = *line_id as u32; let line = chip .get_line(line_id) .map_err(|err| Error::IO(format!("Failed to get GPIO line: {:?}", err)))?; let cmd = (*cmd).clone(); let clone = self.clone(); let msg_transformer = Arc::clone(&msg_transformer); let _handle = std::thread::Builder::new() .name(format!("button-controller-{}", line_id)) .spawn(move || { let res = clone.run_single_event_listener((line, line_id, cmd), msg_transformer); error!("GPIO Listener loop terminated unexpectedly: {:?}", res); }) .unwrap(); } Ok(()) } } } #[derive(Debug)] pub enum Error { IO(String), } impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Error::IO(s) => write!(f, "IO Error: {}", s), } } } impl std::error::Error for Error {} const DELAY_BEFORE_ACCEPTING_SHUTDOWN_COMMANDS: Duration = Duration::from_secs(10);
use core::ffi::c_void; // @Todo These may not be correct on all architectures pub type PVOID = *mut c_void; pub type LPVOID = *mut c_void; pub type LPCVOID = *const c_void; pub type HANDLE = PVOID; pub type HMODULE = HANDLE; pub type HICON = HANDLE; pub type HCURSOR = HANDLE; pub type HBRUSH = HANDLE; pub type HINSTANCE = HANDLE; pub type HWND = HANDLE; pub type HMENU = HANDLE; pub type LPCSTR = *const u8; pub type LPCWSTR = *const u16; pub type FARPROC = *const c_void; pub type BOOL = i32; pub type DWORD = u32; pub type SIZE_T = usize; pub type ULONG_PTR = usize; pub type UINT = u32; pub type LPARAM = isize; pub type WPARAM = usize; pub type LRESULT = isize; pub type WORD = u16; pub type ATOM = WORD; pub type LONG = i32; pub type LPMSG = *mut MSG; pub type LONG_PTR = isize; pub type LARGE_INTEGER = i64; pub type SRWLOCK = usize; pub type PSRWLOCK = *mut SRWLOCK; pub type WNDPROC = unsafe extern "system" fn(hwnd: HWND, uMsg: UINT, wParam: WPARAM, lParam: LPARAM) -> LRESULT; pub type ThreadProc = unsafe extern "system" fn(lpParameter: LPVOID) -> DWORD; pub const INVALID_HANDLE_VALUE: HANDLE = !0u64 as _; pub const SRWLOCK_INIT: SRWLOCK = 0; pub const CS_BYTEALIGNCLIENT: UINT = 0x1000; pub const CS_BYTEALIGNWINDOW: UINT = 0x2000; pub const CS_CLASSDC: UINT = 0x0040; pub const CS_DBLCLKS: UINT = 0x0008; pub const CS_DROPSHADOW: UINT = 0x00020000; pub const CS_GLOBALCLASS: UINT = 0x4000; pub const CS_HREDRAW: UINT = 0x0002; pub const CS_NOCLOSE: UINT = 0x0200; pub const CS_OWNDC: UINT = 0x0020; pub const CS_PARENTDC: UINT = 0x0080; pub const CS_SAVEBITS: UINT = 0x0800; pub const CS_VREDRAW: UINT = 0x0001; pub const WS_EX_ACCEPTFILES: DWORD = 0x00000010; pub const WS_EX_APPWINDOW: DWORD = 0x00040000; pub const WS_EX_CLIENTEDGE: DWORD = 0x00000200; pub const WS_EX_COMPOSITED: DWORD = 0x02000000; pub const WS_EX_CONTEXTHELP: DWORD = 0x00000400; pub const WS_EX_CONTROLPARENT: DWORD = 0x00010000; pub const WS_EX_DLGMODALFRAME: DWORD = 0x00000001; pub const WS_EX_LAYERED: DWORD = 0x00080000; pub const WS_EX_LAYOUTRTL: DWORD = 0x00400000; pub const WS_EX_LEFT: DWORD = 0x00000000; pub const WS_EX_LEFTSCROLLBAR: DWORD = 0x00004000; pub const WS_EX_LTRREADING: DWORD = 0x00000000; pub const WS_EX_MDICHILD: DWORD = 0x00000040; pub const WS_EX_NOACTIVATE: DWORD = 0x08000000; pub const WS_EX_NOINHERITLAYOUT: DWORD = 0x00100000; pub const WS_EX_NOPARENTNOTIFY: DWORD = 0x00000004; pub const WS_EX_NOREDIRECTIONBITMAP: DWORD = 0x00200000; pub const WS_EX_OVERLAPPEDWINDOW: DWORD = (WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE); pub const WS_EX_PALETTEWINDOW: DWORD = (WS_EX_WINDOWEDGE | WS_EX_TOOLWINDOW | WS_EX_TOPMOST); pub const WS_EX_RIGHT: DWORD = 0x00001000; pub const WS_EX_RIGHTSCROLLBAR: DWORD = 0x00000000; pub const WS_EX_RTLREADING: DWORD = 0x00002000; pub const WS_EX_STATICEDGE: DWORD = 0x00020000; pub const WS_EX_TOOLWINDOW: DWORD = 0x00000080; pub const WS_EX_TOPMOST: DWORD = 0x00000008; pub const WS_EX_TRANSPARENT: DWORD = 0x00000020; pub const WS_EX_WINDOWEDGE: DWORD = 0x00000100; pub const WS_OVERLAPPED: DWORD = 0x00000000; pub const WS_POPUP: DWORD = 0x80000000; pub const WS_CHILD: DWORD = 0x40000000; pub const WS_MINIMIZE: DWORD = 0x20000000; pub const WS_VISIBLE: DWORD = 0x10000000; pub const WS_DISABLED: DWORD = 0x08000000; pub const WS_CLIPSIBLINGS: DWORD = 0x04000000; pub const WS_CLIPCHILDREN: DWORD = 0x02000000; pub const WS_MAXIMIZE: DWORD = 0x01000000; pub const WS_CAPTION: DWORD = 0x00C00000; pub const WS_BORDER: DWORD = 0x00800000; pub const WS_DLGFRAME: DWORD = 0x00400000; pub const WS_VSCROLL: DWORD = 0x00200000; pub const WS_HSCROLL: DWORD = 0x00100000; pub const WS_SYSMENU: DWORD = 0x00080000; pub const WS_THICKFRAME: DWORD = 0x00040000; pub const WS_GROUP: DWORD = 0x00020000; pub const WS_TABSTOP: DWORD = 0x00010000; pub const WS_MINIMIZEBOX: DWORD = 0x00020000; pub const WS_MAXIMIZEBOX: DWORD = 0x00010000; pub const WS_TILED: DWORD = WS_OVERLAPPED; pub const WS_ICONIC: DWORD = WS_MINIMIZE; pub const WS_SIZEBOX: DWORD = WS_THICKFRAME; pub const WS_TILEDWINDOW: DWORD = WS_OVERLAPPEDWINDOW; pub const WS_OVERLAPPEDWINDOW: DWORD = (WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX); pub const WS_POPUPWINDOW: DWORD = (WS_POPUP | WS_BORDER | WS_SYSMENU); pub const WS_CHILDWINDOW: DWORD = (WS_CHILD); pub const CW_USEDEFAULT: i32 = -2147483648; pub const SW_HIDE: i32 = 0; pub const SW_SHOWNORMAL: i32 = 1; pub const SW_NORMAL: i32 = 1; pub const SW_SHOWMINIMIZED: i32 = 2; pub const SW_SHOWMAXIMIZED: i32 = 3; pub const SW_MAXIMIZE: i32 = 3; pub const SW_SHOWNOACTIVATE: i32 = 4; pub const SW_SHOW: i32 = 5; pub const SW_MINIMIZE: i32 = 6; pub const SW_SHOWMINNOACTIVE: i32 = 7; pub const SW_SHOWNA: i32 = 8; pub const SW_RESTORE: i32 = 9; pub const SW_SHOWDEFAULT: i32 = 10; pub const SW_FORCEMINIMIZE: i32 = 11; pub const PM_NOREMOVE: UINT = 0x0000; pub const PM_REMOVE: UINT = 0x0001; pub const PM_NOYIELD: UINT = 0x0002; pub const WM_NULL: UINT = 0x0000; pub const WM_CREATE: UINT = 0x0001; pub const WM_DESTROY: UINT = 0x0002; pub const WM_MOVE: UINT = 0x0003; pub const WM_SIZE: UINT = 0x0005; pub const WM_ACTIVATE: UINT = 0x0006; pub const WM_SETFOCUS: UINT = 0x0007; pub const WM_KILLFOCUS: UINT = 0x0008; pub const WM_ENABLE: UINT = 0x000A; pub const WM_SETREDRAW: UINT = 0x000B; pub const WM_SETTEXT: UINT = 0x000C; pub const WM_GETTEXT: UINT = 0x000D; pub const WM_GETTEXTLENGTH: UINT = 0x000E; pub const WM_PAINT: UINT = 0x000F; pub const WM_CLOSE: UINT = 0x0010; pub const WM_QUERYENDSESSION: UINT = 0x0011; pub const WM_QUERYOPEN: UINT = 0x0013; pub const WM_ENDSESSION: UINT = 0x0016; pub const WM_QUIT: UINT = 0x0012; pub const WM_ERASEBKGND: UINT = 0x0014; pub const WM_SYSCOLORCHANGE: UINT = 0x0015; pub const WM_SHOWWINDOW: UINT = 0x0018; pub const WM_WININICHANGE: UINT = 0x001A; pub const WM_SETTINGCHANGE: UINT = WM_WININICHANGE; pub const WM_DEVMODECHANGE: UINT = 0x001B; pub const WM_ACTIVATEAPP: UINT = 0x001C; pub const WM_FONTCHANGE: UINT = 0x001D; pub const WM_TIMECHANGE: UINT = 0x001E; pub const WM_CANCELMODE: UINT = 0x001F; pub const WM_SETCURSOR: UINT = 0x0020; pub const WM_MOUSEACTIVATE: UINT = 0x0021; pub const WM_CHILDACTIVATE: UINT = 0x0022; pub const WM_QUEUESYNC: UINT = 0x0023; pub const WM_GETMINMAXINFO: UINT = 0x0024; pub const WM_PAINTICON: UINT = 0x0026; pub const WM_ICONERASEBKGND: UINT = 0x0027; pub const WM_NEXTDLGCTL: UINT = 0x0028; pub const WM_SPOOLERSTATUS: UINT = 0x002A; pub const WM_DRAWITEM: UINT = 0x002B; pub const WM_MEASUREITEM: UINT = 0x002C; pub const WM_DELETEITEM: UINT = 0x002D; pub const WM_VKEYTOITEM: UINT = 0x002E; pub const WM_CHARTOITEM: UINT = 0x002F; pub const WM_SETFONT: UINT = 0x0030; pub const WM_GETFONT: UINT = 0x0031; pub const WM_SETHOTKEY: UINT = 0x0032; pub const WM_GETHOTKEY: UINT = 0x0033; pub const WM_QUERYDRAGICON: UINT = 0x0037; pub const WM_COMPAREITEM: UINT = 0x0039; pub const WM_GETOBJECT: UINT = 0x003D; pub const WM_COMPACTING: UINT = 0x0041; pub const WM_COMMNOTIFY: UINT = 0x0044; pub const WM_WINDOWPOSCHANGING: UINT = 0x0046; pub const WM_WINDOWPOSCHANGED: UINT = 0x0047; pub const WM_POWER: UINT = 0x0048; pub const WM_COPYDATA: UINT = 0x004A; pub const WM_CANCELJOURNAL: UINT = 0x004B; pub const WM_NOTIFY: UINT = 0x004E; pub const WM_INPUTLANGCHANGEREQUEST: UINT = 0x0050; pub const WM_INPUTLANGCHANGE: UINT = 0x0051; pub const WM_TCARD: UINT = 0x0052; pub const WM_HELP: UINT = 0x0053; pub const WM_USERCHANGED: UINT = 0x0054; pub const WM_NOTIFYFORMAT: UINT = 0x0055; pub const WM_CONTEXTMENU: UINT = 0x007B; pub const WM_STYLECHANGING: UINT = 0x007C; pub const WM_STYLECHANGED: UINT = 0x007D; pub const WM_DISPLAYCHANGE: UINT = 0x007E; pub const WM_GETICON: UINT = 0x007F; pub const WM_SETICON: UINT = 0x0080; pub const WM_NCCREATE: UINT = 0x0081; pub const WM_NCDESTROY: UINT = 0x0082; pub const WM_NCCALCSIZE: UINT = 0x0083; pub const WM_NCHITTEST: UINT = 0x0084; pub const WM_NCPAINT: UINT = 0x0085; pub const WM_NCACTIVATE: UINT = 0x0086; pub const WM_GETDLGCODE: UINT = 0x0087; pub const WM_SYNCPAINT: UINT = 0x0088; pub const WM_NCMOUSEMOVE: UINT = 0x00A0; pub const WM_NCLBUTTONDOWN: UINT = 0x00A1; pub const WM_NCLBUTTONUP: UINT = 0x00A2; pub const WM_NCLBUTTONDBLCLK: UINT = 0x00A3; pub const WM_NCRBUTTONDOWN: UINT = 0x00A4; pub const WM_NCRBUTTONUP: UINT = 0x00A5; pub const WM_NCRBUTTONDBLCLK: UINT = 0x00A6; pub const WM_NCMBUTTONDOWN: UINT = 0x00A7; pub const WM_NCMBUTTONUP: UINT = 0x00A8; pub const WM_NCMBUTTONDBLCLK: UINT = 0x00A9; pub const WM_NCXBUTTONDOWN: UINT = 0x00AB; pub const WM_NCXBUTTONUP: UINT = 0x00AC; pub const WM_NCXBUTTONDBLCLK: UINT = 0x00AD; pub const WM_INPUT_DEVICE_CHANGE: UINT = 0x00FE; pub const WM_INPUT: UINT = 0x00FF; pub const WM_KEYFIRST: UINT = 0x0100; pub const WM_KEYDOWN: UINT = 0x0100; pub const WM_KEYUP: UINT = 0x0101; pub const WM_CHAR: UINT = 0x0102; pub const WM_DEADCHAR: UINT = 0x0103; pub const WM_SYSKEYDOWN: UINT = 0x0104; pub const WM_SYSKEYUP: UINT = 0x0105; pub const WM_SYSCHAR: UINT = 0x0106; pub const WM_SYSDEADCHAR: UINT = 0x0107; pub const WM_UNICHAR: UINT = 0x0109; pub const WM_KEYLAST: UINT = 0x0109; pub const WM_IME_STARTCOMPOSITION: UINT = 0x010D; pub const WM_IME_ENDCOMPOSITION: UINT = 0x010E; pub const WM_IME_COMPOSITION: UINT = 0x010F; pub const WM_IME_KEYLAST: UINT = 0x010F; pub const WM_INITDIALOG: UINT = 0x0110; pub const WM_COMMAND: UINT = 0x0111; pub const WM_SYSCOMMAND: UINT = 0x0112; pub const WM_TIMER: UINT = 0x0113; pub const WM_HSCROLL: UINT = 0x0114; pub const WM_VSCROLL: UINT = 0x0115; pub const WM_INITMENU: UINT = 0x0116; pub const WM_INITMENUPOPUP: UINT = 0x0117; pub const WM_GESTURE: UINT = 0x0119; pub const WM_GESTURENOTIFY: UINT = 0x011A; pub const WM_MENUSELECT: UINT = 0x011F; pub const WM_MENUCHAR: UINT = 0x0120; pub const WM_ENTERIDLE: UINT = 0x0121; pub const WM_MENURBUTTONUP: UINT = 0x0122; pub const WM_MENUDRAG: UINT = 0x0123; pub const WM_MENUGETOBJECT: UINT = 0x0124; pub const WM_UNINITMENUPOPUP: UINT = 0x0125; pub const WM_MENUCOMMAND: UINT = 0x0126; pub const WM_CHANGEUISTATE: UINT = 0x0127; pub const WM_UPDATEUISTATE: UINT = 0x0128; pub const WM_QUERYUISTATE: UINT = 0x0129; pub const WM_CTLCOLORMSGBOX: UINT = 0x0132; pub const WM_CTLCOLOREDIT: UINT = 0x0133; pub const WM_CTLCOLORLISTBOX: UINT = 0x0134; pub const WM_CTLCOLORBTN: UINT = 0x0135; pub const WM_CTLCOLORDLG: UINT = 0x0136; pub const WM_CTLCOLORSCROLLBAR: UINT = 0x0137; pub const WM_CTLCOLORSTATIC: UINT = 0x0138; pub const WM_MOUSEFIRST: UINT = 0x0200; pub const WM_MOUSEMOVE: UINT = 0x0200; pub const WM_LBUTTONDOWN: UINT = 0x0201; pub const WM_LBUTTONUP: UINT = 0x0202; pub const WM_LBUTTONDBLCLK: UINT = 0x0203; pub const WM_RBUTTONDOWN: UINT = 0x0204; pub const WM_RBUTTONUP: UINT = 0x0205; pub const WM_RBUTTONDBLCLK: UINT = 0x0206; pub const WM_MBUTTONDOWN: UINT = 0x0207; pub const WM_MBUTTONUP: UINT = 0x0208; pub const WM_MBUTTONDBLCLK: UINT = 0x0209; pub const WM_MOUSEWHEEL: UINT = 0x020A; pub const WM_XBUTTONDOWN: UINT = 0x020B; pub const WM_XBUTTONUP: UINT = 0x020C; pub const WM_XBUTTONDBLCLK: UINT = 0x020D; pub const WM_MOUSEHWHEEL: UINT = 0x020E; pub const WM_MOUSELAST: UINT = 0x020E; pub const WM_PARENTNOTIFY: UINT = 0x0210; pub const WM_ENTERMENULOOP: UINT = 0x0211; pub const WM_EXITMENULOOP: UINT = 0x0212; pub const WM_NEXTMENU: UINT = 0x0213; pub const WM_SIZING: UINT = 0x0214; pub const WM_CAPTURECHANGED: UINT = 0x0215; pub const WM_MOVING: UINT = 0x0216; pub const WM_POWERBROADCAST: UINT = 0x0218; pub const WM_DEVICECHANGE: UINT = 0x0219; pub const WM_MDICREATE: UINT = 0x0220; pub const WM_MDIDESTROY: UINT = 0x0221; pub const WM_MDIACTIVATE: UINT = 0x0222; pub const WM_MDIRESTORE: UINT = 0x0223; pub const WM_MDINEXT: UINT = 0x0224; pub const WM_MDIMAXIMIZE: UINT = 0x0225; pub const WM_MDITILE: UINT = 0x0226; pub const WM_MDICASCADE: UINT = 0x0227; pub const WM_MDIICONARRANGE: UINT = 0x0228; pub const WM_MDIGETACTIVE: UINT = 0x0229; pub const WM_MDISETMENU: UINT = 0x0230; pub const WM_ENTERSIZEMOVE: UINT = 0x0231; pub const WM_EXITSIZEMOVE: UINT = 0x0232; pub const WM_DROPFILES: UINT = 0x0233; pub const WM_MDIREFRESHMENU: UINT = 0x0234; pub const WM_POINTERDEVICECHANGE: UINT = 0x238; pub const WM_POINTERDEVICEINRANGE: UINT = 0x239; pub const WM_POINTERDEVICEOUTOFRANGE: UINT = 0x23A; pub const WM_TOUCH: UINT = 0x0240; pub const WM_NCPOINTERUPDATE: UINT = 0x0241; pub const WM_NCPOINTERDOWN: UINT = 0x0242; pub const WM_NCPOINTERUP: UINT = 0x0243; pub const WM_POINTERUPDATE: UINT = 0x0245; pub const WM_POINTERDOWN: UINT = 0x0246; pub const WM_POINTERUP: UINT = 0x0247; pub const WM_POINTERENTER: UINT = 0x0249; pub const WM_POINTERLEAVE: UINT = 0x024A; pub const WM_POINTERACTIVATE: UINT = 0x024B; pub const WM_POINTERCAPTURECHANGED: UINT = 0x024C; pub const WM_TOUCHHITTESTING: UINT = 0x024D; pub const WM_POINTERWHEEL: UINT = 0x024E; pub const WM_POINTERHWHEEL: UINT = 0x024F; pub const WM_IME_SETCONTEXT: UINT = 0x0281; pub const WM_IME_NOTIFY: UINT = 0x0282; pub const WM_IME_CONTROL: UINT = 0x0283; pub const WM_IME_COMPOSITIONFULL: UINT = 0x0284; pub const WM_IME_SELECT: UINT = 0x0285; pub const WM_IME_CHAR: UINT = 0x0286; pub const WM_IME_REQUEST: UINT = 0x0288; pub const WM_IME_KEYDOWN: UINT = 0x0290; pub const WM_IME_KEYUP: UINT = 0x0291; pub const WM_MOUSEHOVER: UINT = 0x02A1; pub const WM_MOUSELEAVE: UINT = 0x02A3; pub const WM_NCMOUSEHOVER: UINT = 0x02A0; pub const WM_NCMOUSELEAVE: UINT = 0x02A2; pub const WM_WTSSESSION_CHANGE: UINT = 0x02B1; pub const WM_TABLET_FIRST: UINT = 0x02c0; pub const WM_TABLET_LAST: UINT = 0x02df; pub const WM_DPICHANGED: UINT = 0x02E0; pub const WM_CUT: UINT = 0x0300; pub const WM_COPY: UINT = 0x0301; pub const WM_PASTE: UINT = 0x0302; pub const WM_CLEAR: UINT = 0x0303; pub const WM_UNDO: UINT = 0x0304; pub const WM_RENDERFORMAT: UINT = 0x0305; pub const WM_RENDERALLFORMATS: UINT = 0x0306; pub const WM_DESTROYCLIPBOARD: UINT = 0x0307; pub const WM_DRAWCLIPBOARD: UINT = 0x0308; pub const WM_PAINTCLIPBOARD: UINT = 0x0309; pub const WM_VSCROLLCLIPBOARD: UINT = 0x030A; pub const WM_SIZECLIPBOARD: UINT = 0x030B; pub const WM_ASKCBFORMATNAME: UINT = 0x030C; pub const WM_CHANGECBCHAIN: UINT = 0x030D; pub const WM_HSCROLLCLIPBOARD: UINT = 0x030E; pub const WM_QUERYNEWPALETTE: UINT = 0x030F; pub const WM_PALETTEISCHANGING: UINT = 0x0310; pub const WM_PALETTECHANGED: UINT = 0x0311; pub const WM_HOTKEY: UINT = 0x0312; pub const WM_PRINT: UINT = 0x0317; pub const WM_PRINTCLIENT: UINT = 0x0318; pub const WM_APPCOMMAND: UINT = 0x0319; pub const WM_THEMECHANGED: UINT = 0x031A; pub const WM_CLIPBOARDUPDATE: UINT = 0x031D; pub const WM_DWMCOMPOSITIONCHANGED: UINT = 0x031E; pub const WM_DWMNCRENDERINGCHANGED: UINT = 0x031F; pub const WM_DWMCOLORIZATIONCOLORCHANGED: UINT = 0x0320; pub const WM_DWMWINDOWMAXIMIZEDCHANGE: UINT = 0x0321; pub const WM_DWMSENDICONICTHUMBNAIL: UINT = 0x0323; pub const WM_DWMSENDICONICLIVEPREVIEWBITMAP: UINT = 0x0326; pub const WM_GETTITLEBARINFOEX: UINT = 0x033F; pub const WM_HANDHELDFIRST: UINT = 0x0358; pub const WM_HANDHELDLAST: UINT = 0x035F; pub const WM_AFXFIRST: UINT = 0x0360; pub const WM_AFXLAST: UINT = 0x037F; pub const WM_PENWINFIRST: UINT = 0x0380; pub const WM_PENWINLAST: UINT = 0x038F; pub const WM_APP: UINT = 0x8000; pub const WM_USER: UINT = 0x0400; pub const GWL_EXSTYLE: i32 = -20; pub const GWLP_HINSTANCE: i32 = -6; pub const GWLP_HWNDPARENT: i32 = -8; pub const GWLP_ID: i32 = -12; pub const GWL_STYLE: i32 = -16; pub const GWLP_USERDATA: i32 = -21; pub const GWLP_WNDPROC: i32 = -4; pub const INFINITE: DWORD = 0xffffffff; pub const FILE_SHARE_DELETE: DWORD = 0x00000004; pub const FILE_SHARE_READ: DWORD = 0x00000001; pub const FILE_SHARE_WRITE: DWORD = 0x00000002; pub const GENERIC_ALL: DWORD = 1 << 28; pub const GENERIC_EXECUTE: DWORD = 1 << 29; pub const GENERIC_WRITE: DWORD = 1 << 30; pub const GENERIC_READ: DWORD = 1 << 31; pub const CREATE_ALWAYS: DWORD = 2; pub const CREATE_NEW: DWORD = 1; pub const OPEN_ALWAYS: DWORD = 4; pub const OPEN_EXISTING: DWORD = 3; pub const TRUNCATE_EXISTING: DWORD = 5; pub const ERROR_ALREADY_EXISTS: DWORD = 183; pub const ERROR_FILE_EXISTS: DWORD = 80; pub const ERROR_FILE_NOT_FOUND: DWORD = 2; pub const FILE_ATTRIBUTE_ARCHIVE: DWORD = 32; pub const FILE_ATTRIBUTE_ENCRYPTED: DWORD = 16384; pub const FILE_ATTRIBUTE_HIDDEN: DWORD = 2; pub const FILE_ATTRIBUTE_NORMAL: DWORD = 128; pub const FILE_ATTRIBUTE_OFFLINE: DWORD = 4096; pub const FILE_ATTRIBUTE_READONLY: DWORD = 1; pub const FILE_ATTRIBUTE_SYSTEM: DWORD = 4; pub const FILE_ATTRIBUTE_TEMPORARY: DWORD = 256; pub const FILE_FLAG_BACKUP_SEMANTICS: DWORD = 0x02000000; pub const FILE_FLAG_DELETE_ON_CLOSE: DWORD = 0x04000000; pub const FILE_FLAG_NO_BUFFERING: DWORD = 0x20000000; pub const FILE_FLAG_OPEN_NO_RECALL: DWORD = 0x00100000; pub const FILE_FLAG_OPEN_REPARSE_POINT: DWORD = 0x00200000; pub const FILE_FLAG_OVERLAPPED: DWORD = 0x40000000; pub const FILE_FLAG_POSIX_SEMANTICS: DWORD = 0x0100000; pub const FILE_FLAG_RANDOM_ACCESS: DWORD = 0x10000000; pub const FILE_FLAG_SESSION_AWARE: DWORD = 0x00800000; pub const FILE_FLAG_SEQUENTIAL_SCAN: DWORD = 0x08000000; pub const FILE_FLAG_WRITE_THROUGH: DWORD = 0x80000000; pub const FILE_BEGIN: DWORD = 0; pub const FILE_CURRENT: DWORD = 1; pub const FILE_END: DWORD = 2; pub const CREATE_SUSPENDED: DWORD = 0x00000004; pub const STACK_SIZE_PARAM_IS_A_RESERVATION: DWORD = 0x00010000; pub const STD_INPUT_HANDLE: DWORD = 0xffffffff - 9; pub const STD_OUTPUT_HANDLE: DWORD = 0xffffffff - 10; pub const STD_ERROR_HANDLE: DWORD = 0xffffffff - 11; #[repr(C)] pub struct WNDCLASSA { pub style: UINT, pub lpfnWndProc: WNDPROC, pub cbClsExtra: i32, pub cbWndExtra: i32, pub hInstance: HINSTANCE, pub hIcon: HICON, pub hCursor: HCURSOR, pub hbrBackground: HBRUSH, pub lpszMenuName: LPCSTR, pub lpszClassName: LPCSTR, } #[repr(C)] pub struct POINT { x: LONG, y: LONG, } #[repr(C)] pub struct MSG { hwnd: HWND, message: UINT, wParam: WPARAM, lParam: LPARAM, time: DWORD, pt: POINT, lPrivate: DWORD, } #[repr(C)] pub struct SECURITY_ATTRIBUTES { nLength: DWORD, lpSecurityDescriptor: LPVOID, bInheritHandle: BOOL, } #[repr(C)] #[derive(Copy, Clone)] pub struct OVERLAPPED_INNER_INNER { Offset: DWORD, OffsetHigh: DWORD, } #[repr(C)] pub union OVERLAPPED_INNER { Offset: OVERLAPPED_INNER_INNER, Pointer: PVOID, } #[repr(C)] pub struct OVERLAPPED { Internal: ULONG_PTR, InternalHigh: ULONG_PTR, union: OVERLAPPED_INNER, hEvent: HANDLE, }
use bevy::app::AppExit; use bevy::{prelude::*, tasks::IoTaskPool}; use rand::prelude::random; use crossbeam_channel::{unbounded, Receiver, Sender}; use std::net::{TcpListener, IpAddr, Ipv4Addr, SocketAddr}; use std::thread::spawn; use tungstenite::{ accept_hdr, handshake::server::{Request, Response}, protocol::Message, }; fn main() { App::build() .insert_resource(ClearColor(Color::BLACK)) .add_startup_system(setup.system()) .add_startup_stage("game_setup", SystemStage::single(spawn_player.system())) .add_system(message.system()) .add_system(handle_exit.system()) .add_system(player_movement.system()) .add_plugins(DefaultPlugins) .run(); } fn setup(mut commands: Commands, task_pool: Res<IoTaskPool>) { commands.spawn_bundle(OrthographicCameraBundle::new_2d()); let (sender, receiver) = unbounded::<String>(); let (sender2, receiver2) = unbounded::<String>(); task_pool.spawn(handshake(sender, receiver2)).detach(); commands.insert_resource(receiver); commands.insert_resource(sender2); } fn spawn_player( mut commands: Commands, mut materials: ResMut<Assets<ColorMaterial>> ) { commands .spawn_bundle(SpriteBundle { material: materials.add(Color::hsl(random::<f32>() * 255.0, 0.75, 0.75).into()), sprite: Sprite::new(Vec2::new(32.0, 32.0)), ..Default::default() }) .insert(Player); } fn player_movement( keyboard_input: Res<Input<KeyCode>>, mut player_transforms: Query<&mut Transform, With<Player>> ) { for mut player_transform in player_transforms.iter_mut() { let mut delta_x: f32 = 0.0; let mut delta_y: f32 = 0.0; if keyboard_input.pressed(KeyCode::Left) || keyboard_input.pressed(KeyCode::A) { delta_x -= 1.0; } if keyboard_input.pressed(KeyCode::Right) || keyboard_input.pressed(KeyCode::D) { delta_x += 1.0; } if keyboard_input.pressed(KeyCode::Down) || keyboard_input.pressed(KeyCode::S) { delta_y -= 1.0; } if keyboard_input.pressed(KeyCode::Up) || keyboard_input.pressed(KeyCode::W) { delta_y += 1.0; } if delta_x == 0.0 && delta_y == 0.0 { continue; } // Get input length let delta_length = (delta_x * delta_x + delta_y * delta_y).sqrt(); const SPEED: f32 = 5.0; if delta_x != 0.0 { // Normalize delta_x /= delta_length; delta_x *= SPEED; player_transform.translation.x += delta_x; } if delta_y != 0.0 { // Normalize delta_y /= delta_length; delta_y *= SPEED; player_transform.translation.y += delta_y; } } } struct Player; async fn handshake(sender: Sender<String>, receiver: Receiver<String>) { const PORT: u16 = 3012; let addr = SocketAddr::new( IpAddr::V4( Ipv4Addr::new(127, 0, 0, 1) ), PORT, ); let server = TcpListener::bind(addr).expect("Failed to bind server TcpListener."); for stream in server.incoming() { let stream = match stream { Ok(stream) => stream, Err(_) => return, }; let mut websocket = accept_hdr(stream, |req: &Request, response: Response| { info!("Received a new ws handshake at {}", req.uri()); Ok(response) }).expect("Failed to accept websocket stream."); websocket .write_message(Message::text("Hello from Rust!")) .expect("Failed to write message."); let sender = sender.clone(); let receiver = receiver.clone(); spawn(move || loop { if let Ok(response) = receiver.recv() { info!("{}", response); if response == "exit" { websocket.close(None).unwrap(); return; } } let msg = match websocket.read_message() { Err(error) => { error!("{}", error); break; }, Ok(message) => message, }; if msg.is_binary() || msg.is_text() { sender.send(msg.to_text().unwrap().into()).unwrap(); if let Ok(response) = receiver.recv() { websocket .write_message(Message::text(response)) .expect("Failed to write message"); } } }); } } fn message( sender: Res<Sender<String>>, receiver: Res<Receiver<String>>, players: Query<&Transform, With<Player>>, ) { if let Ok(_) = receiver.try_recv() { let player = players.iter().next().unwrap(); sender.send(format!("{:?}", player.translation)) .expect("Failed to send response."); } } fn handle_exit( mut exit_reader: EventReader<AppExit>, sender: Res<Sender<String>>, ) { if exit_reader.iter().next().is_some() { sender.send("exit".to_string()) .expect("Failed to send exit message."); } }
use super::{internal::Io, AsyncRead, AsyncWrite, PeerAddr, Poll}; use bytes::{Buf, BufMut}; use std::{mem::MaybeUninit, pin::Pin, task::Context}; /// A public wrapper around a `Box<Io>`. /// /// This type ensures that the proper write_buf method is called, /// to allow vectored writes to occur. pub struct BoxedIo(Pin<Box<dyn Io + Unpin>>); impl BoxedIo { pub fn new<T: Io + Unpin + 'static>(io: T) -> Self { BoxedIo(Box::pin(io)) } } impl PeerAddr for BoxedIo { fn peer_addr(&self) -> std::net::SocketAddr { self.0.peer_addr() } } impl AsyncRead for BoxedIo { fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context, buf: &mut [u8]) -> Poll<usize> { self.as_mut().0.as_mut().poll_read(cx, buf) } fn poll_read_buf<B: BufMut>( mut self: Pin<&mut Self>, cx: &mut Context, mut buf: &mut B, ) -> Poll<usize> { // A trait object of AsyncWrite would use the default poll_read_buf, // which doesn't allow vectored reads. Going through this method // allows the trait object to call the specialized poll_read_buf method. self.as_mut().0.as_mut().poll_read_buf_erased(cx, &mut buf) } unsafe fn prepare_uninitialized_buffer(&self, buf: &mut [MaybeUninit<u8>]) -> bool { self.0.prepare_uninitialized_buffer(buf) } } impl AsyncWrite for BoxedIo { fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<()> { self.as_mut().0.as_mut().poll_shutdown(cx) } fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<()> { self.as_mut().0.as_mut().poll_flush(cx) } fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context, buf: &[u8]) -> Poll<usize> { self.as_mut().0.as_mut().poll_write(cx, buf) } fn poll_write_buf<B: Buf>( mut self: Pin<&mut Self>, cx: &mut Context, buf: &mut B, ) -> Poll<usize> where Self: Sized, { // A trait object of AsyncWrite would use the default poll_write_buf, // which doesn't allow vectored writes. Going through this method // allows the trait object to call the specialized poll_write_buf // method. self.as_mut().0.as_mut().poll_write_buf_erased(cx, buf) } } impl Io for BoxedIo { /// This method is to allow using `Async::poll_write_buf` even through a /// trait object. fn poll_write_buf_erased( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut dyn Buf, ) -> Poll<usize> { self.as_mut().0.as_mut().poll_write_buf_erased(cx, buf) } /// This method is to allow using `Async::poll_read_buf` even through a /// trait object. fn poll_read_buf_erased( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut dyn BufMut, ) -> Poll<usize> { self.as_mut().0.as_mut().poll_read_buf_erased(cx, buf) } } impl std::fmt::Debug for BoxedIo { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("BoxedIo").finish() } } #[cfg(test)] mod tests { use super::*; #[derive(Debug)] struct WriteBufDetector; impl PeerAddr for WriteBufDetector { fn peer_addr(&self) -> std::net::SocketAddr { ([0, 0, 0, 0], 0).into() } } impl AsyncRead for WriteBufDetector { fn poll_read(self: Pin<&mut Self>, _: &mut Context<'_>, _: &mut [u8]) -> Poll<usize> { unreachable!("not called in test") } } impl AsyncWrite for WriteBufDetector { fn poll_shutdown(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<()> { unreachable!("not called in test") } fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<()> { unreachable!("not called in test") } fn poll_write(self: Pin<&mut Self>, _: &mut Context<'_>, _: &[u8]) -> Poll<usize> { panic!("BoxedIo called wrong write_buf method"); } fn poll_write_buf<B: bytes::Buf>( self: Pin<&mut Self>, _: &mut Context<'_>, _: &mut B, ) -> Poll<usize> { Poll::Ready(Ok(0)) } } impl Io for WriteBufDetector { fn poll_write_buf_erased( self: Pin<&mut Self>, cx: &mut Context<'_>, mut buf: &mut dyn Buf, ) -> Poll<usize> { self.poll_write_buf(cx, &mut buf) } fn poll_read_buf_erased( self: Pin<&mut Self>, _: &mut Context<'_>, _: &mut dyn BufMut, ) -> Poll<usize> { unreachable!("not called in test") } } #[tokio::test] async fn boxed_io_uses_vectored_io() { use bytes::Bytes; let mut io = BoxedIo::new(WriteBufDetector); futures::future::poll_fn(|cx| { // This method will trigger the panic in WriteBufDetector::write IFF // BoxedIo doesn't call write_buf_erased, but write_buf, and triggering // a regular write. match Pin::new(&mut io).poll_write_buf(cx, &mut Bytes::from("hello")) { Poll::Ready(Ok(_)) => {} _ => panic!("poll_write_buf should return Poll::Ready(Ok(_))"), } Poll::Ready(Ok(())) }) .await .unwrap() } }
use clap::{App, ArgMatches, SubCommand}; use webbrowser; use database::DB; pub fn make_subcommand<'a, 'b>() -> App<'a, 'b> { SubCommand::with_name("open") .about("Open bookmark") .arg_from_usage("<ID>... 'Open bookmark matching the specified ids'") } pub fn execute(args: &ArgMatches) { let db = DB::open(); let ids = values_t!(args, "ID", i64).unwrap(); for id in ids { webbrowser::open(&db.get_url_by_id(id)).unwrap(); } }
// MIT License // Copyright (c) 2018-2021 The orion Developers // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. //! # Parameters: //! - `secret_key`: The authentication key. //! - `data`: Data to be authenticated. //! - `expected`: The expected authentication tag. //! //! # Errors: //! An error will be returned if: //! - [`finalize()`] is called twice without a [`reset()`] in between. //! - [`update()`] is called after [`finalize()`] without a [`reset()`] in //! between. //! - The HMAC does not match the expected when verifying. //! //! # Security: //! - The secret key should always be generated using a CSPRNG. //! [`SecretKey::generate()`] can be used for this. It generates //! a secret key of 128 bytes. //! - The minimum recommended size for a secret key is 64 bytes. //! //! # Recommendation: //! - If you are unsure of whether to use HMAC or Poly1305, it is most often //! easier to just use HMAC. See also [Cryptographic Right Answers]. //! //! # Example: //! ```rust //! use orion::hazardous::mac::hmac::{Hmac, SecretKey}; //! //! let key = SecretKey::generate(); //! //! let mut state = Hmac::new(&key); //! state.update(b"Some message.")?; //! let tag = state.finalize()?; //! //! assert!(Hmac::verify(&tag, &key, b"Some message.").is_ok()); //! # Ok::<(), orion::errors::UnknownCryptoError>(()) //! ``` //! [`update()`]: struct.Hmac.html //! [`reset()`]: struct.Hmac.html //! [`finalize()`]: struct.Hmac.html //! [`SecretKey::generate()`]: struct.SecretKey.html //! [Cryptographic Right Answers]: https://latacora.micro.blog/2018/04/03/cryptographic-right-answers.html use crate::{ errors::UnknownCryptoError, hazardous::hash::sha512::{self, SHA512_BLOCKSIZE, SHA512_OUTSIZE}, }; use zeroize::Zeroize; construct_hmac_key! { /// A type to represent the `SecretKey` that HMAC uses for authentication. /// /// # Note: /// `SecretKey` pads the secret key for use with HMAC to a length of 128, when initialized. /// /// Using `unprotected_as_bytes()` will return the secret key with padding. /// /// `len()` will return the length with padding (always 128). /// /// # Panics: /// A panic will occur if: /// - Failure to generate random bytes securely. (SecretKey, test_hmac_key, SHA512_BLOCKSIZE) } construct_tag! { /// A type to represent the `Tag` that HMAC returns. /// /// # Errors: /// An error will be returned if: /// - `slice` is not 64 bytes. (Tag, test_tag, SHA512_OUTSIZE, SHA512_OUTSIZE) } impl_from_trait!(Tag, SHA512_OUTSIZE); #[derive(Clone)] /// HMAC-SHA512 streaming state. pub struct Hmac { working_hasher: sha512::Sha512, opad_hasher: sha512::Sha512, ipad_hasher: sha512::Sha512, is_finalized: bool, } impl core::fmt::Debug for Hmac { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!( f, "Hmac {{ working_hasher: [***OMITTED***], opad_hasher: [***OMITTED***], ipad_hasher: [***OMITTED***], is_finalized: {:?} }}", self.is_finalized ) } } impl Hmac { /// Pad `key` with `ipad` and `opad`. fn pad_key_io(&mut self, key: &SecretKey) { let mut ipad = [0x36; SHA512_BLOCKSIZE]; let mut opad = [0x5C; SHA512_BLOCKSIZE]; // The key is padded in SecretKey::from_slice for (idx, itm) in key.unprotected_as_bytes().iter().enumerate() { opad[idx] ^= itm; ipad[idx] ^= itm; } self.ipad_hasher.update(ipad.as_ref()).unwrap(); self.opad_hasher.update(opad.as_ref()).unwrap(); self.working_hasher = self.ipad_hasher.clone(); ipad.zeroize(); opad.zeroize(); } /// Initialize `Hmac` struct with a given key. pub fn new(secret_key: &SecretKey) -> Self { let mut state = Self { working_hasher: sha512::Sha512::new(), opad_hasher: sha512::Sha512::new(), ipad_hasher: sha512::Sha512::new(), is_finalized: false, }; state.pad_key_io(secret_key); state } /// Reset to `new()` state. pub fn reset(&mut self) { self.working_hasher = self.ipad_hasher.clone(); self.is_finalized = false; } #[must_use = "SECURITY WARNING: Ignoring a Result can have real security implications."] /// Update state with `data`. This can be called multiple times. pub fn update(&mut self, data: &[u8]) -> Result<(), UnknownCryptoError> { if self.is_finalized { Err(UnknownCryptoError) } else { self.working_hasher.update(data) } } #[must_use = "SECURITY WARNING: Ignoring a Result can have real security implications."] /// Return a HMAC-SHA512 tag. pub fn finalize(&mut self) -> Result<Tag, UnknownCryptoError> { if self.is_finalized { return Err(UnknownCryptoError); } self.is_finalized = true; let mut outer_hasher = self.opad_hasher.clone(); outer_hasher.update(self.working_hasher.finalize()?.as_ref())?; Tag::from_slice(outer_hasher.finalize()?.as_ref()) } #[must_use = "SECURITY WARNING: Ignoring a Result can have real security implications."] /// One-shot function for generating an HMAC-SHA512 tag of `data`. pub fn hmac(secret_key: &SecretKey, data: &[u8]) -> Result<Tag, UnknownCryptoError> { let mut state = Self::new(secret_key); state.update(data)?; state.finalize() } #[must_use = "SECURITY WARNING: Ignoring a Result can have real security implications."] /// Verify a HMAC-SHA512 tag in constant time. pub fn verify( expected: &Tag, secret_key: &SecretKey, data: &[u8], ) -> Result<(), UnknownCryptoError> { if &Self::hmac(secret_key, data)? == expected { Ok(()) } else { Err(UnknownCryptoError) } } } // Testing public functions in the module. #[cfg(test)] mod public { use super::*; #[test] #[cfg(feature = "safe_api")] fn test_debug_impl() { let secret_key = SecretKey::generate(); let initial_state = Hmac::new(&secret_key); let debug = format!("{:?}", initial_state); let expected = "Hmac { working_hasher: [***OMITTED***], opad_hasher: [***OMITTED***], ipad_hasher: [***OMITTED***], is_finalized: false }"; assert_eq!(debug, expected); } #[cfg(feature = "safe_api")] mod test_verify { use super::*; // Proptests. Only executed when NOT testing no_std. #[cfg(feature = "safe_api")] mod proptest { use super::*; quickcheck! { /// When using a different key, verify() should always yield an error. /// NOTE: Using different and same input data is tested with TestableStreamingContext. fn prop_verify_diff_key_false(data: Vec<u8>) -> bool { let sk = SecretKey::generate(); let mut state = Hmac::new(&sk); state.update(&data[..]).unwrap(); let tag = state.finalize().unwrap(); let bad_sk = SecretKey::generate(); Hmac::verify(&tag, &bad_sk, &data[..]).is_err() } } } } mod test_streaming_interface { use super::*; use crate::hazardous::hash::sha512::compare_sha512_states; use crate::test_framework::incremental_interface::*; const KEY: [u8; 32] = [0u8; 32]; impl TestableStreamingContext<Tag> for Hmac { fn reset(&mut self) -> Result<(), UnknownCryptoError> { Ok(self.reset()) } fn update(&mut self, input: &[u8]) -> Result<(), UnknownCryptoError> { self.update(input) } fn finalize(&mut self) -> Result<Tag, UnknownCryptoError> { self.finalize() } fn one_shot(input: &[u8]) -> Result<Tag, UnknownCryptoError> { Hmac::hmac(&SecretKey::from_slice(&KEY).unwrap(), input) } fn verify_result(expected: &Tag, input: &[u8]) -> Result<(), UnknownCryptoError> { // This will only run verification tests on differing input. They do not // include tests for different secret keys. Hmac::verify(expected, &SecretKey::from_slice(&KEY).unwrap(), input) } fn compare_states(state_1: &Hmac, state_2: &Hmac) { compare_sha512_states(&state_1.opad_hasher, &state_2.opad_hasher); compare_sha512_states(&state_1.ipad_hasher, &state_2.ipad_hasher); compare_sha512_states(&state_1.working_hasher, &state_2.working_hasher); assert_eq!(state_1.is_finalized, state_2.is_finalized); } } #[test] fn default_consistency_tests() { let initial_state: Hmac = Hmac::new(&SecretKey::from_slice(&KEY).unwrap()); let test_runner = StreamingContextConsistencyTester::<Tag, Hmac>::new( initial_state, SHA512_BLOCKSIZE, ); test_runner.run_all_tests(); } // Proptests. Only executed when NOT testing no_std. #[cfg(feature = "safe_api")] mod proptest { use super::*; quickcheck! { /// Related bug: https://github.com/brycx/orion/issues/46 /// Test different streaming state usage patterns. fn prop_input_to_consistency(data: Vec<u8>) -> bool { let initial_state: Hmac = Hmac::new(&SecretKey::from_slice(&KEY).unwrap()); let test_runner = StreamingContextConsistencyTester::<Tag, Hmac>::new( initial_state, SHA512_BLOCKSIZE, ); test_runner.run_all_tests_property(&data); true } } } } }
use std::env; fn main() { //initialize what to an Option<String> let what = env::args().next(); //Check if what is empty or not and do something match what { Some(string) => println!("Hello, {}", string), None => panic!("Nothing to print passed!") } }
pub mod damerau_levenshtein; pub mod jaro; pub mod jaro_winkler; pub mod levenshtein; pub mod sorensen_dice; mod utils;
#![feature(non_ascii_idents)] extern crate crossbeam; extern crate music_tools; extern crate portaudio; extern crate rand; extern crate console; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; use console::Term; use std::thread; use std::collections::{HashSet}; use std::f64::consts::{PI}; use std::f64::{MAX}; use std::io::{self, Read}; use crossbeam::queue::ArrayQueue; use music_tools::synth::{Instrument, Instrumentation, Note, Voice}; use music_tools::synth::simple_instruments::{ads, sr, Function, DAGVoice}; use music_tools::{Pitch, Scale}; use portaudio as pa; use rand::prelude::*; use std::sync::Arc; type AudioSample = f32; const CHANNELS: i32 = 1; const FRAMES: u32 = 32; const SAMPLE_HZ: f64 = 48_000.0; fn mutate(parent: &DAGVoice) -> DAGVoice { let mut rng = thread_rng(); let mut child = parent.clone(); for s in &mut child.initial_state { *s *= rng.gen_range(0.8, 1.2); } child } fn main() -> Result<(), pa::Error> { let mut voice = DAGVoice::new(1.0); let mut instrumentation = Instrumentation::new(); { let voice = voice.clone(); instrumentation.add_instrument( 0, Instrument::new(SAMPLE_HZ, 3, & move|| Box::new(voice.clone())), ); } let sample_buffer = Arc::new(ArrayQueue::new(SAMPLE_HZ as usize / 2)); let callback; { let sample_buffer = sample_buffer.clone(); callback = move |pa::OutputStreamCallbackArgs { buffer, frames, .. }| { for i in 0..frames as usize { match sample_buffer.pop() { Ok(sample) => buffer[i] = sample, Err(_) => buffer[i] = 0.0, } } pa::Continue }; } let pa = pa::PortAudio::new()?; let settings = pa.default_output_stream_settings::<AudioSample>(CHANNELS, SAMPLE_HZ, FRAMES)?; let mut stream = pa.open_non_blocking_stream(settings, callback)?; stream.start()?; let semi = 16.0 / 15.0 - 1.0; let whole = semi * 2.0; let major_scale = Scale::new(&[whole, whole, semi, whole, whole, whole, semi]); let tonic = Pitch(220.0); let mut degree = 0; let input_queue = Arc::new(ArrayQueue::new(1)); { let input_queue = input_queue.clone(); thread::spawn(move || { let term = Term::stderr(); loop { match term.read_char() { Ok(n) => { input_queue.push(n); }, Err(_) => (), } } }); } let term = Term::stdout(); loop { if !input_queue.is_empty() { let c = input_queue.pop().unwrap(); let mut regenerate = false; if c == ';' { regenerate = true; } else if c == 'q' { regenerate = true; } if regenerate { voice = mutate(&voice); term.write_line(&serde_json::to_string(&voice).unwrap()); instrumentation = Instrumentation::new(); { let voice = voice.clone(); instrumentation.add_instrument( 0, Instrument::new(SAMPLE_HZ, 3, & move|| Box::new(voice.clone())), ); } } } let len = sample_buffer.len(); if len < SAMPLE_HZ as usize / 5 { if instrumentation.exhausted() { instrumentation.reset(); let mut clock = 0.0; for _ in 0..100 { let note = Note { instrument: 0, pitch: major_scale.pitch(&tonic, degree), onset: clock, duration: 0.4, amplitude: 1.0, }; clock += 0.5; degree = (degree + 1) % 7; instrumentation.schedule_note(&note); } } while !sample_buffer.is_full() { let sample = instrumentation.sample() as f32; sample_buffer.push(sample).unwrap(); } } else { pa.sleep(500); } } }
// 引用类库用于监听读取, use std::{io::{Read, Write}, net::{TcpListener, TcpStream}}; // 引用类库用于多线程处理 use std::thread; // 引用类库用于类型转换。 use std::str; // 程序主函数 fn main() { // 定义一个请求地址和IP:端口 let addr = "127.0.0.1:8866".to_string(); // 创建一个Tcp监听,通过字符串切片将addr传入 let listener = TcpListener::bind(&addr).unwrap(); // 调用 incoming()方法接收客户端的链接信息,新信息返回一个Result枚举 for stream in listener.incoming() { // 打印有新链接进入 println!("有新客户端链接进入..."); // 模式匹配 match stream { // 当Result枚举类型匹配Ok时 Ok(stream) => { // 链接成功,开启一个新线程 thread::spawn(move|| { // 将客户端处理信息解耦到handle_client函数中,并移交stream变量所有权 handle_client(stream); }); } // 当Result枚举匹配错误时 Err(e) => { // 输出错误信息,并终止程序运行。 panic!("出错了! {:?}",e) } } } // 关闭Tcp监听链接 drop(listener); } // 线程调用的处理函数 fn handle_client(mut stream: TcpStream) { println!("客户端链接处理中..."); // 定义一个存储用的数组 let mut buf = [0; 512]; // 建立一个循环,反复读取客户的输入信息 loop { // 使用read方法 let bytes_read = stream.read(&mut buf).expect("读取出现错误,中断程序运行"); // 输出调试信息 println!("byte size: {}", bytes_read); // 如果输入的字符长度是0,直接退出循环。 if bytes_read == 0 { // 退出loop break; } // 将byte转换为str类型 let s = match str::from_utf8(&buf[..bytes_read]) { // 如果转换成功返回字符串值。 Ok(v) => v, // 遇到转换错误输出错误信息,终止程序运行。 Err(e) => { // 输出调试信息。 stream.write(b"Need utf-8 sequence.").unwrap(); // 继续监听 continue; }, }; // 如果输入的前3个字符串是 bye 则程序终止 if s.len() >= 3 && s[0..3] == "bye".to_string() { // 输出终止前的消息 stream.write(b"Bye bye and polkadot to the moooooon!!\n").unwrap(); // 跳出 loop 循环 break; } // 如果程序没有终止,返回输入的消息 stream.write(&buf[..bytes_read]).unwrap(); } }
#[derive(PartialEq)] #[derive(Debug)] pub enum Cell { Dead, Alive } pub struct Cells { pub width: usize, pub height: usize, cells: Vec<Vec<Cell>> } impl Cells { pub fn new(width: usize, height: usize) -> Cells { let mut cells = vec![]; for _ in 0..height { let mut row = vec![]; for _ in 0..width { row.push(Cell::Dead); } cells.push(row); } Cells { height: height, width: width, cells: cells } } #[allow(dead_code)] pub fn get(&self, x: usize, y: usize) -> &Cell { &self.cells[y][x] } pub fn set(&mut self, x: usize, y: usize, cell: Cell) { self.cells[y][x] = cell; } fn count_alive_cell_in_row(&self, row: &Vec<Cell>, pos: usize, skip_same_pos: bool) -> i32 { let mut count = 0; if pos > 0 && row[pos - 1] == Cell::Alive { count += 1; } if !skip_same_pos && row[pos] == Cell::Alive { count += 1; } if pos < self.width - 1 && row[pos + 1] == Cell::Alive { count += 1; } count } pub fn count_alive_adjacent_cells(&self, x: usize, y: usize) -> i32 { let mut alive_cells = 0; if y > 0 { alive_cells += self.count_alive_cell_in_row(&self.cells[y - 1], x, false); } alive_cells += self.count_alive_cell_in_row(&self.cells[y], x, true); if y < self.height - 1 { alive_cells += self.count_alive_cell_in_row(&self.cells[y + 1], x, false); } alive_cells } pub fn step(&mut self) { let mut updated_cells = vec![]; for y in 0..self.height { let mut updated_row = vec![]; for x in 0..self.width { let adjacent_cells = self.count_alive_adjacent_cells(x, y); let next_cell = match self.cells[y][x] { Cell::Alive => match adjacent_cells { 2 | 3 => Cell::Alive, 0 | 1 => Cell::Dead, _ => Cell::Dead }, Cell::Dead => match adjacent_cells { 3 => Cell::Alive, _ => Cell::Dead } }; updated_row.push(next_cell); } updated_cells.push(updated_row); } self.cells = updated_cells; } pub fn print(&self) { for row in &self.cells { for cell in row { match cell { &Cell::Alive => print!("#"), &Cell::Dead => print!(".") } } println!("") } } } #[allow(dead_code)] fn gen_test_cells() -> Cells { /* 0123 0 ##+# 1 #+#+ 2 ++++ 3 +### 4 ++#+ */ let mut cells = Cells::new(4, 5); for &(x, y) in [ (0, 0), (1, 0), (3, 0), (0, 1), (2, 1), (1, 3), (2, 3), (3, 3), (2, 4) ].iter() { cells.set(x, y, Cell::Alive); } cells } #[test] fn width_and_height() { let cells = gen_test_cells(); assert_eq!(4, cells.width); assert_eq!(5, cells.height); } #[test] fn set_and_get() { let mut cells = gen_test_cells(); assert_eq!(Cell::Alive, *cells.get(0, 0)); cells.set(0, 0, Cell::Dead); assert_eq!(Cell::Dead, *cells.get(0, 0)); cells.set(0, 0, Cell::Alive); assert_eq!(Cell::Alive, *cells.get(0, 0)); assert_eq!(Cell::Dead, *cells.get(3, 4)); cells.set(3, 4, Cell::Alive); assert_eq!(Cell::Alive, *cells.get(3, 4)); } #[test] fn count_alive_adjacent_cells() { let cells = gen_test_cells(); let expected = [ [2, 3, 3, 1], [2, 4, 2, 2], [2, 4, 4, 3], [1, 2, 3, 2], [1, 3, 3, 3] ]; for y in 0..cells.height { for x in 0..cells.width { let expected = expected[y][x]; let actual = cells.count_alive_adjacent_cells(x, y); assert!(expected == actual, "x={}, y={}, expected={}, actual={}", x, y, expected, actual); } } } #[test] fn step() { let mut cells = gen_test_cells(); cells.step(); use Cell::*; let expected = [ [Alive, Alive, Alive, Dead], [Alive, Dead, Alive, Dead], [Dead, Dead, Dead, Alive], [Dead, Alive, Alive, Alive], [Dead, Alive, Alive, Alive] ]; for y in 0..cells.height { for x in 0..cells.width { let expected = &expected[y][x]; let actual = cells.get(x, y); assert!(*expected == *actual, "x={}, y={}, expected={:?}, actual={:?}", x, y, expected, actual); } } }
use cursive::{views::*, view::*}; use super::State; use super::task; use crate::model::*; pub fn column(state: State, project: &Project, column: &Column) -> impl View { let column_view = column.tasks().iter() .filter_map(|task_id| project.task_with_id(task_id)) .map(|t| task::card(state.clone(), t)) .fold(LinearLayout::vertical(), LinearLayout::child); let scroll_view = ScrollView::new(column_view) .full_height() .fixed_width(80); Panel::new(scroll_view) .title(column.name()) }
#[macro_use] extern crate lalrpop_util; lalrpop_mod!(pub parser); fn main() { println!("Hello, world!"); let parser = parser::TermParser::new(); println!("{}", parser.parse("(((((15)))))").unwrap()); }
// Reference Pointers - Point to a resource in memory pub fn run() { //Primitive Array let arr1=[1,2,3]; let arr2=arr1; //With non-primitives,if you assign another variable to a piece of data, the first variable will no onger hold that value. You 'll need to use a reference (&) to point to the resource //Vector let vec1=vec![1,2,3]; let vec2=&vec1; println!("Values: {:?}",(&vec1,vec2)); }
// A port of the simplistic benchmark from // // http://github.com/PaulKeeble/ScalaVErlangAgents // // I *think* it's the same, more or less. use std; import std::io::writer; import std::io::writer_util; enum request { get_count, bytes(uint), stop } fn server(requests: comm::port<request>, responses: comm::chan<uint>) { let count = 0u; let done = false; while !done { alt comm::recv(requests) { get_count { comm::send(responses, copy count); } bytes(b) { count += b; } stop { done = true; } } } comm::send(responses, count); } fn run(args: [str]) { let server = task::spawn_connected(server); let size = uint::from_str(args[1]); let workers = uint::from_str(args[2]); let start = std::time::precise_time_s(); let to_child = server.to_child; let worker_tasks = []; uint::range(0u, workers) {|_i| worker_tasks += [task::spawn_joinable {|| uint::range(0u, size / workers) {|_i| comm::send(to_child, bytes(100u)); } }]; } vec::iter(worker_tasks) {|t| task::join(t); } comm::send(server.to_child, stop); let result = comm::recv(server.from_child); let end = std::time::precise_time_s(); let elapsed = end - start; std::io::stdout().write_str(#fmt("Count is %?\n", result)); std::io::stdout().write_str(#fmt("Test took %? seconds\n", elapsed)); let thruput = (size / workers * workers as float) / (elapsed as float); std::io::stdout().write_str(#fmt("Throughput=%f per sec\n", thruput)); } fn main(args: [str]) { let args1 = if vec::len(args) <= 1u { ["", "10000", "4"] } else { args }; #debug("%?", args1); run(args1); }
#[doc = "Register `SWIER2` reader"] pub type R = crate::R<SWIER2_SPEC>; #[doc = "Register `SWIER2` writer"] pub type W = crate::W<SWIER2_SPEC>; #[doc = "Field `SWIER49` reader - Software interrupt on line x+32"] pub type SWIER49_R = crate::BitReader<SWIER49W_A>; #[doc = "Software interrupt on line x+32\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum SWIER49W_A { #[doc = "1: Generates an interrupt request"] Pend = 1, } impl From<SWIER49W_A> for bool { #[inline(always)] fn from(variant: SWIER49W_A) -> Self { variant as u8 != 0 } } impl SWIER49_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> Option<SWIER49W_A> { match self.bits { true => Some(SWIER49W_A::Pend), _ => None, } } #[doc = "Generates an interrupt request"] #[inline(always)] pub fn is_pend(&self) -> bool { *self == SWIER49W_A::Pend } } #[doc = "Field `SWIER49` writer - Software interrupt on line x+32"] pub type SWIER49_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, SWIER49W_A>; impl<'a, REG, const O: u8> SWIER49_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Generates an interrupt request"] #[inline(always)] pub fn pend(self) -> &'a mut crate::W<REG> { self.variant(SWIER49W_A::Pend) } } #[doc = "Field `SWIER51` reader - Software interrupt on line x+32"] pub use SWIER49_R as SWIER51_R; #[doc = "Field `SWIER51` writer - Software interrupt on line x+32"] pub use SWIER49_W as SWIER51_W; impl R { #[doc = "Bit 17 - Software interrupt on line x+32"] #[inline(always)] pub fn swier49(&self) -> SWIER49_R { SWIER49_R::new(((self.bits >> 17) & 1) != 0) } #[doc = "Bit 19 - Software interrupt on line x+32"] #[inline(always)] pub fn swier51(&self) -> SWIER51_R { SWIER51_R::new(((self.bits >> 19) & 1) != 0) } } impl W { #[doc = "Bit 17 - Software interrupt on line x+32"] #[inline(always)] #[must_use] pub fn swier49(&mut self) -> SWIER49_W<SWIER2_SPEC, 17> { SWIER49_W::new(self) } #[doc = "Bit 19 - Software interrupt on line x+32"] #[inline(always)] #[must_use] pub fn swier51(&mut self) -> SWIER51_W<SWIER2_SPEC, 19> { SWIER51_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 = "EXTI software interrupt event register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`swier2::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 [`swier2::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct SWIER2_SPEC; impl crate::RegisterSpec for SWIER2_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`swier2::R`](R) reader structure"] impl crate::Readable for SWIER2_SPEC {} #[doc = "`write(|w| ..)` method takes [`swier2::W`](W) writer structure"] impl crate::Writable for SWIER2_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets SWIER2 to value 0"] impl crate::Resettable for SWIER2_SPEC { const RESET_VALUE: Self::Ux = 0; }
extern crate minifb; extern crate clap; use clap::{Arg, App}; use minifb::{WindowOptions, Window, Key}; use std::io::Read; use std::time::Instant; struct Registers { a: u8, b: u8, c: u8, d: u8, e: u8, f: FlagsRegister, h: u8, l: u8, } impl Registers { fn new() -> Registers { Registers { a: 0, b: 0, c: 0, d: 0, e: 0, f: FlagsRegister::new(), h: 0, l: 0 } } fn get_bc(&self) -> u16 { (self.b as u16) << 8 | self.c as u16 } fn set_bc(&mut self, value: u16) { self.b = ((value & 0xFF00) >> 8) as u8; self.c = (value & 0xFF) as u8; } fn get_de(&self) -> u16 { (self.d as u16) << 8 | self.c as u16 } fn set_de(&mut self, value: u16) { self.d = ((value & 0xFF00) >> 8) as u8; self.e = (value & 0xFF) as u8; } fn get_hl(&self) -> u16 { (self.h as u16) << 8 | self.l as u16 } fn set_hl(&mut self, value: u16) { self.h = ((value & 0xFF00) >> 8) as u8; self.l = (value & 0xFF) as u8; } } struct FlagsRegister { zero: bool, subtract: bool, half_carry: bool, carry: bool } impl FlagsRegister { pub fn new() -> FlagsRegister { FlagsRegister { zero: false, subtract: false, half_carry: false, carry: false } } } const ZERO_FLAG_BYTE_POSITION: u8 = 7; const SUBTRACT_FLAG_BYTE_POSITION: u8 = 6; const HALF_CARRY_FLAG_BYTE_POSITION: u8 = 5; const CARRY_FLAG_BYTE_POSITION: u8 = 4; const BOOT_ROM_BEGIN: usize = 0x00; const BOOT_ROM_END: usize = 0xFF; const BOOT_ROM_SIZE: usize = BOOT_ROM_END - BOOT_ROM_BEGIN + 1; const ROM_BANK_0_BEGIN: usize = 0x0000; const ROM_BANK_0_END: usize = 0x3FFF; const ROM_BANK_0_SIZE: usize = ROM_BANK_0_END - ROM_BANK_0_BEGIN + 1; const ROM_BANK_N_BEGIN: usize = 0x4000; const ROM_BANK_N_END: usize = 0x7FFF; const ROM_BANK_N_SIZE: usize = ROM_BANK_N_END - ROM_BANK_N_BEGIN + 1; const VRAM_BEGIN: usize = 0x8000; const VRAM_END: usize = 0x9FFF; const VRAM_SIZE: usize = VRAM_END - VRAM_BEGIN + 1; const EXTERNAL_RAM_BEGIN: usize = 0xA000; const EXTERNAL_RAM_END: usize = 0xBFFF; const EXTERNAL_RAM_SIZE: usize = EXTERNAL_RAM_END - EXTERNAL_RAM_BEGIN + 1; const WORKING_RAM_BEGIN: usize = 0xC000; const WORKING_RAM_END: usize = 0xDFFF; const WORKING_RAM_SIZE: usize = WORKING_RAM_END - WORKING_RAM_BEGIN + 1; const OAM_BEGIN: usize = 0xFE00; const OAM_END: usize = 0xFE9F; const OAM_SIZE: usize = OAM_END - OAM_BEGIN + 1; const IO_REGISTERS_BEGIN: usize = 0xFF00; const IO_REGISTERS_END: usize = 0xFF7F; const ZERO_PAGE_BEGIN: usize = 0xFF80; const ZERO_PAGE_END: usize = 0xFFFE; const ZERO_PAGE_SIZE: usize = ZERO_PAGE_END - ZERO_PAGE_BEGIN + 1; impl std::convert::From<FlagsRegister> for u8 { fn from(flag: FlagsRegister) -> u8 { (if flag.zero { 1 } else { 0 }) << ZERO_FLAG_BYTE_POSITION | (if flag.subtract { 1 } else { 0 }) << SUBTRACT_FLAG_BYTE_POSITION | (if flag.half_carry { 1 } else { 0 }) << HALF_CARRY_FLAG_BYTE_POSITION | (if flag.carry { 1 } else { 0 }) << CARRY_FLAG_BYTE_POSITION } } impl std::convert::From<u8> for FlagsRegister { fn from(byte: u8) -> Self { let zero = ((byte >> ZERO_FLAG_BYTE_POSITION) & 0b1) != 0; let subtract = ((byte >> SUBTRACT_FLAG_BYTE_POSITION) & 0b1) != 0; let half_carry = ((byte >> HALF_CARRY_FLAG_BYTE_POSITION) & 0b1) != 0; let carry = ((byte >> CARRY_FLAG_BYTE_POSITION) & 0b1) != 0; FlagsRegister { zero, subtract, half_carry, carry } } } enum JumpTest { NotZero, Zero, NotCarry, Carry, Always } enum IncDecTarget { B, C, BC, DE } enum PrefixTarget { A, B, C, D, E, H, L, HLI } enum LoadByteTarget { A, B, C, D, E, H, L, HLI } enum LoadByteSource { A, B, C, D, E, H, L, D8, HLI } enum LoadWordTarget { DE, HL, SP } enum Indirect { DEIndirect, HLIndirectMinus, LastByteIndirect, WordIndirect } enum LoadType { Byte(LoadByteTarget, LoadByteSource), Word(LoadWordTarget), AFromIndirect(Indirect), IndirectFromA(Indirect), ByteAddressFromA } enum StackTarget { BC, DE } #[derive(Copy, Clone, Debug, PartialEq)] pub enum BitPosition { B0, B1, B2, B3, B4, B5, B6, B7 } impl std::convert::From<BitPosition> for u8 { fn from(position: BitPosition) -> u8 { match position { BitPosition::B0 => 0, BitPosition::B1 => 1, BitPosition::B2 => 2, BitPosition::B3 => 3, BitPosition::B4 => 4, BitPosition::B5 => 5, BitPosition::B6 => 6, BitPosition::B7 => 7 } } } enum Instruction { ADD(ArithmeticTarget), BIT(PrefixTarget, BitPosition), CALL(JumpTest), DEC(IncDecTarget), INC(IncDecTarget), JP(JumpTest), JR(JumpTest), LD(LoadType), POP(StackTarget), PUSH(StackTarget), RL(PrefixTarget), RLA, XOR(ArithmeticTarget) } impl Instruction { fn from_byte(byte: u8, prefixed: bool) -> Option<Instruction> { if prefixed { Instruction::from_byte_prefixed(byte) } else { Instruction::from_byte_not_prefixed(byte) } } fn from_byte_prefixed(byte: u8) -> Option<Instruction> { match byte { 0x11 => Some(Instruction::RL(PrefixTarget::C)), 0x7c => Some(Instruction::BIT(PrefixTarget::H, BitPosition::B7)), _ => None } } fn from_byte_not_prefixed(byte: u8) -> Option<Instruction> { match byte { 0x02 => Some(Instruction::INC(IncDecTarget::BC)), 0x05 => Some(Instruction::DEC(IncDecTarget::B)), 0x06 => Some(Instruction::LD(LoadType::Byte(LoadByteTarget::B, LoadByteSource::D8))), 0x0c => Some(Instruction::INC(IncDecTarget::C)), 0x0e => Some(Instruction::LD(LoadType::Byte(LoadByteTarget::C, LoadByteSource::D8))), 0x11 => Some(Instruction::LD(LoadType::Word(LoadWordTarget::DE))), 0x13 => Some(Instruction::INC(IncDecTarget::DE)), 0x17 => Some(Instruction::RLA), 0x1a => Some(Instruction::LD(LoadType::AFromIndirect(Indirect::DEIndirect))), 0x20 => Some(Instruction::JR(JumpTest::NotZero)), 0x21 => Some(Instruction::LD(LoadType::Word(LoadWordTarget::HL))), 0x31 => Some(Instruction::LD(LoadType::Word(LoadWordTarget::SP))), 0x32 => Some(Instruction::LD(LoadType::IndirectFromA(Indirect::HLIndirectMinus))), 0x3e => Some(Instruction::LD(LoadType::Byte(LoadByteTarget::A, LoadByteSource::D8))), 0x4f => Some(Instruction::LD(LoadType::Byte(LoadByteTarget::C, LoadByteSource::A))), 0x77 => Some(Instruction::LD(LoadType::Byte(LoadByteTarget::HLI, LoadByteSource::A))), 0x7c => Some(Instruction::LD(LoadType::Byte(LoadByteTarget::A, LoadByteSource::H))), 0xaf => Some(Instruction::XOR(ArithmeticTarget::A)), 0xc1 => Some(Instruction::POP(StackTarget::BC)), 0xc5 => Some(Instruction::PUSH(StackTarget::BC)), 0xcd => Some(Instruction::CALL(JumpTest::Always)), 0xe0 => Some(Instruction::LD(LoadType::ByteAddressFromA)), 0xe2 => Some(Instruction::LD(LoadType::IndirectFromA(Indirect::LastByteIndirect))), _ => /* TODO: add instruction mappings */ None } } } enum ArithmeticTarget { A, B, C, D, E, H, L, } struct CPU { registers: Registers, pc: u16, sp: u16, bus: MemoryBus, is_halted: bool } #[derive(Copy, Clone)] enum TilePixelValue { Zero, One, Two, Three } type Tile = [[TilePixelValue; 8]; 8]; fn empty_tile() -> Tile { [[TilePixelValue::Zero; 8]; 8] } #[derive(Copy, Clone, Debug, PartialEq)] pub enum Color { White = 255, LightGray = 192, DarkGray = 96, Black = 0 } impl std::convert::From<u8> for Color { fn from(n: u8) -> Self { match n { 0 => Color::White, 1 => Color::LightGray, 2 => Color::DarkGray, 3 => Color::Black, _ => panic!("Cannot covert {} to color", n) } } } #[derive(Copy, Clone, Debug, PartialEq)] pub struct BackgroundColors( Color, Color, Color, Color ); impl BackgroundColors { fn new() -> BackgroundColors { BackgroundColors(Color::White, Color::LightGray, Color::DarkGray, Color::Black) } } impl std::convert::From<u8> for BackgroundColors { fn from(value: u8) -> Self { BackgroundColors( (value & 0b11).into(), ((value >> 2) & 0b11).into(), ((value >> 4) & 0b11).into(), (value >> 6).into(), ) } } const SCREEN_WIDTH: usize = 160; const SCREEN_HEIGHT: usize = 144; struct GPU { pub canvas_buffer: [u8; SCREEN_WIDTH * SCREEN_HEIGHT * 4], vram: [u8; VRAM_SIZE], tile_set: [Tile; 384], background_colors: BackgroundColors } impl GPU { fn new() -> GPU { GPU { canvas_buffer: [0; SCREEN_WIDTH * SCREEN_HEIGHT * 4], tile_set: [empty_tile(); 384], vram: [0; VRAM_SIZE], background_colors: BackgroundColors::new() } } fn read_vram(&self, address: usize) -> u8 { self.vram[address] } fn write_vram(&mut self, index: usize, value: u8) { self.vram[index] = value; if index >= 0x1800 { return } let normalized_index = index & 0xFFFE; let byte1 = self.vram[normalized_index]; let byte2 = self.vram[normalized_index + 1]; let tile_index = index / 16; let row_index = (index % 16) / 2; for pixel_index in 0..8 { let mask = 1 << (7 - pixel_index); let lsb = byte1 & mask; let msb = byte2 & mask; let value = match(lsb != 0, msb != 0) { (true, true) => TilePixelValue::Three, (false, true) => TilePixelValue::Two, (true, false) => TilePixelValue::One, (false, false) => TilePixelValue::Zero }; self.tile_set[tile_index][row_index][pixel_index] = value; } } } struct MemoryBus { boot_rom: Option<[u8; BOOT_ROM_SIZE]>, rom_bank_0: [u8; ROM_BANK_0_SIZE], rom_bank_n: [u8; ROM_BANK_N_SIZE], external_ram: [u8; EXTERNAL_RAM_SIZE], working_ram: [u8; WORKING_RAM_SIZE], oam: [u8; OAM_SIZE], zero_page: [u8; ZERO_PAGE_SIZE], gpu: GPU } impl MemoryBus { fn new(boot_rom_buffer: Option<Vec<u8>>, game_rom: Vec<u8>) -> MemoryBus { let boot_rom = boot_rom_buffer.map(|boot_rom_buffer| { if boot_rom_buffer.len() != BOOT_ROM_SIZE { panic!("Supplied boot ROM is wrong size. Is {} bytes, should be {} bytes", boot_rom_buffer.len(), BOOT_ROM_SIZE); } let mut boot_rom = [0; BOOT_ROM_SIZE]; boot_rom.copy_from_slice(&boot_rom_buffer); boot_rom }); let mut rom_bank_0 = [0; ROM_BANK_0_SIZE]; for i in 0..ROM_BANK_0_SIZE { rom_bank_0[i] = game_rom[i]; } let mut rom_bank_n = [0; ROM_BANK_N_SIZE]; for i in 0..ROM_BANK_N_SIZE { rom_bank_n[i] = game_rom[ROM_BANK_N_SIZE + i]; } MemoryBus { boot_rom, rom_bank_0, rom_bank_n, external_ram: [0; EXTERNAL_RAM_SIZE], working_ram: [0; WORKING_RAM_SIZE], oam: [0; OAM_SIZE], zero_page: [0; ZERO_PAGE_SIZE], gpu: GPU::new() } } fn read_byte(&self, address: u16) -> u8 { let address = address as usize; match address { BOOT_ROM_BEGIN ..= BOOT_ROM_END => { if let Some(boot_rom) = self.boot_rom { boot_rom[address] } else { self.rom_bank_0[address] } } ROM_BANK_0_BEGIN ..= ROM_BANK_0_END => { self.rom_bank_0[address] } VRAM_BEGIN ..= VRAM_END => { self.gpu.read_vram(address - VRAM_BEGIN) } 0xFFFA ..= 0xFFFB => { //println!("Reading undocumented register 0x{:x}", address); 0xFF } _ => { panic!("Reading from unknown memory at address 0x{:x}", address); } } } fn write_byte(&mut self, address: u16, value: u8) { let address = address as usize; match address { VRAM_BEGIN ... VRAM_END => { self.gpu.write_vram(address - VRAM_BEGIN, value); }, IO_REGISTERS_BEGIN ... IO_REGISTERS_END => { self.write_io_register(address, value) }, ZERO_PAGE_BEGIN ... ZERO_PAGE_END => { self.zero_page[address - ZERO_PAGE_BEGIN] = value } _ => { panic!("Writing to unknown memory section at address 0x{:x}", address); } } } fn write_io_register(&mut self, address: usize, value: u8) { match address { 0xFF11 => {println!("Writing 0x{:x} to Channel 1 sweep register", value)}, 0xFF12 => {println!("Writing 0x{:x} to Channel 1 sound length/wave pattern duty register", value)}, 0xFF24 => {println!("Writing 0x{:x} to sound volume register", value)}, 0xFF25 => {println!("Writing 0x{:x} to sound output terminal", value)}, 0xFF26 => { if (value & 128) == 0 { println!("Gameboy requesting sound disable") } else { println!("Gameboy requesting sound enable") } }, 0xFF47 => { // background colors setting self.gpu.background_colors = value.into(); } _ => panic!("Writing '0b{:b}' to an unknown I/O register {:x}", value, address) } } } impl CPU { fn new(boot_rom: Option<Vec<u8>>, game_rom: Vec<u8>) -> CPU { CPU { registers: Registers::new(), pc: 0x0, sp: 0x00, bus: MemoryBus::new(boot_rom, game_rom), is_halted: false } } fn step(&mut self) -> usize { let mut instruction_byte = self.bus.read_byte(self.pc); let prefixed = instruction_byte == 0xCB; if prefixed { instruction_byte = self.bus.read_byte(self.pc + 1); } //let description = format!("0x{}{:x}", if prefixed { "cb" } else { "" }, instruction_byte); //println!("Decoding instruction found at: {}, pc: 0x{:x}", description, self.pc); let next_pc: u16 = if let Some(instruction) = Instruction::from_byte(instruction_byte, prefixed) { self.execute(instruction) } else { let description = format!("0x{}{:x}", if prefixed { "cb" } else { "" }, instruction_byte); panic!("Unknown instruction found for: {}", description); }; self.pc = next_pc; 2 } fn jump(&self, should_jump: bool) -> u16 { if should_jump { self.read_next_word() } else { self.pc.wrapping_add(3) } } fn jump_relative(&self, should_jump: bool) -> u16 { let next_step = self.pc.wrapping_add(2); if should_jump { let offset = self.read_next_byte() as i8; let pc = if offset >= 0 { next_step.wrapping_add(offset as u16) } else { next_step.wrapping_sub(offset.abs() as u16) }; pc } else { next_step } } fn call(&mut self, should_jump: bool) -> u16 { let next_pc = self.pc.wrapping_add(3); if should_jump { self.push(next_pc); self.read_next_word() } else { next_pc } } fn execute(&mut self, instruction: Instruction) -> u16 { match instruction { Instruction::ADD(target) => { match target { ArithmeticTarget::C => { let value = self.registers.c; let new_value = self.add(value); self.registers.a = new_value; self.pc.wrapping_add(1) } _ => { /* TODO: support more targets */ self.pc } } } Instruction::BIT(register, bit_position) => { match register { PrefixTarget::H => { let value = self.registers.h; match bit_position { BitPosition::B7 => self.bit_test(value, BitPosition::B7), _ => { panic!("TODO: implement other positions for BIT comparison")} }; } _ => { panic!("TODO: implement other registers for BIT comparison")} } self.pc.wrapping_add(2) } Instruction::CALL(test) => { let jump_condition = match test { JumpTest::NotZero => !self.registers.f.zero, JumpTest::NotCarry => !self.registers.f.carry, JumpTest::Zero => self.registers.f.zero, JumpTest::Carry => self.registers.f.carry, JumpTest::Always => true }; self.call(jump_condition) } Instruction::DEC(target) => { match target { IncDecTarget::B => { let value = self.registers.b; let new_value = self.dec_8bit(value); self.registers.b = new_value; }, IncDecTarget::C => { let value = self.registers.c; let new_value = self.dec_8bit(value); self.registers.c = new_value; }, _ => {panic!("TODO: implement other targets")} }; self.pc.wrapping_add(1) } Instruction::INC(target) => { match target { IncDecTarget::C => { let value = self.registers.c; let new_value = self.inc_8bit(value); self.registers.c = new_value; }, _ => {panic!("TODO: implement other targets")} }; self.pc.wrapping_add(1) } Instruction::LD(load_type) => { match load_type { LoadType::Byte(target, source) => { let source_value = match source { LoadByteSource::A => self.registers.a, LoadByteSource::H => self.registers.h, LoadByteSource::D8 => self.read_next_byte(), LoadByteSource::HLI => self.bus.read_byte(self.registers.get_hl()), _ => { panic!("TODO: implement other sources")} }; match target { LoadByteTarget::A => self.registers.a = source_value, LoadByteTarget::B => self.registers.b = source_value, LoadByteTarget::C => self.registers.c = source_value, LoadByteTarget::HLI => self.bus.write_byte(self.registers.get_hl(), source_value), _ => { panic!("TODO: implement other targets")} } match source { LoadByteSource::D8 => self.pc.wrapping_add(2), LoadByteSource::HLI => self.pc.wrapping_add(1), _ => self.pc.wrapping_add(1), } } LoadType::Word(target) => { let word = self.read_next_word(); match target { LoadWordTarget::DE => self.registers.set_de(word), LoadWordTarget::HL => self.registers.set_hl(word), LoadWordTarget::SP => self.sp = word, _ => { panic!("TODO: implement other word targets")} } self.pc.wrapping_add(3) } LoadType::AFromIndirect(source) => { self.registers.a = match source { Indirect::DEIndirect => self.bus.read_byte(self.registers.get_de()), _ => { panic!("TODO: implement other indirect sources")}, }; match source { Indirect::WordIndirect => self.pc.wrapping_add(3), _ => self.pc.wrapping_add(1), } } LoadType::IndirectFromA(target) => { let a = self.registers.a; match target { Indirect::HLIndirectMinus => { let hl = self.registers.get_hl(); self.registers.set_hl(hl.wrapping_sub(1)); self.bus.write_byte(hl, a); }, Indirect::LastByteIndirect => { let c = self.registers.c as u16; self.bus.write_byte(0xFF00 + c, a); } _ => panic!("TODO: implement other indirect from A targets") } match target { _ => (self.pc.wrapping_add(1)) } } LoadType::ByteAddressFromA => { let offset = self.bus.read_byte(self.pc + 1) as u16; self.bus.write_byte(0xFF00 + offset, self.registers.a); self.pc.wrapping_add(2) } _ => panic!("TODO: implement other load types") } } Instruction::JP(test) => { let jump_condition = match test { JumpTest::NotZero => !self.registers.f.zero, JumpTest::NotCarry => !self.registers.f.carry, JumpTest::Zero => self.registers.f.zero, JumpTest::Carry => self.registers.f.carry, JumpTest::Always => true }; self.jump(jump_condition) } Instruction::JR(test) => { let jump_condition = match test { JumpTest::NotZero => !self.registers.f.zero, JumpTest::NotCarry => !self.registers.f.carry, JumpTest::Zero => self.registers.f.zero, JumpTest::Carry => self.registers.f.carry, JumpTest::Always => true }; self.jump_relative(jump_condition) } Instruction::POP(target) => { let result = self.pop(); match target { StackTarget::BC => self.registers.set_bc(result), _ => { panic!("TODO: support more targets")} }; self.pc.wrapping_add(1) } Instruction::PUSH(target) => { let value = match target { StackTarget::BC => self.registers.get_bc(), _ => { panic!("TODO: support more targets")} }; self.push(value); self.pc.wrapping_add(1) } Instruction::RL(register) => { match register { PrefixTarget::C => { let value = self.registers.c; let new_value = self.rotate_left_through_carry_set_zero(value); self.registers.c = new_value; } PrefixTarget::H => { let value = self.registers.h; let new_value = self.rotate_left_through_carry_set_zero(value); self.registers.h = new_value; } _ => { panic!("TODO: implement other registers for RL")} } self.pc.wrapping_add(2) } Instruction::RLA => { let value = self.registers.a; let new_value = self.rotate_left_through_carry_retain_zero(value); self.registers.a = new_value; self.pc.wrapping_add(1) } Instruction::XOR(target) => { match target { ArithmeticTarget::A => { let value = self.registers.a; let new_value = self.xor(value); self.registers.a = new_value; }, _ => { panic!("TODO: support other XOR targets")} } self.pc.wrapping_add(1) } _ => { /* TODO: support more instructions */ self.pc } } } fn add(&self, value: u8) -> u8 { 0 } fn bit_test(&mut self, value: u8, bit_position: BitPosition) { let bit_position: u8 = bit_position.into(); let result = (value >> bit_position) & 0b1; self.registers.f.zero = result == 0; self.registers.f.subtract = false; self.registers.f.half_carry = true; } fn dec_8bit(&mut self, value: u8) -> u8 { let (new_value, did_overflow) = value.overflowing_sub(1); self.registers.f.zero = new_value == 0; self.registers.f.subtract = true; self.registers.f.half_carry = (new_value & 0xF) + (value & 0xF) > 0xF; self.registers.f.carry = did_overflow; new_value } fn inc_8bit(&mut self, value: u8) -> u8 { let (new_value, did_overflow) = value.overflowing_add(1); self.registers.f.zero = new_value == 0; self.registers.f.subtract = false; self.registers.f.half_carry = (new_value & 0xF) + (value & 0xF) > 0xF; self.registers.f.carry = did_overflow; new_value } fn push(&mut self, value: u16) { self.sp = self.sp.wrapping_sub(1); self.bus.write_byte(self.sp, ((value & 0xFF00) >> 8) as u8); self.sp = self.sp.wrapping_sub(1); self.bus.write_byte(self.sp, (value & 0xFF) as u8); } fn pop(&mut self) -> u16 { let lsb = self.bus.read_byte(self.sp) as u16; self.sp = self.sp.wrapping_add(1); let msb = self.bus.read_byte(self.sp) as u16; self.sp = self.sp.wrapping_add(1); (msb << 8) | lsb } fn read_next_byte(&self) -> u8 { (self.bus.read_byte(self.pc + 1)) } fn read_next_word(&self) -> u16 { ((self.bus.read_byte(self.pc + 2) as u16) << 8) | (self.bus.read_byte(self.pc + 1) as u16) } fn rotate_left_through_carry(&mut self, value: u8, set_zero: bool) -> u8 { let carry_bit = if self.registers.f.carry { 1 } else { 0 }; let new_value = (value << 1) | carry_bit; self.registers.f.zero = set_zero && new_value == 0; self.registers.f.subtract = false; self.registers.f.half_carry = false; self.registers.f.carry = (value & 0x80) == 0x80; new_value } fn rotate_left_through_carry_set_zero(&mut self, value: u8) -> u8 { self.rotate_left_through_carry(value, true) } fn rotate_left_through_carry_retain_zero(&mut self, value: u8) -> u8 { self.rotate_left_through_carry(value, false) } fn xor(&mut self, value: u8) -> u8 { let new_value = self.registers.a ^ value; self.registers.f.zero = new_value == 0; self.registers.f.subtract = false; self.registers.f.half_carry = false; self.registers.f.carry = false; new_value } } const ENLARGEMENT_FACTOR: usize = 1; const WINDOW_DIMENSIONS: [usize; 2] = [(160 * ENLARGEMENT_FACTOR), (144 * ENLARGEMENT_FACTOR)]; fn main() { let matches = App::new("Rust GBemu") .author("Michelle Darcy <mdarcy137@gmail.com") .arg(Arg::with_name("bootrom") .short("b") .default_value("./roms/dmg_boot.bin") .value_name("FILE")) .arg(Arg::with_name("rom") .short("r") .required(true) .default_value("./roms/tetris.gb") .value_name("FILE")) .get_matches(); let boot_buffer = matches.value_of("bootrom").map(|path| buffer_from_file(path)); let game_buffer = matches.value_of("rom").map(|path| buffer_from_file(path)).unwrap(); let cpu = CPU::new(boot_buffer, game_buffer); let window = Window::new( "Rust GBemu", WINDOW_DIMENSIONS[0], WINDOW_DIMENSIONS[1], WindowOptions::default(), ).unwrap(); run(cpu, window) } const ONE_SECOND_IN_MICROS: usize = 1000000000; const ONE_SECOND_IN_CYCLES: usize = 4190000; const ONE_FRAME_IN_CYCLES: usize = 70224; const NUMBER_OF_PIXELS: usize = 23040; fn run(mut cpu: CPU, mut window: Window) { let mut buffer = [0; NUMBER_OF_PIXELS]; let mut cycles_elapsed_in_frame = 0usize; let mut now = Instant::now(); while window.is_open() && !window.is_key_down(Key::Escape) { let time_delta = now.elapsed().subsec_nanos(); now = Instant::now(); let delta = time_delta as f64 / ONE_SECOND_IN_MICROS as f64; let cycles_to_run = delta * ONE_SECOND_IN_CYCLES as f64; let mut cycles_elapsed = 0; while cycles_elapsed <= cycles_to_run as usize { cycles_elapsed += cpu.step() as usize; } cycles_elapsed_in_frame += cycles_elapsed; for (i, pixel) in cpu.bus.gpu.canvas_buffer.chunks(4).enumerate() { buffer[i] = (pixel[3] as u32) << 24 | (pixel[2] as u32) << 16 | (pixel[1] as u32) << 8 | (pixel[0] as u32) } window.update_with_buffer(&buffer).unwrap(); loop { cpu.step(); } } } fn buffer_from_file(path: &str) -> Vec<u8> { let mut file = std::fs::File::open(path).expect("File not present"); let mut buffer = Vec::new(); file.read_to_end(&mut buffer).expect("Could not read file"); buffer }
use std::fs::File; use std::io::{BufRead, BufReader}; fn parse_input(file_name: &str) -> Vec<String> { let br = BufReader::new(File::open(file_name).unwrap()); let mut v: Vec<String> = Vec::new(); for line in br.lines() { let current = match line { Ok(val) => val.clone(), Err(_) => panic!("failure to read line.") }; v.push(current); } v } fn count_trees(lines: &Vec<String>, x_jump_size: usize, y_jump_size: usize) -> u32 { let width = lines[0].len(); lines.iter() .enumerate() .filter(|(i, line)| { let mut chars = line.chars(); (i % y_jump_size == 0) && (chars.nth(x_jump_size * i / y_jump_size % width).unwrap() == '#') }) .count() as u32 } fn main() -> Result<(), std::io::Error> { let lines: Vec<String> = parse_input("input.txt"); let trees: u32 = count_trees(&lines, 1, 1); let trees1: u32 = count_trees(&lines, 3, 1); let trees2: u32 = count_trees(&lines, 5, 1); let trees3: u32 = count_trees(&lines, 7, 1); let trees4: u32 = count_trees(&lines, 1, 2); let result: u32 = &trees * &trees1 * &trees2 * &trees3 * &trees4; println!("{}", result); Ok(()) }
//! //! cd C:\Users\むずでょ\OneDrive\ドキュメント\practice-rust\kirimoti\max //! cargo check --example main-3 //! cargo run --example main-3 //! //! [crates.io](https://crates.io/) //! fn main() { let table = vec![ vec![-1, 3, -2, 10] ,vec![16, -15, 9, -7] ,vec![8, -11, 4, 5] ,vec![-6, 9, 0, -1] ]; let max = get_max(&table); println!("{:?}, max={}", table, max); } fn get_max(table:&Vec<Vec<i64>>) -> i64 { let mut max = std::i64::MIN; for row in table.iter() { for column in row.iter() { if max < *column { max = *column; } } } max }
pub fn run() { greeting("Hello", "Haardik"); // Function values to vars let sum = add(5, 5); println!("Sum: {}", sum); let dif = sub(10, 5); println!("Diff: {}", dif); // Closures (pipes) let add_nums = |n1: i32, n2: i32| n1 + n2; println!("Closure Sum: {}", add_nums(3, 4)); println!("-----------------------"); } fn greeting(greet: &str, name: &str) { println!("{} {}, nice to meet you!", greet, name); } fn add(n1: i32, n2: i32) -> i32 { // Can return by omitting semicolon n1 + n2 } fn sub(n1: i32, n2: i32) -> i32 { // Can return by including return statement with semicolon return n1 - n2; }
use rand::Rng; #[derive(Debug, Copy, Clone, PartialEq, Default)] pub struct Vec2 { pub x: f32, pub y: f32, } impl Vec2 { #[allow(dead_code)] pub fn randomize(origin: Vec2, spread: f32) -> Vec2 { let mut x = origin.x; let mut y = origin.y; x += rand::thread_rng().gen_range(-spread, spread); y += rand::thread_rng().gen_range(-spread, spread); Vec2 { x, y } } pub fn dot(&self, rhs: &Vec2) -> f32 { (self.x * rhs.x) + (self.y * rhs.y) } pub fn right() -> Vec2 { Vec2 { x: 1.0, y: 0.0 } } pub fn left() -> Vec2 { Vec2 { x: -1.0, y: 0.0 } } pub fn up() -> Vec2 { Vec2 { x: 0.0, y: -1.0 } } pub fn down() -> Vec2 { Vec2 { x: 0.0, y: 1.0 } } #[allow(dead_code)] pub fn normalzed(&self) -> Vec2 { let r: f32 = 1.0 / self.length(); Vec2 { x: self.x * r, y: self.y * r, } } #[allow(dead_code)] pub fn direction(from: Vec2, to: Vec2) -> Vec2 { let diff = to - from; diff.normalzed() } pub fn distance(from: Vec2, to: Vec2) -> f32 { let diff = to - from; diff.length() } pub fn length(&self) -> f32 { self.squared_length().sqrt() } pub fn squared_length(&self) -> f32 { self.x * self.x + self.y * self.y } } impl std::ops::Add for Vec2 { type Output = Self; fn add(self, other: Self) -> Self { Self { x: self.x + other.x, y: self.y + other.y, } } } impl std::ops::AddAssign for Vec2 { fn add_assign(&mut self, other: Self) { self.x += other.x; self.y += other.y; } } impl std::ops::MulAssign for Vec2 { fn mul_assign(&mut self, other: Self) { self.x *= other.x; self.y *= other.y; } } impl std::ops::Sub for Vec2 { type Output = Self; fn sub(self, other: Self) -> Self { Self { x: self.x - other.x, y: self.y - other.y, } } } impl std::ops::Mul<f32> for Vec2 { type Output = Self; fn mul(self, other: f32) -> Self { Self { x: self.x * other, y: self.y * other, } } }
#![feature(option_result_contains)] pub mod config; pub mod services; pub mod constants; pub mod api; pub mod queries; pub mod websocket;
use image::EncodableLayout; use pix_engine::prelude::*; use rand::distributions::{Distribution, Uniform}; use rand::rngs::ThreadRng; use std::time::Instant; use structopt::StructOpt; #[derive(StructOpt)] struct ProgArgs { // #[structopt(short, long, default_value = "800")] // width: u32, // #[structopt(short, long, default_value = "600")] // height: u32, #[structopt(short = "w", long, default_value = "300")] twidth: u32, #[structopt(short = "h", long, default_value = "225")] theight: u32, } struct CamogenDemo { img: camogen::Texture, tid: TextureId, r: ThreadRng, paint_color: Option<camogen::Color>, } impl CamogenDemo { fn new(texture_width: usize, texture_height: usize) -> CamogenDemo { CamogenDemo { img: camogen::Texture::new(texture_width, texture_height), tid: TextureId::default(), r: rand::thread_rng(), paint_color: None, } } fn randomize_texture(&mut self) { let sampler = Uniform::new(0u8, 3); for y in 0..self.img.height { for x in 0..self.img.width { self.img .set_pixel(x, y, camogen::Color::from(sampler.sample(&mut self.r))); } } } } impl PixEngine for CamogenDemo { // Set up application state and initial settings. `PixState` contains // engine specific state and utility methods for actions like getting mouse // coordinates, drawing shapes, etc. (Optional) fn on_start(&mut self, s: &mut PixState) -> PixResult<()> { self.randomize_texture(); self.tid = s.create_texture( self.img.width as u32, self.img.height as u32, PixelFormat::Rgba, )?; s.clear() } // Main update/render loop. Called as often as possible unless // `target_frame_rate` was set with a value. (Required) fn on_update(&mut self, s: &mut PixState) -> PixResult<()> { let start = Instant::now(); let mut gen_camo = true; if s.key_pressed() { if s.key_down(Key::R) { self.randomize_texture(); } else if s.key_down(Key::Q) { s.close_window(s.window_id())?; } } else if s.mouse_down(Mouse::Left) || s.mouse_down(Mouse::Right) { let pos = s.mouse_pos(); let x = (pos.x() as usize) >> 1; let y = (pos.y() as usize) >> 1; let c: camogen::Color; if let Some(stored_color) = self.paint_color { c = stored_color; } else { if s.mouse_down(Mouse::Left) { c = camogen::Color::from(random!(1, 4)); } else if s.mouse_down(Mouse::Right) { c = self.img.get_pixel(x, y); } else { c = camogen::Color::from(camogen::Pixel::Black); } self.paint_color = Some(c); } // println!("{x} {y} {c:?}"); self.img.set_pixel(x - 2, y - 2, c); self.img.set_pixel(x - 2, y - 1, c); self.img.set_pixel(x - 2, y, c); self.img.set_pixel(x - 2, y + 1, c); self.img.set_pixel(x - 2, y + 2, c); self.img.set_pixel(x - 1, y - 2, c); self.img.set_pixel(x - 1, y - 1, c); self.img.set_pixel(x - 1, y, c); self.img.set_pixel(x - 1, y + 1, c); self.img.set_pixel(x - 1, y + 2, c); self.img.set_pixel(x, y - 2, c); self.img.set_pixel(x, y - 1, c); self.img.set_pixel(x, y, c); self.img.set_pixel(x, y + 1, c); self.img.set_pixel(x, y + 2, c); self.img.set_pixel(x + 1, y - 2, c); self.img.set_pixel(x + 1, y - 1, c); self.img.set_pixel(x + 1, y, c); self.img.set_pixel(x + 1, y + 1, c); self.img.set_pixel(x + 1, y + 2, c); self.img.set_pixel(x + 2, y - 2, c); self.img.set_pixel(x + 2, y - 1, c); self.img.set_pixel(x + 2, y, c); self.img.set_pixel(x + 2, y + 1, c); self.img.set_pixel(x + 2, y + 2, c); gen_camo = false; } else if self.paint_color.is_some() { self.paint_color = None; } if gen_camo { let mut temp = camogen::Texture::new(self.img.width, self.img.height); for y in 0..self.img.height { for x in 0..self.img.width { let new_color = camogen::sample_fanbase( &self.img, x, y, self.img.get_pixel(x, y).into(), &mut self.r, ); temp.set_pixel(x, y, new_color); } } self.img = temp; } s.update_texture( self.tid, None, self.img.data_buffer.as_bytes(), self.img.width * 4, )?; s.texture(self.tid, None, None)?; let elapsed = start.elapsed(); println!("Update took {} ms", elapsed.as_millis()); Ok(()) } // Clean up any state or resources before exiting such as deleting temporary // files or saving game state. (Optional) fn on_stop(&mut self, _s: &mut PixState) -> PixResult<()> { Ok(()) } } fn main() -> PixResult<()> { let progargs = ProgArgs::from_args(); // let width = progargs.width; // let height = progargs.height; let mut demo = CamogenDemo::new(progargs.twidth as usize, progargs.theight as usize); let mut engine = Engine::builder() .dimensions(progargs.twidth * 2, progargs.theight * 2) .title("CamogenDemo") .show_frame_rate() .target_frame_rate(60) .resizable() .build()?; engine.run(&mut demo) }
use std::os::raw::{c_int, c_uchar, c_uint}; use libc::uint16_t; pub use rte_sys::*; /// Error number value, stored per-thread, which can be queried after /// calls to certain functions to determine why those functions failed. pub fn rte_errno() -> i32 { unsafe { rte_sys::_rte_errno() } }
use std::{env, path::Path}; use crate::{ git_actions::GitActions, hg_actions::HgActions, version_control_actions::VersionControlActions, }; pub fn get_current_version_control() -> Option<Box<dyn VersionControlActions>> { let mut args = env::args(); if let Some(dir) = args.nth(1) { let dir = Path::new(&dir); dir.canonicalize().expect("could not canonicalize path"); env::set_current_dir(dir).expect("could not set current directory"); } let current_dir = env::current_dir().expect("could not get current directory"); // First try Git because it's the most common and also responds the fastest let mut git_actions = Box::from(GitActions { current_dir: current_dir .to_str() .expect("current directory is not valid utf8") .into(), revision_shortcut: Default::default(), }); if git_actions.set_root().is_ok() { return Some(git_actions); } // Otherwise try Mercurial let mut hg_actions = Box::from(HgActions { current_dir: current_dir .to_str() .expect("current directory is not valid utf8") .into(), revision_shortcut: Default::default(), }); if hg_actions.set_root().is_ok() { return Some(hg_actions); } None }
use crate::*; cfg_mysql_support!( pub(crate) mod mysql; pub(crate) use mysql::establish_connection; embed_migrations!("./migrations/mysql"); ); cfg_postgres_support!( pub(crate) mod postgres; pub(crate) use postgres::establish_connection; embed_migrations!("./migrations/postgres"); ); pub fn init() { let connection = establish_connection(); // This will run the necessary migrations. embedded_migrations::run(&connection).unwrap(); }
#![warn(rust_2018_idioms)] #[macro_use] extern crate glium; #[macro_use] extern crate slog; #[macro_use(define_roles)] extern crate smithay; use slog::Drain; use smithay::reexports::{calloop::EventLoop, wayland_server::Display}; #[macro_use] mod shaders; mod glium_drawer; mod input_handler; mod shell; mod shm_load; #[cfg(feature = "udev")] mod udev; mod window_map; #[cfg(feature = "winit")] mod winit; static POSSIBLE_BACKENDS: &'static [&'static str] = &[ #[cfg(feature = "winit")] "--winit : Run anvil as a X11 or Wayland client using winit.", #[cfg(feature = "udev")] "--tty-udev : Run anvil as a tty udev client (requires root if without logind).", ]; fn main() { // A logger facility, here we use the terminal here let log = slog::Logger::root( slog_async::Async::default(slog_term::term_full().fuse()).fuse(), o!(), ); let mut event_loop = EventLoop::<()>::new().unwrap(); let mut display = Display::new(event_loop.handle()); let arg = ::std::env::args().nth(1); match arg.as_ref().map(|s| &s[..]) { #[cfg(feature = "winit")] Some("--winit") => { info!(log, "Starting anvil with winit backend"); if let Err(()) = winit::run_winit(&mut display, &mut event_loop, log.clone()) { crit!(log, "Failed to initialize winit backend."); } } #[cfg(feature = "udev")] Some("--tty-udev") => { info!(log, "Starting anvil on a tty using udev"); if let Err(()) = udev::run_udev(display, event_loop, log.clone()) { crit!(log, "Failed to initialize tty backend."); } } _ => { println!("USAGE: anvil --backend"); println!(); println!("Possible backends are:"); for b in POSSIBLE_BACKENDS { println!("\t{}", b); } } } }
//! ```cargo //! [dependencies] //! toml = "0.5" //! serde = { version = "1.0", features = ["derive"] } //! ``` // Copyright Jeron Aldaron Lau 2017 - 2020. // Distributed under either the Apache License, Version 2.0 // (See accompanying file LICENSE_APACHE_2_0.txt or copy at // https://apache.org/licenses/LICENSE-2.0), // or the Boost Software License, Version 1.0. // (See accompanying file LICENSE_BOOST_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) // at your option. This file may not be copied, modified, or distributed except // according to those terms. use std::{ env, fs, io, path::{Path, PathBuf}, }; mod format { include!(concat!(env!("RUST_SCRIPT_BASE_PATH"), "/ctlr_db/format.rs")); } fn main() -> io::Result<()> { // Get path to this script's directory from the enviroment let mut dir = PathBuf::from(env::var("RUST_SCRIPT_BASE_PATH").unwrap()); // Add the folder structure to base path dir.push("ctlr_db"); dir.push("ctlr"); dir.push("list"); // Printing for clarity println!("The directory is: {:?}", dir); if dir.is_dir() { order_dir(dir.as_path()) } else { Err(io::Error::from(io::ErrorKind::NotFound)) } } /// Loop through each folder in the directory fn order_dir(dir: &Path) -> io::Result<()> { for file in Path::new(dir).read_dir()? { order_file(file?.path().as_path())?; } Ok(()) } /// This reads a file into a string /// Tries to parse it from toml into a Controller struct /// Sorts the inner structs (button, axis, etc.) by code /// Tries to parse to toml again /// Write to file fn order_file(file_path: &Path) -> io::Result<()> { println!("{:?}", file_path); let content = fs::read_to_string(file_path)?; let mut pad: format::CtlrMapping = toml::from_str(&content).expect("Error parsing file"); sort_by_code(&mut pad); let toml = toml::to_string(&pad).expect("Error serializing file"); fs::write(file_path, &toml) } fn sort_by_code(pad: &mut format::CtlrMapping) { sort_by_code_button(pad); sort_by_code_axis(pad); sort_by_code_trigger(pad); sort_by_code_three_way(pad); sort_by_code_wheel(pad); } fn sort_by_code_button(pad: &mut format::CtlrMapping) { if let Some(ref mut v) = pad.button { v.sort_by(|a, b| a.code.cmp(&b.code)); } } fn sort_by_code_axis(pad: &mut format::CtlrMapping) { if let Some(ref mut v) = pad.axis { v.sort_by(|a, b| a.code.cmp(&b.code)); } } fn sort_by_code_trigger(pad: &mut format::CtlrMapping) { if let Some(ref mut v) = pad.trigger { v.sort_by(|a, b| a.code.cmp(&b.code)); } } fn sort_by_code_three_way(pad: &mut format::CtlrMapping) { if let Some(ref mut v) = pad.three_way { v.sort_by(|a, b| a.code.cmp(&b.code)); } } fn sort_by_code_wheel(pad: &mut format::CtlrMapping) { if let Some(ref mut v) = pad.wheel { v.sort_by(|a, b| a.code.cmp(&b.code)); } }
mod client; mod config; mod miner; mod worker; use byteorder::{ByteOrder, LittleEndian}; pub use crate::client::Client; pub use crate::config::MinerConfig; pub use crate::miner::Miner; use ckb_core::block::{Block, BlockBuilder}; use ckb_jsonrpc_types::BlockTemplate; use std::convert::From; use ckb_core::difficulty::difficulty_to_target; use ckb_hash::blake2b_256; use numext_fixed_hash::H256; use numext_fixed_uint::U256; #[derive(Debug, Clone)] pub struct Work { work_id: u64, block: Block, } impl From<BlockTemplate> for Work { fn from(block_template: BlockTemplate) -> Work { let work_id = block_template.work_id.clone(); let block: BlockBuilder = block_template.into(); let block = block.build(); Work { work_id: work_id.0, block, } } } pub fn verify_proof_difficulty(proof: &[u8], difficulty: &U256) -> bool { let proof_hash: H256 = blake2b_256(proof).into(); proof_hash < difficulty_to_target(difficulty) } pub fn pow_message(pow_hash: &H256, nonce: u64) -> [u8; 40] { let mut message = [0; 40]; message[8..40].copy_from_slice(&pow_hash[..]); LittleEndian::write_u64(&mut message, nonce); message }
use super::super::entity::CategoryResult; use super::super::entity::Category; use log::{trace}; const TOLERANCE: f64 = 0.00000000001; struct Combinatorial { total: u32, // n current: Vec<u32>, // has size m current_n: u32, } // iterate through all possible combinations where sum of vector entries = total // inefficient algorithm complexity: total^size or O(n^m) impl Combinatorial { fn new(size: usize, total: u32) -> Combinatorial { let mut current : Vec<u32> = Vec::new(); for _ in 0..size { current.push(0); } Self { total, current, current_n: 0, } } } impl Iterator for Combinatorial { type Item = Vec<u32>; fn next(&mut self) -> Option<Self::Item> { let base = self.total+1; let len = self.current.len(); let max_n = base.pow(len as u32); for n in self.current_n..max_n { // set all the numbers in the vector for i in 0..len { let x = len - 1 - i; let curr_base = base.pow((i) as u32); let shifted = (n - (n % curr_base)) / curr_base; self.current[x] = shifted % base; } // try if self.current.clone().into_iter().sum::<u32>() == self.total { self.current_n = n + 1; //println!("Eureka!"); return Some(self.current.clone()); } } return None; } } pub fn compute(input: Vec<CategoryResult>) -> Vec<Category> { input.into_iter().map(|mut i| { // for each category, we must satisfy // sum of items_sold = i.summary.num_items trace!("Trying combo for {:?} items and total number sold: {:?}",i.category.items.len(), i.summary.num_items); let mut combo = Combinatorial::new(i.category.items.len(), i.summary.num_items as u32); // put all solutions in this vector: let mut solutions: Vec<Vec<u32>> = vec![]; loop { let guess = combo.next(); match guess { None => { // reached the end of break }, Some(guess) => { let soln = guess.clone(); // sum of (item.price * item.items_sold) = i.summary.total_sale let matches = (i.category.items.clone().into_iter() .map( |item| item.price) .zip(guess.into_iter()) .map(| (x, y) | x*(y as f64)) .sum::<f64>() - i.summary.total_sale).abs() <= TOLERANCE; if matches { trace!("Found solution {:?}", soln); solutions.push(soln); } } } } solutions.into_iter().for_each( | soln: Vec<u32> | { trace!("Combo {:?} matched!", soln); for x in 0..i.category.items.len() { //let copy = soln.clone(); let curr_items = i.category.items[x].items_sold.clone(); let curr_totals = i.category.items[x].total_price.clone(); let item_price = i.category.items[x].price; let mut new_items: Vec<usize>; let mut new_totals: Vec<f64>; match curr_items { None => { new_items = vec![]; } Some(sold) => { new_items = sold; //sold.push(copy[x] as usize); } } new_items.push(soln[x] as usize); i.category.items[x].items_sold = Some(new_items); match curr_totals { None => { new_totals = vec![]; } Some(sold) => { new_totals = sold; } } // round result to 2 decimal places: new_totals.push((item_price * (soln[x] as f64) * 100.0).round() / 100.0); i.category.items[x].total_price = Some(new_totals); } }); i.category }).collect() } #[cfg(test)] mod tests { use super::{Category, CategoryResult, compute}; use super::super::super::entity::{InventoryItem, InputSummary}; fn helper_get_sample() -> Vec<CategoryResult> { vec![CategoryResult { category: Category { name: "Vinegar".to_string(), items: vec![ InventoryItem { description: "1L".to_string(), price: 290.0, items_sold: None, total_price: None, }] }, summary: InputSummary { num_items: 1, total_sale: 290.0 } }, CategoryResult { category: Category { name: "soy sauce".to_string(), items: vec![ InventoryItem { description: "Dashi 1L".to_string(), price: 905.0, items_sold: None, total_price: None, }, InventoryItem { description: "Silver 1L".to_string(), price: 540.0, items_sold: None, total_price: None, }] }, summary: InputSummary { num_items: 22, total_sale: 14070.0 } }, CategoryResult { category: Category { name: "Sashimi sauce".to_string(), items: vec![ InventoryItem { description: "0.153L".to_string(), price: 260.0, items_sold: None, total_price: None, }, InventoryItem { description: "0.36L".to_string(), price: 450.0, items_sold: None, total_price: None, }, InventoryItem { description: "1L".to_string(), price: 940.0, items_sold: None, total_price: None, }] }, summary: InputSummary { num_items: 16, total_sale: 7420.0, } }] } #[test] fn test_common_case() { let input: Vec<CategoryResult> = helper_get_sample(); let res = compute(input); assert_eq!(res.len(), 3); assert_eq!(res[0].items[0].items_sold, Some(vec![1])); assert_eq!(res[0].items[0].total_price, Some(vec![290.0])); assert_eq!(res[1].items[0].items_sold, Some(vec![6])); assert_eq!(res[1].items[0].total_price, Some(vec![6.0*905.0])); assert_eq!(res[1].items[1].items_sold, Some(vec![16])); assert_eq!(res[1].items[1].total_price, Some(vec![16.0*540.0])); assert_eq!(res[2].items[0].items_sold, Some(vec![4])); assert_eq!(res[2].items[0].total_price, Some(vec![4.0*260.0])); assert_eq!(res[2].items[1].items_sold, Some(vec![10])); assert_eq!(res[2].items[1].total_price, Some(vec![10.0*450.0])); assert_eq!(res[2].items[2].items_sold, Some(vec![2])); assert_eq!(res[2].items[2].total_price, Some(vec![2.0*940.0])); } #[test] fn test_with_zero_sales() { let mut input = helper_get_sample(); input[0].summary.num_items = 0; input[0].summary.total_sale = 0.0; let res = compute(input); assert_eq!(res[0].items[0].items_sold, Some(vec![0])); assert_eq!(res[0].items[0].total_price, Some(vec![0.0])); assert_eq!(res[1].items[0].items_sold, Some(vec![6])); assert_eq!(res[1].items[0].total_price, Some(vec![6.0*905.0])); assert_eq!(res[1].items[1].items_sold, Some(vec![16])); assert_eq!(res[1].items[1].total_price, Some(vec![16.0*540.0])); assert_eq!(res[2].items[0].items_sold, Some(vec![4])); assert_eq!(res[2].items[0].total_price, Some(vec![4.0*260.0])); assert_eq!(res[2].items[1].items_sold, Some(vec![10])); assert_eq!(res[2].items[1].total_price, Some(vec![10.0*450.0])); assert_eq!(res[2].items[2].items_sold, Some(vec![2])); assert_eq!(res[2].items[2].total_price, Some(vec![2.0*940.0])); } #[test] fn test_multiple_solns() { let input: Vec<CategoryResult> = vec![CategoryResult { category: Category { name: "Apple".to_string(), items: vec![InventoryItem { description: "McIntosh".to_string(), price: 3.0, items_sold: None, total_price: None, }, InventoryItem { description: "Fuji".to_string(), price: 3.0, items_sold: None, total_price: None, }, InventoryItem { description: "Gala".to_string(), price: 3.0, items_sold: None, total_price: None, }] }, summary: InputSummary { num_items: 3, total_sale: 9.0 } }]; let res = compute(input); assert_eq!(res[0].items[0].items_sold, Some(vec![0, 0, 0, 0, 1, 1, 1, 2, 2, 3])); assert_eq!(res[0].items[0].total_price, Some(vec![0.0, 0.0, 0.0, 0.0, 3.0, 3.0, 3.0, 6.0, 6.0, 9.0])); assert_eq!(res[0].items[1].items_sold, Some(vec![0, 1, 2, 3, 0, 1, 2, 0, 1, 0])); assert_eq!(res[0].items[1].total_price, Some(vec![0.0, 3.0, 6.0, 9.0, 0.0, 3.0, 6.0, 0.0, 3.0, 0.0])); assert_eq!(res[0].items[2].items_sold, Some(vec![3, 2, 1, 0, 2, 1, 0, 1, 0, 0])); assert_eq!(res[0].items[2].total_price, Some(vec![9.0, 6.0, 3.0, 0.0, 6.0, 3.0, 0.0, 3.0, 0.0, 0.0])); } }
use crate::{Context, Error}; use reqwest::header; use serde::Deserialize; const USER_AGENT: &str = "kangalioo/rustbot"; #[derive(Debug, Deserialize)] struct Crates { crates: Vec<Crate>, } #[derive(Debug, Deserialize)] struct Crate { id: String, name: String, newest_version: String, updated_at: String, downloads: u64, description: Option<String>, documentation: Option<String>, exact_match: bool, } /// Queries the crates.io crates list for a specific crate async fn get_crate(http: &reqwest::Client, query: &str) -> Result<Crate, Error> { log::info!("searching for crate `{}`", query); let crate_list = http .get("https://crates.io/api/v1/crates") .header(header::USER_AGENT, USER_AGENT) .query(&[("q", query)]) .send() .await? .json::<Crates>() .await?; let crate_ = crate_list .crates .into_iter() .next() .ok_or_else(|| format!("Crate `{}` not found", query))?; if crate_.exact_match { Ok(crate_) } else { Err(format!( "Crate `{}` not found. Did you mean `{}`?", query, crate_.name ) .into()) } } fn get_documentation(crate_: &Crate) -> String { match &crate_.documentation { Some(doc) => doc.to_owned(), None => format!("https://docs.rs/{}", crate_.name), } } /// 6051423 -> "6 051 423" fn format_number(mut n: u64) -> String { let mut output = String::new(); while n >= 1000 { output.insert_str(0, &format!(" {:03}", n % 1000)); n /= 1000; } output.insert_str(0, &format!("{}", n)); output } /// Lookup crates on crates.io /// /// Search for a crate on crates.io /// ``` /// ?crate crate_name /// ``` #[poise::command( prefix_command, rename = "crate", broadcast_typing, track_edits, slash_command )] pub async fn crate_( ctx: Context<'_>, #[description = "Name of the searched crate"] crate_name: String, ) -> Result<(), Error> { if let Some(url) = rustc_crate_link(&crate_name) { poise::say_reply(ctx, url.to_owned()).await?; return Ok(()); } let crate_ = get_crate(&ctx.data().http, &crate_name).await?; poise::send_reply(ctx, |m| { m.embed(|e| { e.title(&crate_.name) .url(get_documentation(&crate_)) .description( &crate_ .description .as_deref() .unwrap_or("_<no description available>_"), ) .field("Version", &crate_.newest_version, true) .field("Downloads", format_number(crate_.downloads), true) .timestamp(crate_.updated_at.as_str()) .color(crate::EMBED_COLOR) }) }) .await?; Ok(()) } /// Provide the documentation link to an official Rust crate (e.g. std, alloc, nightly) fn rustc_crate_link(crate_name: &str) -> Option<&'static str> { match crate_name.to_ascii_lowercase().as_str() { "std" => Some("https://doc.rust-lang.org/stable/std/"), "core" => Some("https://doc.rust-lang.org/stable/core/"), "alloc" => Some("https://doc.rust-lang.org/stable/alloc/"), "proc_macro" => Some("https://doc.rust-lang.org/stable/proc_macro/"), "beta" => Some("https://doc.rust-lang.org/beta/std/"), "nightly" => Some("https://doc.rust-lang.org/nightly/std/"), "rustc" => Some("https://doc.rust-lang.org/nightly/nightly-rustc/"), "test" => Some("https://doc.rust-lang.org/stable/test"), _ => None, } } /// Lookup documentation /// /// Retrieve documentation for a given crate /// ``` /// ?docs crate_name::module::item /// ``` #[poise::command( prefix_command, aliases("docs"), broadcast_typing, track_edits, slash_command )] pub async fn doc( ctx: Context<'_>, #[description = "Path of the crate and item to lookup"] query: String, ) -> Result<(), Error> { let mut query_iter = query.splitn(2, "::"); let crate_name = query_iter.next().unwrap(); let mut doc_url = if let Some(rustc_crate) = rustc_crate_link(crate_name) { rustc_crate.to_owned() } else if crate_name.is_empty() { "https://doc.rust-lang.org/stable/std/".to_owned() } else { get_documentation(&get_crate(&ctx.data().http, crate_name).await?) }; if let Some(item_path) = query_iter.next() { doc_url += "?search="; doc_url += item_path; } poise::say_reply(ctx, doc_url).await?; Ok(()) }
use crate::query::refs::*; use crate::query::*; #[derive(Debug)] pub struct MinifiedFormatter { buf: String, } impl Default for MinifiedFormatter { fn default() -> Self { Self { buf: String::with_capacity(1024), } } } pub trait MinifiedString { /// writes the minified string representation of this type, returns true if whitespace is needed after it. fn minify(&self, f: &mut MinifiedFormatter) -> bool; } pub trait DisplayMinified { fn minified(&self) -> String; } impl<T: MinifiedString> DisplayMinified for T { fn minified(&self) -> String { let mut formatter = MinifiedFormatter::default(); self.minify(&mut formatter); formatter.buf } } macro_rules! minify_each { ({$f:ident, $v:expr}) => { if !$v.is_empty() { write!($f, "{"); minify_each!($f, $v); write!($f, "}"); } }; (($f:ident, $v:expr) no_space) => { if !$v.is_empty() { write!($f, "("); for t in $v.iter() { t.minify($f); } write!($f, ")"); } }; (($f:ident, $v:expr)) => { if !$v.is_empty() { write!($f, "("); minify_each!($f, $v); write!($f, ")"); } }; ($f:ident, $v:expr) => { let mut space = false; for t in $v.iter() { if space { write!($f, " "); } space = t.minify($f); } }; } macro_rules! minify_enum { ($t:path, $($p:path),+) => { impl MinifiedString for $t { fn minify(&self, f: &mut MinifiedFormatter) -> bool { match self { $( $p(v) => v.minify(f) ),* } } } }; } macro_rules! write_escaped { ($f:ident, $e:expr) => { write!(escaped $f, $e); }; } macro_rules! write { (escaped $f:ident, $e:expr) => { if $e.contains('\\') || $e.contains('"') { for c in $e.chars() { if c == '"' { $f.buf.push_str("\\\""); } else if c == '\\' { $f.buf.push_str(r"\\"); } else { $f.buf.push(c); } } } else { write!($f, $e); } }; ($f:ident, $($e:expr,)*) => { $( if $e.len() == 1 { $f.buf.push($e.chars().next().unwrap()) } else { $f.buf.push_str($e) } )* }; ($f:ident, $($e:expr),*) => { write!($f, $($e,)*); }; } impl<'a> MinifiedString for Document<'a> { fn minify(&self, f: &mut MinifiedFormatter) -> bool { minify_each!(f, self.definitions); false } } minify_enum!( Definition<'_>, Definition::SelectionSet, Definition::Operation, Definition::Fragment ); impl<'a> MinifiedString for FragmentDefinition<'a> { fn minify(&self, f: &mut MinifiedFormatter) -> bool { write!(f, "fragment ", self.name, " on ", self.type_condition); minify_each!(f, self.directives); self.selection_set.minify(f); self.selection_set.items.is_empty() } } impl<'a> MinifiedString for FragmentDefinitionRef<'a> { fn minify(&self, f: &mut MinifiedFormatter) -> bool { write!(f, "fragment ", &self.name, " on ", &self.type_condition); self.selection_set.minify(f); self.selection_set.items.is_empty() } } impl<'a> MinifiedString for OperationDefinition<'a> { fn minify(&self, f: &mut MinifiedFormatter) -> bool { write!(f, self.kind.as_str()); if let Some(name) = self.name { write!(f, " ", name); } minify_each!((f, self.variable_definitions) no_space); minify_each!(f, self.directives); self.selection_set.minify(f); self.selection_set.items.is_empty() } } impl<'a> MinifiedString for SelectionSet<'a> { fn minify(&self, f: &mut MinifiedFormatter) -> bool { minify_each!({f, self.items}); false } } impl<'a> MinifiedString for SelectionSetRef<'a> { fn minify(&self, f: &mut MinifiedFormatter) -> bool { minify_each!({f, self.items}); false } } impl<'a> MinifiedString for VariableDefinition<'a> { fn minify(&self, f: &mut MinifiedFormatter) -> bool { write!(f, "$", self.name, ":",); self.var_type.minify(f); if let Some(ref default) = self.default_value { write!(f, "="); default.minify(f); }; true } } minify_enum!( Selection<'_>, Selection::Field, Selection::FragmentSpread, Selection::InlineFragment ); minify_enum!( SelectionRef<'_>, SelectionRef::Ref, SelectionRef::Field, SelectionRef::FieldRef, SelectionRef::InlineFragmentRef, SelectionRef::FragmentSpreadRef ); impl<'a> MinifiedString for FragmentSpreadRef { fn minify(&self, f: &mut MinifiedFormatter) -> bool { write!(f, "...", &self.name); true } } impl<'a> MinifiedString for Field<'a> { fn minify(&self, f: &mut MinifiedFormatter) -> bool { if let Some(alias) = self.alias { write!(f, alias, ":"); } write!(f, self.name); minify_each!((f, self.arguments)); minify_each!(f, self.directives); self.selection_set.minify(f); self.selection_set.items.is_empty() } } impl<'a> MinifiedString for FieldRef<'a> { fn minify(&self, f: &mut MinifiedFormatter) -> bool { if let Some(alias) = self.alias { write!(f, alias, ":"); } write!(f, self.name); minify_each!((f, self.arguments)); minify_each!(f, self.directives); self.selection_set.minify(f); self.selection_set.items.is_empty() } } impl<'a> MinifiedString for FragmentSpread<'a> { fn minify(&self, f: &mut MinifiedFormatter) -> bool { write!(f, "...", self.fragment_name); minify_each!(f, self.directives); true } } impl<'a> MinifiedString for InlineFragment<'a> { fn minify(&self, f: &mut MinifiedFormatter) -> bool { write!(f, "..."); if let Some(cond) = self.type_condition { write!(f, "on ", cond); } minify_each!(f, self.directives); self.selection_set.minify(f); self.selection_set.items.is_empty() } } impl<'a> MinifiedString for InlineFragmentRef<'a> { fn minify(&self, f: &mut MinifiedFormatter) -> bool { write!(f, "..."); if let Some(cond) = self.type_condition { write!(f, "on ", cond); } minify_each!(f, self.directives); self.selection_set.minify(f); self.selection_set.items.is_empty() } } impl<'a> MinifiedString for Directive<'a> { fn minify(&self, f: &mut MinifiedFormatter) -> bool { write!(f, "@", self.name); minify_each!((f, self.arguments)); true } } impl<'a> MinifiedString for Value<'a> { fn minify(&self, f: &mut MinifiedFormatter) -> bool { match self { Value::Variable(name) => { write!(f, "$", name); true } Value::Int(ref num) => { write!(f, &format!("{}", num)); true } Value::Float(val) => { write!(f, &format!("{}", val)); true } Value::String(ref val) => { write!(f, "\""); write_escaped!(f, val); write!(f, "\""); true } Value::Boolean(true) => { write!(f, "true"); true } Value::Boolean(false) => { write!(f, "false"); true } Value::Null => { write!(f, "null"); true } Value::Enum(name) => { write!(f, name); true } Value::List(ref items) => { write!(f, "["); minify_each!(f, items); write!(f, "]"); false } Value::Object(items) => { write!(f, "{"); minify_each!(f, items); write!(f, "}"); false } } } } impl<'a> MinifiedString for (Txt<'a>, Value<'a>) { fn minify(&self, f: &mut MinifiedFormatter) -> bool { let (a, b) = self; write!(f, a, ":"); b.minify(f); true } } impl<'a> MinifiedString for (&Txt<'a>, &Value<'a>) { fn minify(&self, f: &mut MinifiedFormatter) -> bool { let (a, b) = self; write!(f, a, ":"); b.minify(f); true } } impl<'a> MinifiedString for Type<'a> { fn minify(&self, f: &mut MinifiedFormatter) -> bool { match self { Type::NamedType(name) => { write!(f, name); true } Type::ListType(typ) => { write!(f, "["); typ.minify(f); write!(f, "]"); false } Type::NonNullType(typ) => { typ.minify(f); write!(f, "!"); false } } } } #[cfg(test)] mod tests { use crate::{parse_query, DisplayMinified}; #[test] fn minify() { let queries: Vec<&str> = vec![ "{a{b}c}", "query{testing}", "{body{__typename nested{__typename}}test{__typename nested{__typename}}}", "query($representations:[_Any!]!){_entities(representations:$representations){...on Book{__typename isbn title year}}}", "{body{__typename ...on Image{attributes{url}}...on Text{attributes{bold text}}}}", "query($arg:String$arg2:Int){field(argValue:$arg){otherField field3(foo:$arg2)}}", "query($representations:[_Any!]!){_entities(representations:$representations){...on User{reviews{body}numberOfReviews}}}", "query($representations:[_Any!]!$format:Boolean){_entities(representations:$representations){...on User{reviews{body(format:$format)}}}}", "query($arg1:String$representations:[_Any!]!){_entities(arg:$arg1 representations:$representations){...on User{reviews{body}numberOfReviews}}}", "{vehicle(id:\"{\\\"make\\\":\\\"Toyota\\\",\\\"model\\\":\\\"Rav4\\\",\\\"trim\\\":\\\"Limited\\\"}\")}", "{vehicle(id:\"this is a \\\\ string with a slash \\\\ \")}", ]; for query in queries { let parsed = parse_query(query).unwrap(); assert_eq!(query, parsed.minified()) } } }
use ::*; #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum MouseEventType { Click, MouseDown, MouseUp, DblClick, MouseMove, MouseEnter, MouseLeave, } impl MouseEventType { fn from(event: EM_EVENT_TYPE) -> MouseEventType { match event { EMSCRIPTEN_EVENT_CLICK => MouseEventType::Click, EMSCRIPTEN_EVENT_MOUSEDOWN => MouseEventType::MouseDown, EMSCRIPTEN_EVENT_MOUSEUP => MouseEventType::MouseUp, EMSCRIPTEN_EVENT_DBLCLICK => MouseEventType::DblClick, EMSCRIPTEN_EVENT_MOUSEMOVE => MouseEventType::MouseMove, EMSCRIPTEN_EVENT_MOUSEENTER => MouseEventType::MouseEnter, EMSCRIPTEN_EVENT_MOUSELEAVE => MouseEventType::MouseLeave, _ => unreachable!(), } } } #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum MouseButton { Left, Middle, Right, } impl MouseButton { fn from(button: c_ushort) -> MouseButton { match button { 0 => MouseButton::Left, 1 => MouseButton::Middle, 2 => MouseButton::Right, _ => unreachable!(), } } } #[derive(Debug)] pub struct MouseEvent { pub screen_pos: (i32, i32), pub client_pos: (i32, i32), pub ctrl_key: bool, pub shift_key: bool, pub alt_key: bool, pub meta_key: bool, pub button: MouseButton, pub movement: (i32, i32), pub target_pos: (i32, i32), pub canvas_pos: (i32, i32), pub padding: i32, } impl MouseEvent { pub(crate) fn from(event: &EmscriptenMouseEvent) -> MouseEvent { MouseEvent { screen_pos: (event.screenX as i32, event.screenY as i32), client_pos: (event.clientX as i32, event.clientY as i32), ctrl_key: event.ctrlKey != EM_FALSE, shift_key: event.shiftKey != EM_FALSE, alt_key: event.altKey != EM_FALSE, meta_key: event.metaKey != EM_FALSE, button: MouseButton::from(event.button), movement: (event.movementX as i32, event.movementY as i32), target_pos: (event.targetX as i32, event.targetY as i32), canvas_pos: (event.canvasX as i32, event.canvasY as i32), padding: event.padding as i32, } } } #[allow(non_snake_case)] type Registrator = unsafe extern "C" fn( target: *const c_char, userData: *mut c_void, useCapture: EM_BOOL, callback: em_mouse_callback_func, ) -> EMSCRIPTEN_RESULT; fn set_callback<F>( registrator: Registrator, target: Selector, use_capture: bool, callback: F, ) -> HtmlResult<()> where F: FnMut(MouseEventType, MouseEvent) -> bool + 'static, { let result = unsafe { registrator( selector_as_ptr!(target), Box::<F>::into_raw(Box::new(callback)) as *mut _, if use_capture { EM_TRUE } else { EM_FALSE }, Some(wrapper::<F>), ) }; return match parse_html_result(result) { None => Ok(()), Some(err) => Err(err), }; #[allow(non_snake_case)] unsafe extern "C" fn wrapper<F: FnMut(MouseEventType, MouseEvent) -> bool + 'static>( eventType: EM_EVENT_TYPE, mouseEvent: *const EmscriptenMouseEvent, userData: *mut c_void, ) -> EM_BOOL { let mouseEvent = &*mouseEvent; let mut callback = Box::<F>::from_raw(userData as *mut F); let result = callback( MouseEventType::from(eventType), MouseEvent::from(mouseEvent), ); mem::forget(callback); if result { EM_TRUE } else { EM_FALSE } } } pub fn set_click_callback<F>(target: Selector, use_capture: bool, callback: F) -> HtmlResult<()> where F: FnMut(MouseEventType, MouseEvent) -> bool + 'static, { set_callback(emscripten_set_click_callback, target, use_capture, callback) } pub fn set_mouse_down_callback<F>( target: Selector, use_capture: bool, callback: F, ) -> HtmlResult<()> where F: FnMut(MouseEventType, MouseEvent) -> bool + 'static, { set_callback( emscripten_set_mousedown_callback, target, use_capture, callback, ) } pub fn set_mouse_up_callback<F>(target: Selector, use_capture: bool, callback: F) -> HtmlResult<()> where F: FnMut(MouseEventType, MouseEvent) -> bool + 'static, { set_callback( emscripten_set_mouseup_callback, target, use_capture, callback, ) } pub fn set_dbl_click_callback<F>(target: Selector, use_capture: bool, callback: F) -> HtmlResult<()> where F: FnMut(MouseEventType, MouseEvent) -> bool + 'static, { set_callback( emscripten_set_dblclick_callback, target, use_capture, callback, ) } pub fn set_mouse_move_callback<F>( target: Selector, use_capture: bool, callback: F, ) -> HtmlResult<()> where F: FnMut(MouseEventType, MouseEvent) -> bool + 'static, { set_callback( emscripten_set_mousemove_callback, target, use_capture, callback, ) } pub fn set_mouse_enter_callback<F>( target: Selector, use_capture: bool, callback: F, ) -> HtmlResult<()> where F: FnMut(MouseEventType, MouseEvent) -> bool + 'static, { set_callback( emscripten_set_mouseenter_callback, target, use_capture, callback, ) } pub fn set_mouse_leave_callback<F>( target: Selector, use_capture: bool, callback: F, ) -> HtmlResult<()> where F: FnMut(MouseEventType, MouseEvent) -> bool + 'static, { set_callback( emscripten_set_mouseleave_callback, target, use_capture, callback, ) }
#![cfg_attr(feature = "unstable-testing", feature(plugin))] #![cfg_attr(feature = "unstable-testing", plugin(clippy))] extern crate k5test; extern crate gssapi; extern crate gssapi_sys; fn create_k5realm() -> k5test::K5Realm { let realm = "KRBTEST.COM".to_owned(); k5test::K5RealmBuilder::new(realm.clone()) .add_principal(format!("user@{}", realm), None) .add_principal(format!("impersonator@{}", realm), None) .build() .expect("failed to create realm") } fn import_name(username: &str, realm: &k5test::K5Realm) -> gssapi::Name { let user_principal = format!("{}@{}", username, realm.realm()); gssapi::Name::new(&user_principal, gssapi::OID::nt_user_name()).expect("Failed to import name") } fn duplicate_name(name: &gssapi::Name) -> gssapi::Name { name.clone().duplicate().expect("Failed to duplicate name") } fn create_oid_set() -> gssapi::OIDSet { gssapi::OIDSet::empty().expect("Failed to create empty OID set.") } fn illegal_operation() -> gssapi::Error { // TODO: Do a real illegal operation. gssapi::Error::new(0, 0, gssapi::OID::empty()) } fn acquire_creds(name: gssapi::Name) -> gssapi::Credentials { gssapi::Credentials::accept(name).build().expect("Failed to acquire credentials") } #[test] fn test() { let realm = create_k5realm(); // Test name creation & duplication. let user_name = import_name("user", &realm); let _impersonator_name = import_name("impersonator", &realm); duplicate_name(&user_name); // Test OID set creation. create_oid_set(); // TODO: test buffer // Test errors. let _err = illegal_operation(); // Test credentials. let _cred = acquire_creds(user_name); }