text
stringlengths 8
4.13M
|
|---|
use crate::*;
/// Sprites are conceptually both a reference to an image, and the sub region of the image
/// which represents the logical sprite.
pub trait CommonSprite<R: CommonRenderer>: Sized + Clone {
/// Construct a new sprite from an image. The image contents are copied to a texture
/// in RGBA8 format. The entire image will be used
fn new_from_image(
renderer: &R,
img: &Image,
init_args: &SpriteInitArgs,
) -> Result<Self, R::Error>;
/// Build a sprite that shares the same underlying texture but represents a different portion
/// of the texture.
///
/// # Arguments
///
/// * **source_rect** - The portion of the texture that the new sprite will render, relative to
/// the current sprite's bounds. The bounds of the output sprite will be
/// the intersection of the sprite's rect and the source_rect, so the dimensions
/// of the output sprite may not match the `source_rect` dimensions.
///
/// # Example
///
/// ```no_run
/// # use riddle::{common::Color, image::*, platform::*, renderer::*, math::*, *};
/// # fn main() -> Result<(), RiddleError> {
/// # let rdl = RiddleLib::new()?; let window = WindowBuilder::new().build(rdl.context())?;
/// let renderer = Renderer::new_from_window(&window)?;
///
/// // Load an image and create a sprite from it
/// let img = Image::new(100, 100);
/// let sprite = Sprite::new_from_image(&renderer, &img, &SpriteInitArgs::new())?;
///
/// // Take a portion of the sprite as a new sprite.
/// let subsprite = sprite.subsprite(&Rect::new(vec2(75.0, 75.0), vec2(50.0, 50.0)));
///
/// // The subsprite dimensions will be the size of the intersection between the
/// // source sprite and the new bounds.
/// assert_eq!(vec2(25.0, 25.0), subsprite.dimensions());
/// # Ok(()) }
/// ```
fn subsprite(&self, source_rect: &Rect<f32>) -> Self;
/// Get the dimensions of the sprite
///
/// # Example
///
/// ```no_run
/// # use riddle::{common::Color, image::*, platform::*, renderer::*, math::*, *};
/// # fn main() -> Result<(), RiddleError> {
/// # let rdl = RiddleLib::new()?; let window = WindowBuilder::new().build(rdl.context())?;
/// let renderer = Renderer::new_from_window(&window)?;
///
/// // Load an image and create a sprite from it
/// let img = Image::new(100, 100);
/// let sprite = Sprite::new_from_image(&renderer, &img, &SpriteInitArgs::new())?;
///
/// // The sprite dimensions will be the same of the source image
/// assert_eq!(vec2(100.0, 100.0), sprite.dimensions());
/// # Ok(()) }
/// ```
fn dimensions(&self) -> Vector2<f32>;
/// Render multiple sub regions of the sprite at once.
///
/// The regions are defined by pairs of the region of the sprite to draw in texels, and where
/// to position the region relative to the [`SpriteRenderArgs::location`].
///
/// The pivot and rotation are relative to the location arg. A change in rotation will
/// transform all rendered regions as one, not individually.
fn render_regions<Ctx: RenderContext<R> + ?Sized>(
&self,
render_ctx: &mut Ctx,
args: &SpriteRenderArgs,
parts: &[(Rect<f32>, Vector2<f32>)],
) -> Result<(), R::Error>;
/// Render the entire sprite.
fn render<Ctx: RenderContext<R> + ?Sized>(
&self,
render_ctx: &mut Ctx,
args: &SpriteRenderArgs,
) -> Result<(), R::Error> {
self.render_regions(
render_ctx,
args,
&[(
Rect::new([0.0, 0.0], self.dimensions().into()),
Vector2::new(0.0, 0.0),
)],
)
}
/// Utility function to simply render the sprite at a given location
///
/// See [`SpriteRenderArgs`] for how to render the sprite with more control.
fn render_at<Ctx: RenderContext<R> + ?Sized>(
&self,
render_ctx: &mut Ctx,
location: Vector2<f32>,
) -> Result<(), R::Error> {
self.render(
render_ctx,
&SpriteRenderArgs {
location,
..Default::default()
},
)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FilterMode {
Nearest,
Linear,
}
impl Default for FilterMode {
fn default() -> Self {
FilterMode::Nearest
}
}
#[derive(Default, Debug, Clone, PartialEq, Eq)]
pub struct SpriteInitArgs {
pub mag_filter: FilterMode,
pub min_filter: FilterMode,
}
impl SpriteInitArgs {
/// Create a new default init args.
pub fn new() -> Self {
Self {
mag_filter: Default::default(),
min_filter: Default::default(),
}
}
/// Specify the min and mag filters used when rendering the sprite
pub fn with_filter_modes(mut self, mag_filter: FilterMode, min_filter: FilterMode) -> Self {
self.mag_filter = mag_filter;
self.min_filter = min_filter;
self
}
}
#[derive(Clone, Debug)]
pub struct SpriteRenderArgs {
pub location: Vector2<f32>,
pub pivot: Vector2<f32>,
pub scale: Vector2<f32>,
pub angle: f32,
pub diffuse_color: Color<f32>,
}
impl SpriteRenderArgs {
/// New render args, with defaults, at the specified location
pub fn new<T: Into<Vector2<f32>>>(location: T) -> Self {
let mut args = Self::default();
args.at(location);
args
}
/// Set the location of the sprite, specifying where the pivot should
/// be placed.
#[inline]
pub fn at<T: Into<Vector2<f32>>>(&mut self, location: T) -> &mut Self {
self.location = location.into();
self
}
/// Set the pivot of the sprite, relative to the top left of the sprite
#[inline]
pub fn with_pivot<T: Into<Vector2<f32>>>(&mut self, pivot: T) -> &mut Self {
self.pivot = pivot.into();
self
}
/// Set the scale at which the sprite will be rendered
pub fn with_scale<T: Into<Vector2<f32>>>(&mut self, scale: T) -> &mut Self {
self.scale = scale.into();
self
}
/// Set the angle at which the sprite will be rendered, in radians.
pub fn with_angle(&mut self, angle: f32) -> &mut Self {
self.angle = angle;
self
}
/// Set the diffuse color of the sprite, which will be multiplied by the sprite
/// colors.
pub fn with_color(&mut self, color: Color<f32>) -> &mut Self {
self.diffuse_color = color;
self
}
}
impl Default for SpriteRenderArgs {
fn default() -> Self {
SpriteRenderArgs {
location: [0.0, 0.0].into(),
pivot: [0.0, 0.0].into(),
angle: 0.0,
scale: [1.0, 1.0].into(),
diffuse_color: Color::WHITE,
}
}
}
|
use std;
use bincode;
use mio_more;
#[derive(Debug)]
pub enum Error {
Io(std::io::Error),
Bincode(bincode::Error),
Timer(mio_more::timer::TimerError),
InvalidId,
}
impl From<std::io::Error> for Error {
fn from(other: std::io::Error) -> Self {
Error::Io(other)
}
}
impl From<bincode::Error> for Error {
fn from(other: bincode::Error) -> Self {
Error::Bincode(other)
}
}
impl From<mio_more::timer::TimerError> for Error {
fn from(other: mio_more::timer::TimerError) -> Self {
Error::Timer(other)
}
}
|
/*
* 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
*/
/// FormulaAndFunctionEventsDataSource : Data source for event platform-based queries.
/// Data source for event platform-based queries.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
pub enum FormulaAndFunctionEventsDataSource {
#[serde(rename = "logs")]
LOGS,
#[serde(rename = "spans")]
SPANS,
#[serde(rename = "network")]
NETWORK,
#[serde(rename = "rum")]
RUM,
#[serde(rename = "security_signals")]
SECURITY_SIGNALS,
#[serde(rename = "profiles")]
PROFILES,
}
impl ToString for FormulaAndFunctionEventsDataSource {
fn to_string(&self) -> String {
match self {
Self::LOGS => String::from("logs"),
Self::SPANS => String::from("spans"),
Self::NETWORK => String::from("network"),
Self::RUM => String::from("rum"),
Self::SECURITY_SIGNALS => String::from("security_signals"),
Self::PROFILES => String::from("profiles"),
}
}
}
|
use boxfnonce::BoxFnOnce;
use entity_template::EntityTemplate;
use std::any::Any;
use std::collections::HashMap;
use worker::schema::{Command, CommandRequestInterface, CommandResponseInterface, Component,
GeneratedSchema};
use worker::{CommandStatus, ComponentId, Connection, EntityId, RequestId};
use world::World;
type Callback<S, T> = BoxFnOnce<'static, (*mut World<S>, T, CommandStatus, String)>;
type CommandHandler<S> = Box<FnMut(&mut World<S>, &mut Connection, RequestId, EntityId, Box<Any>)>;
pub struct Commands<S: GeneratedSchema> {
entity_command_handlers: HashMap<(ComponentId, u32), CommandHandler<S>>,
entity_command_callbacks: HashMap<RequestId, Callback<S, (EntityId, Option<Box<Any>>)>>,
create_entity_callbacks: HashMap<RequestId, Callback<S, EntityId>>,
delete_entity_callbacks: HashMap<RequestId, Callback<S, EntityId>>,
}
impl<S: 'static + GeneratedSchema> Commands<S> {
pub fn new() -> Commands<S> {
Commands {
entity_command_handlers: HashMap::new(),
entity_command_callbacks: HashMap::new(),
create_entity_callbacks: HashMap::new(),
delete_entity_callbacks: HashMap::new(),
}
}
pub fn register_handler<C: 'static + Command<S>, H: 'static>(&mut self, handler: H)
where
H: Fn(&mut World<S>, EntityId, &C::Request) -> C::Response,
{
let id = (C::Component::component_id(), C::command_index());
if self.entity_command_handlers.contains_key(&id) {
panic!("Command handler for component {} and command with index {} has already been registered.", id.0, id.1);
}
self.entity_command_handlers.insert(
id,
Box::new(move |world, connection, request_id, entity_id, request| {
let request = request.downcast_ref::<C::Request>().unwrap();
let response = handler(world, entity_id, request);
let reponse = response.serialise_response();
connection.send_command_response(request_id, C::Component::component_id(), reponse);
}),
);
}
pub fn on_command_request(
&mut self,
world: &mut World<S>,
connection: &mut Connection,
request_id: RequestId,
entity_id: EntityId,
component_id: ComponentId,
command_id: u32,
request: Box<Any>,
) {
if let Some(handler) = self.entity_command_handlers
.get_mut(&(component_id, command_id))
{
handler(world, connection, request_id, entity_id, request);
}
}
pub fn send_command<C: 'static + Command<S>, A: 'static, F: 'static>(
&mut self,
connection: &mut Connection,
entity_id: EntityId,
request: C::Request,
success: A,
failure: F,
) where
A: FnOnce(&mut World<S>, EntityId, &C::Response),
F: FnOnce(&mut World<S>, CommandStatus, String),
{
let request_ptr = request.serialise_request();
let request_id = connection.send_command_request(
entity_id,
C::Component::component_id(),
request_ptr,
C::command_index(),
None,
);
Commands::<S>::register_callback(
&mut self.entity_command_callbacks,
request_id,
|world, (entity_id, response)| {
let response = response
.as_ref()
.unwrap()
.downcast_ref::<C::Response>()
.unwrap();
success(world, entity_id, response);
},
failure,
)
}
pub fn on_command_response(
&mut self,
world: &mut World<S>,
request_id: RequestId,
entity_id: EntityId,
response: Option<Box<Any>>,
success_code: CommandStatus,
message: &str,
) {
if let Some(callback) = self.entity_command_callbacks.remove(&request_id) {
callback.call(
world,
(entity_id, response),
success_code,
message.to_string(),
);
}
}
pub fn create_entity<A: 'static, F: 'static>(
&mut self,
connection: &mut Connection,
mut entity_template: EntityTemplate,
success: A,
failure: F,
) where
A: FnOnce(&mut World<S>, EntityId),
F: FnOnce(&mut World<S>, CommandStatus, String),
{
let (entity_acl_id, entity_acl_data) =
S::serialise_entity_acl(entity_template.read_access, entity_template.write_access);
entity_template.data.insert(entity_acl_id, entity_acl_data);
let request_id = connection.send_create_entity_request(
entity_template.data,
entity_template.entity_id,
None,
);
Commands::<S>::register_callback(
&mut self.create_entity_callbacks,
request_id,
|world, entity_id| {
success(world, entity_id);
},
failure,
)
}
pub fn on_create_entity_response(
&mut self,
world: &mut World<S>,
request_id: RequestId,
entity_id: EntityId,
success_code: CommandStatus,
message: &str,
) {
for callback in self.create_entity_callbacks.remove(&request_id) {
callback.call(world, entity_id, success_code, message.to_string());
}
}
pub fn delete_entity<A: 'static, F: 'static>(
&mut self,
connection: &mut Connection,
entity_id: EntityId,
success: A,
failure: F,
) where
A: FnOnce(&mut World<S>, EntityId),
F: FnOnce(&mut World<S>, CommandStatus, String),
{
let request_id = connection.send_delete_entity_request(entity_id, None);
Commands::<S>::register_callback(
&mut self.delete_entity_callbacks,
request_id,
|world, entity_id| {
success(world, entity_id);
},
failure,
)
}
pub fn on_delete_entity_response(
&mut self,
world: &mut World<S>,
request_id: RequestId,
entity_id: EntityId,
success_code: CommandStatus,
message: &str,
) {
for callback in self.delete_entity_callbacks.remove(&request_id) {
callback.call(world, entity_id, success_code, message.to_string());
}
}
fn register_callback<T: 'static, A, F>(
callbacks: &mut HashMap<RequestId, Callback<S, T>>,
request_id: RequestId,
success: A,
failure: F,
) where
A: 'static + FnOnce(&mut World<S>, T),
F: 'static + FnOnce(&mut World<S>, CommandStatus, String),
{
callbacks.insert(
request_id,
BoxFnOnce::from(move |world_ptr: *mut World<S>, object, status, message| {
let world = unsafe { &mut (*world_ptr) };
if status == CommandStatus::Success {
success(world, object);
} else {
failure(world, status, message);
}
}),
);
}
}
|
#![allow(clippy::identity_op)]
use crate::encoder::JpegColorType;
/// Conversion from RGB to YCbCr
#[inline]
pub fn rgb_to_ycbcr(r: u8, g: u8, b: u8) -> (u8, u8, u8) {
// To avoid floating point math this scales everything by 2^16 which gives
// a precision of approx 4 digits.
//
// Non scaled conversion:
// Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
// Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + 128
// Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + 128
let r = r as i32;
let g = g as i32;
let b = b as i32;
let y = 19595 * r + 38470 * g + 7471 * b;
let cb = -11059 * r - 21709 * g + 32768 * b + (128 << 16);
let cr = 32768 * r - 27439 * g - 5329 * b + (128 << 16);
let y = (y + (1 << 15)) >> 16;
let cb = (cb + (1 << 15)) >> 16;
let cr = (cr + (1 << 15)) >> 16;
(y as u8, cb as u8, cr as u8)
}
/// Conversion from CMYK to YCCK (YCbCrK)
#[inline]
pub fn cmyk_to_ycck(c: u8, m: u8, y: u8, k: u8) -> (u8, u8, u8, u8) {
let (y, cb, cr) = rgb_to_ycbcr(c, m, y);
(y, cb, cr, 255 - k)
}
/// # Buffer used as input value for image encoding
///
/// Image encoding with [Encoder::encode_image](crate::Encoder::encode_image) needs an ImageBuffer
/// as input for the image data. For convenience the [Encoder::encode](crate::Encoder::encode)
/// function contains implementaions for common byte based pixel formats.
/// Users that needs other pixel formats or don't have the data available as byte slices
/// can create their own buffer implementations.
///
/// ## Example: ImageBuffer implementation for RgbImage from the `image` crate
/// ```no_run
/// use image::RgbImage;
/// use jpeg_encoder::{ImageBuffer, JpegColorType, rgb_to_ycbcr};
///
/// pub struct RgbImageBuffer {
/// image: RgbImage,
/// }
///
/// impl ImageBuffer for RgbImageBuffer {
/// fn get_jpeg_color_type(&self) -> JpegColorType {
/// // Rgb images are encoded as YCbCr in JFIF files
/// JpegColorType::Ycbcr
/// }
///
/// fn width(&self) -> u16 {
/// self.image.width() as u16
/// }
///
/// fn height(&self) -> u16 {
/// self.image.height() as u16
/// }
///
/// fn fill_buffers(&self, x: u16, y: u16, buffers: &mut [Vec<u8>; 4]){
/// let pixel = self.image.get_pixel(x as u32 ,y as u32);
///
/// let (y,cb,cr) = rgb_to_ycbcr(pixel[0], pixel[1], pixel[2]);
///
/// // For YCbCr the 4th buffer is not used
/// buffers[0].push(y);
/// buffers[1].push(cb);
/// buffers[2].push(cr);
/// }
/// }
///
/// ```
pub trait ImageBuffer {
/// The color type used in the image encoding
fn get_jpeg_color_type(&self) -> JpegColorType;
/// Width of the image
fn width(&self) -> u16;
/// Height of the image
fn height(&self) -> u16;
/// Add color values for the position to color component buffers
fn fill_buffers(&self, x: u16, y: u16, buffers: &mut [Vec<u8>; 4]);
}
pub(crate) struct GrayImage<'a>(pub &'a [u8], pub u16, pub u16);
impl<'a> ImageBuffer for GrayImage<'a> {
fn get_jpeg_color_type(&self) -> JpegColorType {
JpegColorType::Luma
}
fn width(&self) -> u16 {
self.1
}
fn height(&self) -> u16 {
self.2
}
fn fill_buffers(&self, x: u16, y: u16, buffers: &mut [Vec<u8>; 4]) {
let offset = usize::from(y) * usize::from(self.1) + usize::from(x);
buffers[0].push(self.0[offset + 0]);
}
}
macro_rules! ycbcr_image {
($name:ident, $num_colors:expr, $o1:expr, $o2:expr, $o3:expr) => {
pub(crate) struct $name<'a>(pub &'a [u8], pub u16, pub u16);
impl<'a> ImageBuffer for $name<'a> {
fn get_jpeg_color_type(&self) -> JpegColorType {
JpegColorType::Ycbcr
}
fn width(&self) -> u16 {
self.1
}
fn height(&self) -> u16 {
self.2
}
#[inline(always)]
fn fill_buffers(&self, x: u16, y: u16, buffers: &mut [Vec<u8>; 4]) {
let offset = (usize::from(y) * usize::from(self.1) + usize::from(x)) * $num_colors;
let (y, cb, cr) = rgb_to_ycbcr(self.0[offset + $o1], self.0[offset + $o2], self.0[offset + $o3]);
buffers[0].push(y);
buffers[1].push(cb);
buffers[2].push(cr);
}
}
}
}
ycbcr_image!(RgbImage, 3, 0, 1, 2);
ycbcr_image!(RgbaImage, 4, 0, 1, 2);
ycbcr_image!(BgrImage, 3, 2, 1, 0);
ycbcr_image!(BgraImage, 4, 2, 1, 0);
pub(crate) struct YCbCrImage<'a>(pub &'a [u8], pub u16, pub u16);
impl<'a> ImageBuffer for YCbCrImage<'a> {
fn get_jpeg_color_type(&self) -> JpegColorType {
JpegColorType::Ycbcr
}
fn width(&self) -> u16 {
self.1
}
fn height(&self) -> u16 {
self.2
}
fn fill_buffers(&self, x: u16, y: u16, buffers: &mut [Vec<u8>; 4]) {
let offset = (usize::from(y) * usize::from(self.1) + usize::from(x)) * 3;
buffers[0].push(self.0[offset + 0]);
buffers[1].push(self.0[offset + 1]);
buffers[2].push(self.0[offset + 2]);
}
}
pub(crate) struct CmykImage<'a>(pub &'a [u8], pub u16, pub u16);
impl<'a> ImageBuffer for CmykImage<'a> {
fn get_jpeg_color_type(&self) -> JpegColorType {
JpegColorType::Cmyk
}
fn width(&self) -> u16 {
self.1
}
fn height(&self) -> u16 {
self.2
}
fn fill_buffers(&self, x: u16, y: u16, buffers: &mut [Vec<u8>; 4]) {
let offset = (usize::from(y) * usize::from(self.1) + usize::from(x)) * 4;
buffers[0].push(255 - self.0[offset + 0]);
buffers[1].push(255 - self.0[offset + 1]);
buffers[2].push(255 - self.0[offset + 2]);
buffers[3].push(255 - self.0[offset + 3]);
}
}
pub(crate) struct CmykAsYcckImage<'a>(pub &'a [u8], pub u16, pub u16);
impl<'a> ImageBuffer for CmykAsYcckImage<'a> {
fn get_jpeg_color_type(&self) -> JpegColorType {
JpegColorType::Ycck
}
fn width(&self) -> u16 {
self.1
}
fn height(&self) -> u16 {
self.2
}
fn fill_buffers(&self, x: u16, y: u16, buffers: &mut [Vec<u8>; 4]) {
let offset = (usize::from(y) * usize::from(self.1) + usize::from(x)) * 4;
let (y, cb, cr, k) = cmyk_to_ycck(
self.0[offset + 0],
self.0[offset + 1],
self.0[offset + 2],
self.0[offset + 3]);
buffers[0].push(y);
buffers[1].push(cb);
buffers[2].push(cr);
buffers[3].push(k);
}
}
pub(crate) struct YcckImage<'a>(pub &'a [u8], pub u16, pub u16);
impl<'a> ImageBuffer for YcckImage<'a> {
fn get_jpeg_color_type(&self) -> JpegColorType {
JpegColorType::Ycck
}
fn width(&self) -> u16 {
self.1
}
fn height(&self) -> u16 {
self.2
}
fn fill_buffers(&self, x: u16, y: u16, buffers: &mut [Vec<u8>; 4]) {
let offset = (usize::from(y) * usize::from(self.1) + usize::from(x)) * 4;
buffers[0].push(self.0[offset + 0]);
buffers[1].push(self.0[offset + 1]);
buffers[2].push(self.0[offset + 2]);
buffers[3].push(self.0[offset + 3]);
}
}
#[cfg(test)]
mod tests {
use crate::rgb_to_ycbcr;
fn assert_rgb_to_ycbcr(rgb: [u8; 3], ycbcr: [u8; 3]) {
let (y, cb, cr) = rgb_to_ycbcr(rgb[0], rgb[1], rgb[2]);
assert_eq!([y, cb, cr], ycbcr);
}
#[test]
fn test_rgb_to_ycbcr() {
// Values taken from libjpeg for a common image
assert_rgb_to_ycbcr([59, 109, 6], [82, 85, 111]);
assert_rgb_to_ycbcr([29, 60, 11], [45, 109, 116]);
assert_rgb_to_ycbcr([57, 114, 26], [87, 94, 107]);
assert_rgb_to_ycbcr([30, 60, 6], [45, 106, 117]);
assert_rgb_to_ycbcr([41, 75, 11], [58, 102, 116]);
assert_rgb_to_ycbcr([145, 184, 108], [164, 97, 115]);
assert_rgb_to_ycbcr([33, 85, 7], [61, 98, 108]);
assert_rgb_to_ycbcr([61, 90, 40], [76, 108, 118]);
assert_rgb_to_ycbcr([75, 127, 45], [102, 96, 109]);
assert_rgb_to_ycbcr([30, 56, 14], [43, 111, 118]);
assert_rgb_to_ycbcr([106, 142, 81], [124, 104, 115]);
assert_rgb_to_ycbcr([35, 59, 11], [46, 108, 120]);
assert_rgb_to_ycbcr([170, 203, 123], [184, 94, 118]);
assert_rgb_to_ycbcr([45, 87, 16], [66, 100, 113]);
assert_rgb_to_ycbcr([59, 109, 21], [84, 92, 110]);
assert_rgb_to_ycbcr([100, 167, 36], [132, 74, 105]);
assert_rgb_to_ycbcr([17, 53, 5], [37, 110, 114]);
assert_rgb_to_ycbcr([226, 244, 220], [236, 119, 121]);
assert_rgb_to_ycbcr([192, 214, 120], [197, 85, 125]);
assert_rgb_to_ycbcr([63, 107, 22], [84, 93, 113]);
assert_rgb_to_ycbcr([44, 78, 19], [61, 104, 116]);
assert_rgb_to_ycbcr([72, 106, 54], [90, 108, 115]);
assert_rgb_to_ycbcr([99, 123, 73], [110, 107, 120]);
assert_rgb_to_ycbcr([188, 216, 148], [200, 99, 120]);
assert_rgb_to_ycbcr([19, 46, 7], [33, 113, 118]);
assert_rgb_to_ycbcr([56, 95, 40], [77, 107, 113]);
assert_rgb_to_ycbcr([81, 120, 56], [101, 103, 114]);
assert_rgb_to_ycbcr([9, 30, 0], [20, 117, 120]);
assert_rgb_to_ycbcr([90, 118, 46], [101, 97, 120]);
assert_rgb_to_ycbcr([24, 52, 0], [38, 107, 118]);
assert_rgb_to_ycbcr([32, 69, 9], [51, 104, 114]);
assert_rgb_to_ycbcr([74, 134, 33], [105, 88, 106]);
assert_rgb_to_ycbcr([37, 74, 7], [55, 101, 115]);
assert_rgb_to_ycbcr([69, 119, 31], [94, 92, 110]);
assert_rgb_to_ycbcr([63, 112, 21], [87, 91, 111]);
assert_rgb_to_ycbcr([90, 148, 17], [116, 72, 110]);
assert_rgb_to_ycbcr([50, 97, 30], [75, 102, 110]);
assert_rgb_to_ycbcr([99, 129, 72], [114, 105, 118]);
assert_rgb_to_ycbcr([161, 196, 57], [170, 64, 122]);
assert_rgb_to_ycbcr([10, 26, 1], [18, 118, 122]);
assert_rgb_to_ycbcr([87, 128, 68], [109, 105, 112]);
assert_rgb_to_ycbcr([111, 155, 73], [132, 94, 113]);
assert_rgb_to_ycbcr([33, 75, 11], [55, 103, 112]);
assert_rgb_to_ycbcr([70, 122, 51], [98, 101, 108]);
assert_rgb_to_ycbcr([22, 74, 3], [50, 101, 108]);
assert_rgb_to_ycbcr([88, 142, 45], [115, 89, 109]);
assert_rgb_to_ycbcr([66, 107, 40], [87, 101, 113]);
assert_rgb_to_ycbcr([18, 45, 0], [32, 110, 118]);
assert_rgb_to_ycbcr([163, 186, 88], [168, 83, 124]);
assert_rgb_to_ycbcr([47, 104, 4], [76, 88, 108]);
assert_rgb_to_ycbcr([147, 211, 114], [181, 90, 104]);
assert_rgb_to_ycbcr([42, 77, 18], [60, 104, 115]);
assert_rgb_to_ycbcr([37, 72, 6], [54, 101, 116]);
assert_rgb_to_ycbcr([84, 140, 55], [114, 95, 107]);
assert_rgb_to_ycbcr([46, 98, 25], [74, 100, 108]);
assert_rgb_to_ycbcr([48, 97, 20], [74, 98, 110]);
assert_rgb_to_ycbcr([189, 224, 156], [206, 100, 116]);
assert_rgb_to_ycbcr([36, 83, 0], [59, 94, 111]);
assert_rgb_to_ycbcr([159, 186, 114], [170, 97, 120]);
assert_rgb_to_ycbcr([75, 118, 46], [97, 99, 112]);
assert_rgb_to_ycbcr([193, 233, 158], [212, 97, 114]);
assert_rgb_to_ycbcr([76, 116, 48], [96, 101, 114]);
assert_rgb_to_ycbcr([108, 157, 79], [133, 97, 110]);
assert_rgb_to_ycbcr([180, 208, 155], [194, 106, 118]);
assert_rgb_to_ycbcr([74, 126, 53], [102, 100, 108]);
assert_rgb_to_ycbcr([72, 123, 46], [99, 98, 109]);
assert_rgb_to_ycbcr([71, 123, 34], [97, 92, 109]);
assert_rgb_to_ycbcr([130, 184, 72], [155, 81, 110]);
assert_rgb_to_ycbcr([30, 61, 17], [47, 111, 116]);
assert_rgb_to_ycbcr([27, 71, 0], [50, 100, 112]);
assert_rgb_to_ycbcr([45, 73, 24], [59, 108, 118]);
assert_rgb_to_ycbcr([139, 175, 93], [155, 93, 117]);
assert_rgb_to_ycbcr([11, 38, 0], [26, 114, 118]);
assert_rgb_to_ycbcr([34, 87, 15], [63, 101, 107]);
assert_rgb_to_ycbcr([43, 76, 35], [61, 113, 115]);
assert_rgb_to_ycbcr([18, 35, 7], [27, 117, 122]);
assert_rgb_to_ycbcr([69, 97, 48], [83, 108, 118]);
assert_rgb_to_ycbcr([139, 176, 50], [151, 71, 120]);
assert_rgb_to_ycbcr([21, 51, 7], [37, 111, 117]);
assert_rgb_to_ycbcr([209, 249, 189], [230, 105, 113]);
assert_rgb_to_ycbcr([32, 66, 14], [50, 108, 115]);
assert_rgb_to_ycbcr([100, 143, 67], [121, 97, 113]);
assert_rgb_to_ycbcr([40, 96, 14], [70, 96, 107]);
assert_rgb_to_ycbcr([88, 130, 64], [110, 102, 112]);
assert_rgb_to_ycbcr([52, 112, 14], [83, 89, 106]);
assert_rgb_to_ycbcr([49, 72, 25], [60, 108, 120]);
assert_rgb_to_ycbcr([144, 193, 75], [165, 77, 113]);
assert_rgb_to_ycbcr([49, 94, 1], [70, 89, 113]);
}
}
|
use crate::types::buffer::ebo::EBO;
use crate::types::buffer::vao::VAO;
use crate::types::buffer::vbo::VBO;
use crate::types::data::data_layout::DataLayout;
use gl::types::*;
pub type VAOBuilder<'a> = VertexArrayObjectBuilder<'a>;
pub struct VertexArrayObjectBuilder<'a> {
pub vbo: VBO,
pub vbo_data: &'a [f32],
pub vbo_draw_type: GLenum,
pub data_layout: DataLayout,
pub ebo: Option<EBO>,
pub ebo_data: Option<&'a [u32]>,
pub ebo_draw_type: Option<GLenum>,
}
impl<'a> VAOBuilder<'a> {
pub fn from_vbo(
vbo: VBO,
vbo_data: &'a [f32],
vbo_draw_type: GLenum,
data_layout: DataLayout,
) -> Self {
VAOBuilder {
vbo,
vbo_data,
vbo_draw_type,
data_layout,
ebo: None,
ebo_data: None,
ebo_draw_type: None,
}
}
pub fn add_ebo(mut self, ebo: EBO, ebo_data: &'a [u32], ebo_draw_type: GLenum) -> Self {
self.ebo = Some(ebo);
self.ebo_data = Some(ebo_data);
self.ebo_draw_type = Some(ebo_draw_type);
self
}
pub fn compile(self) -> (VAO, VBO, Option<EBO>) {
let vao = VAO::default();
vao.bind();
self.vbo.bind();
self.vbo.buffer_data(self.vbo_data, self.vbo_draw_type);
if self.ebo.is_some() {
let ebo = self.ebo.as_ref().unwrap();
ebo.bind();
ebo.buffer_data(self.ebo_data.unwrap(), self.ebo_draw_type.unwrap());
}
self.data_layout.vertex_attrib_pointer();
vao.unbind();
self.vbo.unbind();
if self.ebo.is_some() {
self.ebo.as_ref().unwrap().unbind();
}
(vao, self.vbo, self.ebo)
}
}
|
use std::fs;
fn solve(input: &Vec<&str>, right: usize, down: usize) -> usize {
let mut count: usize = 0;
let mut x: usize = 0;
for a in (0..input.len()).step_by(down) {
if input[a].chars().nth(x).unwrap() == '#' {
count += 1;
}
for _ in 0..right {
if x == input[a].len()-1 {x = 0;}
else {x += 1;}
}
}
count
}
fn main() {
let inputfile = fs::read_to_string("input.txt").
expect("File could not be read.");
let input: Vec<&str> = inputfile.lines().collect();
let solution1 = solve(&input, 3, 1);
println!("Part 1: {}", solution1);
let solution2 =
solve(&input, 1, 1) *
solve(&input, 3, 1) *
solve(&input, 5, 1) *
solve(&input, 7, 1) *
solve(&input, 1, 2);
println!("Part 2: {}", solution2);
}
|
//!
//! Rust Firebird Client
//!
//! Transaction struct tests
//!
mk_tests_default! {
use crate::{FbError, Connection, Transaction};
use rsfbclient_core::FirebirdClient;
macro_rules! recreate_tbl_fmtstring{
() => {"recreate table {} ( id INT NOT NULL PRIMARY KEY, description VARCHAR(20) );"};
}
macro_rules! drop_tbl_fmtstring{
() => {"drop table {};"};
}
macro_rules! insert_stmt_fmtstring{
() => {"insert into {} (id, description) values (543210, 'testing');"};
}
fn setup<C: FirebirdClient>( conn: &mut Connection<C>, table_name: &str ) -> Result<(), FbError>{
let mut setup_transaction = Transaction::new(conn)?;
setup_transaction.execute_immediate( format!(recreate_tbl_fmtstring!(), table_name).as_str() )?;
setup_transaction.commit()
}
fn teardown<C: FirebirdClient>( conn: Connection<C>, table_name: &str ) -> Result<(), FbError> {
let mut conn = conn;
let mut setup_transaction = Transaction::new(&mut conn)?;
setup_transaction.execute_immediate( format!(drop_tbl_fmtstring!(), table_name ).as_str() )?;
setup_transaction.commit()?;
conn.close()
}
#[test]
fn recreate_insert_drop_with_commit() -> Result<(), FbError> {
const TABLE_NAME: &str = "RSFBCLIENT_TEST_TRANS0";
let mut conn = cbuilder().connect()?;
setup(&mut conn, TABLE_NAME)?;
let mut transaction = Transaction::new(&mut conn)?;
let _insert_result = transaction.execute_immediate( format!(insert_stmt_fmtstring!(), TABLE_NAME).as_str() );
let commit_result = transaction.commit();
teardown(conn, TABLE_NAME)?;
commit_result
}
#[test]
fn recreate_insert_drop_with_commit_retaining() -> Result<(), FbError> {
const TABLE_NAME: &str = "RSFBCLIENT_TEST_TRANS1";
let mut conn = cbuilder().connect()?;
setup(&mut conn, TABLE_NAME)?;
let mut transaction = Transaction::new(&mut conn)?;
let _insert_result = transaction.execute_immediate( format!(insert_stmt_fmtstring!(), TABLE_NAME).as_str() );
let commit_result = transaction.commit_retaining();
drop(transaction);
teardown(conn, TABLE_NAME)?;
commit_result
}
#[test]
fn recreate_insert_drop_with_rollback() -> Result<(), FbError> {
const TABLE_NAME: &str = "RSFBCLIENT_TEST_TRANS2";
let mut conn = cbuilder().connect()?;
setup(&mut conn, TABLE_NAME)?;
let mut transaction = Transaction::new(&mut conn)?;
let _insert_result = transaction.execute_immediate( format!(insert_stmt_fmtstring!(), TABLE_NAME).as_str() );
let rollback_result = transaction.rollback();
teardown(conn, TABLE_NAME)?;
rollback_result
}
#[test]
fn recreate_insert_drop_with_rollback_retaining() -> Result<(), FbError> {
const TABLE_NAME: &str = "RSFBCLIENT_TEST_TRANS3";
let mut conn = cbuilder().connect()?;
setup(&mut conn, TABLE_NAME)?;
let mut transaction = Transaction::new(&mut conn)?;
let _insert_result = transaction.execute_immediate( format!(insert_stmt_fmtstring!(), TABLE_NAME).as_str() );
let rollback_result = transaction.rollback_retaining();
drop(transaction);
teardown(conn, TABLE_NAME)?;
rollback_result
}
}
|
pub struct Player {}
impl Player {
pub fn new() -> Player {
Player {}
}
pub fn version(&self) -> String {
String::from("0.1.0")
}
}
|
use error::Err;
/// Exponential Moving Average
/// Formula :
pub fn ema(data: &[f64], period: usize) -> Result<Vec<f64>, Err> {
if period > data.len() {
return Err(Err::NotEnoughtData);
}
let mut ema = Vec::new();
let mut j = 1;
// get period sma first and calculate the next period period ema
let sma = (data[0..period]).iter().sum::<f64>() / period as f64;
let multiplier: f64 = 2.0 / (1.0 + period as f64);
ema.push(sma);
// EMA(current) = ( (Price(current) - EMA(prev) ) x Multiplier) + EMA(prev)
ema.push(((data[period] - sma) * multiplier) + sma);
// now calculate the rest of the values
for i in &data[period + 1..data.len()] {
let tmp = ((*i - ema[j]) * multiplier) + ema[j];
j = j + 1;
ema.push(tmp);
}
Ok(ema)
}
|
use crate::{
document::Document,
schema::{self, Collection, CollectionName, InvalidNameError, Name, Schematic, View},
Error,
};
/// A database stored in `BonsaiDb`.
#[derive(Debug)]
pub struct Database;
impl Collection for Database {
fn collection_name() -> Result<CollectionName, InvalidNameError> {
CollectionName::new("bonsaidb", "databases")
}
fn define_views(schema: &mut Schematic) -> Result<(), Error> {
schema.define_view(ByName)
}
}
#[derive(Debug)]
pub struct ByName;
impl View for ByName {
type Collection = Database;
type Key = String;
type Value = schema::SchemaName;
fn unique(&self) -> bool {
true
}
fn version(&self) -> u64 {
1
}
fn name(&self) -> Result<Name, InvalidNameError> {
Name::new("by-name")
}
fn map(&self, document: &Document<'_>) -> schema::MapResult<Self::Key, Self::Value> {
let database = document.contents::<crate::connection::Database>()?;
Ok(Some(document.emit_key_and_value(
database.name.to_ascii_lowercase(),
database.schema,
)))
}
}
|
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::prelude::*;
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen(start)]
pub fn wasm_main() {
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
main();
}
use instant;
#[cfg(target_arch = "android")]
use ndk_glue;
use std::iter;
#[repr(C)]
#[derive(Debug, Clone, Copy)]
struct PushConstants {
color: [f32; 4],
pos: [f32; 2],
scale: [f32; 2],
}
#[cfg_attr(target_os = "android", ndk_glue::main(backtrace = "on"))]
pub fn main() {
#[cfg(target_arch = "wasm32")]
console_log::init_with_level(log::Level::Debug).unwrap();
#[cfg(not(target_arch = "wasm32"))]
env_logger::init();
#[allow(unused_imports)]
use gfx_hal::{
adapter::{Adapter, MemoryType},
buffer, command,
format::{self as f, AsFormat},
image as i, memory as m, pass, pool,
prelude::*,
pso,
queue::QueueGroup,
window, Backend,
};
use std::mem::ManuallyDrop;
const APP_NAME: &'static str = "Part 1: Drawing a triangle";
const WINDOW_SIZE: [u32; 2] = [512, 512];
let event_loop = winit::event_loop::EventLoop::new();
let (logical_window_size, physical_window_size) = {
use winit::dpi::{LogicalSize, PhysicalSize};
let dpi = event_loop
.primary_monitor()
.expect("No primary monitor")
.scale_factor();
let logical: LogicalSize<u32> = WINDOW_SIZE.into();
let physical: PhysicalSize<u32> = logical.to_physical(dpi);
(logical, physical)
};
let mut surface_extend = window::Extent2D {
width: physical_window_size.width,
height: physical_window_size.height,
};
let window = winit::window::WindowBuilder::new()
.with_title(APP_NAME)
.with_inner_size(logical_window_size)
.build(&event_loop)
.expect("Failed to create window");
#[cfg(target_arch = "wasm32")]
{
#[allow(unused_imports)]
use web_sys::{WebGlProgram, WebGlRenderingContext, WebGlShader, Window};
web_sys::window()
.unwrap()
.document()
.unwrap()
.body()
.unwrap()
.append_child(&winit::platform::web::WindowExtWebSys::canvas(&window))
.unwrap();
web_sys::console::log_1(&"Hello using web-sys".into());
}
let (instance, surface, adapter) = {
let instance = backend::Instance::create(APP_NAME, 1).expect("Backend not supported");
let surface = unsafe {
instance
.create_surface(&window)
.expect("Failed to create surface for window")
};
let adapter = instance.enumerate_adapters().remove(0);
for adapter in &instance.enumerate_adapters() {
println!("{:?}", adapter.info);
}
(instance, surface, adapter)
};
let (device, mut queue_group) = {
let queue_family = adapter
.queue_families
.iter()
.find(|family| {
surface.supports_queue_family(family) && family.queue_type().supports_graphics()
})
.expect("No compatible queue family found");
let mut gpu = unsafe {
adapter
.physical_device
.open(&[(queue_family, &[1.0])], gfx_hal::Features::empty())
.expect("Failed to open device")
};
(gpu.device, gpu.queue_groups.pop().unwrap())
};
let (command_pool, mut command_buffer) = unsafe {
use gfx_hal::command::Level;
use gfx_hal::pool::CommandPoolCreateFlags;
let mut command_pool = device
.create_command_pool(queue_group.family, CommandPoolCreateFlags::empty())
.expect("Out of memory");
let command_buffer = command_pool.allocate_one(Level::Primary);
(command_pool, command_buffer)
};
// Render passes
let surface_color_format = {
use gfx_hal::format::{ChannelType, Format};
let supported_formats = surface
.supported_formats(&adapter.physical_device)
.unwrap_or(vec![]);
let default_format = *supported_formats.get(0).unwrap_or(&Format::Rgba8Srgb);
supported_formats
.into_iter()
.find(|format| format.base_format().1 == ChannelType::Srgb)
.unwrap_or(default_format)
};
let render_pass = {
use gfx_hal::image::Layout;
use gfx_hal::pass::{
Attachment, AttachmentLoadOp, AttachmentOps, AttachmentStoreOp, SubpassDesc,
};
let color_attachment = Attachment {
format: Some(surface_color_format),
samples: 1,
ops: AttachmentOps::new(AttachmentLoadOp::Clear, AttachmentStoreOp::Store),
stencil_ops: AttachmentOps::DONT_CARE,
layouts: Layout::Undefined..Layout::Present,
};
let subpass = SubpassDesc {
colors: &[(0, Layout::ColorAttachmentOptimal)],
depth_stencil: None,
inputs: &[],
resolves: &[],
preserves: &[],
};
unsafe {
device
.create_render_pass(
iter::once(color_attachment),
iter::once(subpass),
iter::empty(),
)
.expect("Out of memory")
}
};
let pipeline_layout = unsafe {
use gfx_hal::pso::ShaderStageFlags;
let push_constant_bytes = std::mem::size_of::<PushConstants>() as u32;
device
.create_pipeline_layout(
iter::empty(),
iter::once((ShaderStageFlags::VERTEX, 0..push_constant_bytes)),
)
.expect("Out of memory")
};
let vertex_shader = include_bytes!("shaders/part-2.vert.spv");
let fragment_shader = include_bytes!("shaders/part-2.frag.spv");
//Create a pipeline with the given layout and shadaers
unsafe fn make_pipeline<B: gfx_hal::Backend>(
device: &B::Device,
render_pass: &B::RenderPass,
pipeline_layout: &B::PipelineLayout,
vertex_shader: &[u8],
fragment_shader: &[u8],
) -> B::GraphicsPipeline {
use gfx_hal::pass::Subpass;
use gfx_hal::pso::{
BlendState, ColorBlendDesc, ColorMask, EntryPoint, Face, GraphicsPipelineDesc,
InputAssemblerDesc, Primitive, PrimitiveAssemblerDesc, Rasterizer, Specialization,
};
let spirv: Vec<u32> = auxil::read_spirv(std::io::Cursor::new(vertex_shader)).unwrap();
let vertex_shader_module = device
.create_shader_module(&spirv)
.expect("Failed to create vertex shader module");
let spirv: Vec<u32> = auxil::read_spirv(std::io::Cursor::new(fragment_shader)).unwrap();
let fragment_shader_module = device
.create_shader_module(&spirv)
.expect("Failed to create fragment shader module");
let (vs_entry, fs_entry) = (
EntryPoint::<B> {
entry: "main",
module: &vertex_shader_module,
specialization: Specialization::default(),
},
EntryPoint::<B> {
entry: "main",
module: &fragment_shader_module,
specialization: Specialization::default(),
},
);
let primitive_assembler = PrimitiveAssemblerDesc::Vertex {
buffers: &[],
attributes: &[],
input_assembler: InputAssemblerDesc::new(Primitive::TriangleList),
vertex: vs_entry,
tessellation: None,
geometry: None,
};
let mut pipeline_desc = GraphicsPipelineDesc::new(
primitive_assembler,
Rasterizer {
cull_face: Face::BACK,
..Rasterizer::FILL
},
Some(fs_entry),
pipeline_layout,
Subpass {
index: 0,
main_pass: render_pass,
},
);
pipeline_desc.blender.targets.push(ColorBlendDesc {
mask: ColorMask::ALL,
blend: Some(BlendState::ALPHA),
});
let pipeline = device
.create_graphics_pipeline(&pipeline_desc, None)
.expect("Failed to create graphics pipeline");
device.destroy_shader_module(vertex_shader_module);
device.destroy_shader_module(fragment_shader_module);
pipeline
}
let pipeline = unsafe {
make_pipeline::<backend::Backend>(
&device,
&render_pass,
&pipeline_layout,
vertex_shader,
fragment_shader,
)
};
struct Resources<B: gfx_hal::Backend> {
instance: B::Instance,
surface: B::Surface,
device: B::Device,
render_passes: Vec<B::RenderPass>,
pipeline_layouts: Vec<B::PipelineLayout>,
pipelines: Vec<B::GraphicsPipeline>,
command_pool: B::CommandPool,
submission_complete_fence: B::Fence,
rendering_complete_semaphore: B::Semaphore,
}
struct ResourceHolder<B: gfx_hal::Backend>(ManuallyDrop<Resources<B>>);
impl<B: gfx_hal::Backend> Drop for ResourceHolder<B> {
fn drop(&mut self) {
unsafe {
let Resources {
instance,
mut surface,
device,
command_pool,
render_passes,
pipeline_layouts,
pipelines,
submission_complete_fence,
rendering_complete_semaphore,
} = ManuallyDrop::take(&mut self.0);
device.destroy_semaphore(rendering_complete_semaphore);
device.destroy_fence(submission_complete_fence);
for pipeline in pipelines {
device.destroy_graphics_pipeline(pipeline);
}
for pipeline_layout in pipeline_layouts {
device.destroy_pipeline_layout(pipeline_layout);
}
for render_pass in render_passes {
device.destroy_render_pass(render_pass);
}
device.destroy_command_pool(command_pool);
surface.unconfigure_swapchain(&device);
instance.destroy_surface(surface);
}
}
}
let submission_complete_fence = device.create_fence(true).expect("Out of memory");
let rendering_complete_semaphore = device.create_semaphore().expect("Out of memory");
let mut _should_configure_swapchain = true;
let mut resource_holder: ResourceHolder<backend::Backend> =
ResourceHolder(ManuallyDrop::new(Resources {
instance,
surface,
device,
command_pool,
render_passes: vec![render_pass],
pipeline_layouts: vec![pipeline_layout],
pipelines: vec![pipeline],
submission_complete_fence,
rendering_complete_semaphore,
}));
let start_time = instant::Instant::now();
event_loop.run(move |event, _, control_flow| {
use winit::event::{Event, WindowEvent};
use winit::event_loop::ControlFlow;
match event {
Event::WindowEvent { event, .. } => match event {
WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit,
WindowEvent::Resized(dims) => {
surface_extend = window::Extent2D {
width: dims.width,
height: dims.height,
};
_should_configure_swapchain = true;
}
WindowEvent::ScaleFactorChanged { new_inner_size, .. } => {
surface_extend = window::Extent2D {
height: new_inner_size.height,
width: new_inner_size.width,
};
_should_configure_swapchain = true;
}
_ => (),
},
Event::MainEventsCleared => window.request_redraw(),
winit::event::Event::RedrawEventsCleared => {
let res: &mut Resources<_> = &mut resource_holder.0;
let render_pass = &res.render_passes[0];
let pipeline_layout = &res.pipeline_layouts[0];
let pipeline = &res.pipelines[0];
let anim = start_time.elapsed().as_secs_f32().sin();
let small = [0.33, 0.33];
let triangles = &[
// red triangles
PushConstants {
color: [1.0, 0.0, 0.0, 1.0],
pos: [-0.5, -0.5],
scale: small,
},
];
unsafe {
#[allow(unused_variables)]
let render_timeout_ns = 1_000_000_000;
#[cfg(not(target_arch = "wasm32"))]
{
res.device
.wait_for_fence(&res.submission_complete_fence, render_timeout_ns)
.expect("Out of memory or device lost");
}
res.device
.reset_fence(&mut res.submission_complete_fence)
.expect("Out of memory");
res.command_pool.reset(false);
}
if _should_configure_swapchain {
use gfx_hal::window::SwapchainConfig;
let caps = res.surface.capabilities(&adapter.physical_device);
let mut swapchain_config =
SwapchainConfig::from_caps(&caps, surface_color_format, surface_extend);
if caps.image_count.contains(&3) {
swapchain_config.image_count = 3;
}
surface_extend = swapchain_config.extent;
unsafe {
res.surface
.configure_swapchain(&res.device, swapchain_config)
.expect("Failed re configure swapchain");
}
_should_configure_swapchain = false;
}
let surface_image = unsafe {
let acquire_timeout_ns = 1_000_000_000;
match res.surface.acquire_image(acquire_timeout_ns) {
Ok((image, _)) => image,
Err(_) => {
_should_configure_swapchain = true;
return;
}
}
};
let framebuffer = unsafe {
use gfx_hal::image::Extent;
use gfx_hal::window::SwapchainConfig;
let caps = res.surface.capabilities(&adapter.physical_device);
let swapchain_config =
SwapchainConfig::from_caps(&caps, surface_color_format, surface_extend);
res.device
.create_framebuffer(
render_pass,
iter::once(swapchain_config.framebuffer_attachment()),
Extent {
width: surface_extend.width,
height: surface_extend.height,
depth: 1,
},
)
.unwrap()
};
let viewport = {
use gfx_hal::pso::{Rect, Viewport};
Viewport {
rect: Rect {
x: 0,
y: 0,
w: surface_extend.width as i16,
h: surface_extend.height as i16,
},
depth: 0.0..1.0,
}
};
unsafe {
use gfx_hal::command::{CommandBufferFlags, SubpassContents};
command_buffer.begin_primary(CommandBufferFlags::ONE_TIME_SUBMIT);
command_buffer.set_viewports(0, iter::once(viewport.clone()));
command_buffer.set_scissors(0, iter::once(viewport.rect));
command_buffer.begin_render_pass(
render_pass,
&framebuffer,
viewport.rect,
iter::once(command::RenderAttachmentInfo {
image_view: std::borrow::Borrow::borrow(&surface_image),
clear_value: command::ClearValue {
color: command::ClearColor {
float32: [0.0, 0.0, 0.0, 1.0],
},
},
}),
SubpassContents::Inline,
);
command_buffer.bind_graphics_pipeline(pipeline);
command_buffer.draw(0..4, 0..1);
command_buffer.end_render_pass();
command_buffer.finish();
queue_group.queues[0].submit(
iter::once(&command_buffer),
iter::empty(),
iter::once(&res.rendering_complete_semaphore),
Some(&mut res.submission_complete_fence),
);
// present frame
if let Err(_) = queue_group.queues[0].present(
&mut res.surface,
surface_image,
Some(&mut res.rendering_complete_semaphore),
) {
_should_configure_swapchain = true;
res.device.destroy_framebuffer(framebuffer);
}
}
}
_ => (),
}
})
}
|
use crate::r#type::Type;
#[derive(Debug, Clone)]
pub struct Bound {
pub name: String,
pub bound: Vec<Type>,
}
|
use std::thread;
use std::net::{TcpListener, TcpStream};
use std::io::{Read, Write};
use std::env;
use std::str;
const BUFFERBYTES: usize = 20;
fn client_handshake(mut stream: TcpStream) {
let mut data = [0 as u8; BUFFERBYTES]; // using 20 byte buffer
while match stream.read(&mut data) {
Ok(size) => {
// echo what's received
if size > 0 {
let val = str::from_utf8(&data[0..size]).unwrap();
println!("{}", val);
let resp = cycle_client_response(val);
stream.write(resp.as_bytes()).unwrap();
}
true
},
Err(_) => {
eprintln!("An error occurred while connecting to socket");
false
}
} {}
}
fn cycle_client_response(value: &str) -> String {
let mut splits = value.split(' ');
splits.next();
// get number sent by client
let mut num = splits.next().unwrap()
.parse::<i32>().unwrap();
num += 1;
let msg = format!("Hello {}", num);
msg
}
fn main() {
let mut addr = String::from("127.0.0.1:");
// read user input which should contain port
let args: Vec<String> = env::args().collect();
addr.push_str(&args[1]);
let listener = TcpListener::bind(addr).unwrap();
// accept connections and process them,
// spawning a new thread for each connection
for stream in listener.incoming() {
match stream {
Ok(stream) => {
thread::spawn(move || {
// handle successful connection
client_handshake(stream);
});
}
Err(e) => eprintln!("Error: {}", e),
}
}
// close the socket server
drop(listener);
}
|
use std::error::Error;
use futures::{Async, Poll};
use futures::future::{Future, IntoFuture, Shared, SharedError, SharedItem};
use rayon::ThreadPool;
use specs::{Component, DenseVecStorage};
use {BoxedErr, SharedAssetError, StoreId};
/// One of the three core traits of this crate.
///
/// You want to implement this for every type of asset like
///
/// * `Mesh`
/// * `Texture`
/// * `Terrain`
///
/// and so on. Now, an asset may be available in different formats.
/// That's why we have the `Data` associated type here. You can specify
/// an intermediate format here, like the vertex data for a mesh or the samples
/// for audio data.
///
/// This data is then generated by the `Format` trait.
pub trait Asset: Sized {
/// The `Context` type that can produce this asset
type Context: Context<Asset = Self>;
}
/// A future for an asset
pub struct AssetFuture<A>(pub Shared<Box<Future<Item = A, Error = BoxedErr>>>);
impl<A> AssetFuture<A> {
/// Wrap another future into `AssetFuture`
pub fn from_future<F>(f: F) -> Self
where
F: IntoFuture<Item = A, Error = BoxedErr> + 'static,
{
let f: Box<Future<Item = A, Error = BoxedErr>> = Box::new(f.into_future());
AssetFuture(f.shared())
}
}
impl<A> Component for AssetFuture<A>
where
A: Component,
Self: 'static,
{
type Storage = DenseVecStorage<Self>;
}
impl<A> AssetFuture<A> {
/// If any clone of this future has completed execution, returns its result immediately
/// without blocking.
/// Otherwise, returns None without triggering the work represented by this future.
pub fn peek(&self) -> Option<Result<SharedItem<A>, SharedError<BoxedErr>>> {
self.0.peek()
}
}
impl<A> Clone for AssetFuture<A> {
fn clone(&self) -> Self {
AssetFuture(self.0.clone())
}
}
impl<A> Future for AssetFuture<A>
where
A: Clone,
{
type Item = A;
type Error = BoxedErr;
fn poll(&mut self) -> Poll<A, BoxedErr> {
match self.0.poll() {
Ok(Async::NotReady) => Ok(Async::NotReady),
Ok(Async::Ready(asset)) => Ok(Async::Ready((*asset).clone())),
Err(err) => Err(BoxedErr(Box::new(SharedAssetError::from(err)))),
}
}
}
impl<A> From<Shared<Box<Future<Item = A, Error = BoxedErr>>>> for AssetFuture<A> {
fn from(inner: Shared<Box<Future<Item = A, Error = BoxedErr>>>) -> Self {
AssetFuture(inner)
}
}
/// A specifier for an asset, uniquely identifying it by
///
/// * the extension (the format it was provided in)
/// * its name
/// * the storage it was loaded from
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct AssetSpec {
/// The possible extensions of this asset
pub exts: &'static [&'static str],
/// The name of this asset.
pub name: String,
/// Unique identifier indicating the Storage from which the asset was loaded.
pub store: StoreId,
}
impl AssetSpec {
/// Creates a new asset specifier from the given parameters.
pub fn new(name: String, exts: &'static [&'static str], store: StoreId) -> Self {
AssetSpec { exts, name, store }
}
}
/// The context type which manages assets of one type.
/// It is responsible for caching
pub trait Context: Send + Sync + 'static {
/// The asset type this context can produce.
type Asset: Asset;
/// The `Data` type the asset can be created from.
type Data;
/// The error that may be returned from `create_asset`.
type Error: Error + Send + Sync;
/// The result type for loading an asset. This can also be a future
/// (or anything that implements `IntoFuture`).
type Result: IntoFuture<Item = Self::Asset, Error = Self::Error>;
/// A small keyword for which category these assets belongs to.
///
/// ## Examples
///
/// * `"mesh"` for `Mesh`
/// * `"data"` for `Level`
///
/// The storage may use this information, to e.g. search the identically-named
/// subfolder.
fn category(&self) -> &str;
/// Provides the conversion from the data format to the actual asset.
fn create_asset(&self, data: Self::Data, pool: &ThreadPool) -> Self::Result;
/// Notifies about an asset load. This is can be used to cache the asset.
/// To return a cached asset, see the `retrieve` function.
fn cache(&self, _spec: AssetSpec, _asset: AssetFuture<Self::Asset>) {}
/// Returns `Some` cached value if possible, otherwise `None`.
///
/// For a basic implementation of a cache, please take a look at the `Cache` type.
fn retrieve(&self, _spec: &AssetSpec) -> Option<AssetFuture<Self::Asset>> {
None
}
/// Updates an asset after it's been reloaded.
///
/// This usually just puts the new asset into a queue;
/// the actual update happens by calling `update` on the
/// asset.
fn update(&self, spec: &AssetSpec, asset: AssetFuture<Self::Asset>);
/// Gives a hint that several assets may have been released recently.
///
/// This is useful if your assets are reference counted, because you are
/// now able to remove unique assets from the cache, leaving the shared
/// ones there.
fn clear(&self) {}
/// Request for clearing the whole cache.
fn clear_all(&self) {}
}
/// A format, providing a conversion from bytes to asset data, which is then
/// in turn accepted by `Asset::from_data`. Examples for formats are
/// `Png`, `Obj` and `Wave`.
pub trait Format {
/// A list of the extensions (without `.`).
///
/// ## Examples
///
/// * `"png"`
/// * `"obj"`
/// * `"wav"`
const EXTENSIONS: &'static [&'static str];
/// The data type this format is able to load.
type Data;
/// The error that may be returned from `Format::parse`.
type Error: Error + Send + Sync;
/// The result of the `parse` method. Can be anything that implements
/// `IntoFuture`.
type Result: IntoFuture<Item = Self::Data, Error = Self::Error>;
/// Reads the given bytes and produces asset data.
fn parse(&self, bytes: Vec<u8>, pool: &ThreadPool) -> Self::Result;
}
|
pub const PIXELS_PER_TIME: f64 = 100.0;
pub const PIXELS_PER_SEMITONE: f64 = 8.0;
use misc::Vector;
use data::{State, DragType};
use edited_note::NoteDrawingInfo;
impl State {
pub fn client_to_time (&self, client: f64)->f64 {
client / PIXELS_PER_TIME
}
pub fn client_to_pitch (&self, client: f64)->f64 {
(client / -PIXELS_PER_SEMITONE) + 101.5
}
pub fn time_to_client (&self, time: f64)->f64 {
time * PIXELS_PER_TIME
}
pub fn pitch_to_client (&self, pitch: f64)->f64 {
(pitch - 101.5) * -PIXELS_PER_SEMITONE
}
pub fn music_to_client (&self, music: Vector)->Vector {
Vector::new (self.time_to_client (music [0]), self.pitch_to_client (music [1]))
}
pub fn client_to_music (&self, client: Vector)->Vector {
Vector::new (self.client_to_time (client[0]), self.client_to_pitch (client[1]))
}
pub fn update_elements (&self) {
js!{ $("#notes").height (@{PIXELS_PER_SEMITONE*80.0 }); }
let info = NoteDrawingInfo {
drag_type: self.drag_type(),
state: & self,
};
js!{ $(".drag_select").remove() ;}
if let Some(DragType::DragSelect {minima, maxima, ..}) = info.drag_type {
let minima = self.music_to_client (minima);
let maxima = self.music_to_client (maxima);
let size = maxima - minima;
js!{ $("<div>", {class: "drag_select"}).appendTo ($("#notes")).css ({
left:@{minima [0]},
top:@{maxima [1]},
width:@{size[0]},
height:@{-size[1]},
});}
}
for note in &self.notes {note.update_element(& info)}
}
pub fn init_elements (&self) {
for octave in 0..10 {
for (index, black) in vec![false, true, false, false, true, false, true, false, false, true, false, true].into_iter().enumerate() {
let pitch = (octave*12 + index + 21) as f64;
if black {
js!{
$("#notes").append ($("<div>", {class: "key"}).css({top: @{self.pitch_to_client (pitch+0.5)}, height:@{PIXELS_PER_SEMITONE}, "background-color": "#ddd"}));
}
}
}
}
}
}
|
extern crate bitmap_io;
use bitmap_io::*;
use std::fs::File;
#[allow(unused_must_use)]
fn main() {
let mut bmp_file = File::open("test_24-uncompressed.bmp").unwrap();
let test_24_uncompressed = Bitmap::from_file(&mut bmp_file).unwrap();
let mut bmp_file = File::open("test_32-uncompressed.bmp").unwrap();
let test_32_uncompressed = Bitmap::from_file(&mut bmp_file).unwrap();
let mut bmp_file = File::open("test_32-bitfield.bmp").unwrap();
let test_32_bitfield = Bitmap::from_file(&mut bmp_file).unwrap();
let mut bmp_file = File::open("test_16-bitfield.bmp").unwrap();
let test_16_bitfield = Bitmap::from_file(&mut bmp_file).unwrap();
let mut bmp_file = File::open("8bpp.bmp").unwrap();
let test_8_uncompressed = Bitmap::from_file(&mut bmp_file).unwrap();
// let mut bmp_file = File::open("test.bmp").unwrap();
// let bitmap = Bitmap::from_file(&mut bmp_file).unwrap();
// println!("{}", bitmap.file_header);
// println!("{}", bitmap.info_header);
if let Ok(mut out_file) = File::create("test_24-uncompressed-result.bmp") {
test_24_uncompressed.into_file(&mut out_file);
}
if let Ok(mut out_file) = File::create("test_32-uncompressed-result.bmp") {
test_32_uncompressed.into_file(&mut out_file);
}
if let Ok(mut out_file) = File::create("test_32-bitfield-result.bmp") {
test_32_bitfield.into_file(&mut out_file);
}
if let Ok(mut out_file) = File::create("test_16-bitfield-result.bmp") {
test_16_bitfield.into_file(&mut out_file);
}
if let Ok(mut out_file) = File::create("test_8-uncompressed-result.bmp") {
test_8_uncompressed.into_file(&mut out_file);
}
println!("Hello world");
}
|
use exonum::crypto::{PublicKey, Hash};
encoding_struct! {
#[derive(Eq, PartialOrd, Ord)]
struct Offer {
wallet: &PublicKey,
amount: u64,
tx_hash: &Hash,
}
}
impl Offer {
pub fn remove_amount(&mut self, amount: u64) {
*self = Offer::new(self.wallet(), self.amount() - amount, &self.tx_hash());
}
pub fn add_amount(&mut self, amount: u64) {
*self = Offer::new(self.wallet(), self.amount() + amount, &self.tx_hash());
}
}
|
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Resource {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
pub location: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ActionGroupResource {
#[serde(flatten)]
pub resource: Resource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<ActionGroup>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ActionGroupList {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<ActionGroupResource>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ActionGroup {
#[serde(rename = "groupShortName")]
pub group_short_name: String,
pub enabled: bool,
#[serde(rename = "emailReceivers", default, skip_serializing_if = "Vec::is_empty")]
pub email_receivers: Vec<EmailReceiver>,
#[serde(rename = "smsReceivers", default, skip_serializing_if = "Vec::is_empty")]
pub sms_receivers: Vec<SmsReceiver>,
#[serde(rename = "webhookReceivers", default, skip_serializing_if = "Vec::is_empty")]
pub webhook_receivers: Vec<WebhookReceiver>,
#[serde(rename = "itsmReceivers", default, skip_serializing_if = "Vec::is_empty")]
pub itsm_receivers: Vec<ItsmReceiver>,
#[serde(rename = "azureAppPushReceivers", default, skip_serializing_if = "Vec::is_empty")]
pub azure_app_push_receivers: Vec<AzureAppPushReceiver>,
#[serde(rename = "automationRunbookReceivers", default, skip_serializing_if = "Vec::is_empty")]
pub automation_runbook_receivers: Vec<AutomationRunbookReceiver>,
#[serde(rename = "voiceReceivers", default, skip_serializing_if = "Vec::is_empty")]
pub voice_receivers: Vec<VoiceReceiver>,
#[serde(rename = "logicAppReceivers", default, skip_serializing_if = "Vec::is_empty")]
pub logic_app_receivers: Vec<LogicAppReceiver>,
#[serde(rename = "azureFunctionReceivers", default, skip_serializing_if = "Vec::is_empty")]
pub azure_function_receivers: Vec<AzureFunctionReceiver>,
#[serde(rename = "armRoleReceivers", default, skip_serializing_if = "Vec::is_empty")]
pub arm_role_receivers: Vec<ArmRoleReceiver>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EmailReceiver {
pub name: String,
#[serde(rename = "emailAddress")]
pub email_address: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<ReceiverStatus>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SmsReceiver {
pub name: String,
#[serde(rename = "countryCode")]
pub country_code: String,
#[serde(rename = "phoneNumber")]
pub phone_number: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<ReceiverStatus>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WebhookReceiver {
pub name: String,
#[serde(rename = "serviceUri")]
pub service_uri: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ItsmReceiver {
pub name: String,
#[serde(rename = "workspaceId")]
pub workspace_id: String,
#[serde(rename = "connectionId")]
pub connection_id: String,
#[serde(rename = "ticketConfiguration")]
pub ticket_configuration: String,
pub region: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AzureAppPushReceiver {
pub name: String,
#[serde(rename = "emailAddress")]
pub email_address: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AutomationRunbookReceiver {
#[serde(rename = "automationAccountId")]
pub automation_account_id: String,
#[serde(rename = "runbookName")]
pub runbook_name: String,
#[serde(rename = "webhookResourceId")]
pub webhook_resource_id: String,
#[serde(rename = "isGlobalRunbook")]
pub is_global_runbook: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "serviceUri", default, skip_serializing_if = "Option::is_none")]
pub service_uri: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VoiceReceiver {
pub name: String,
#[serde(rename = "countryCode")]
pub country_code: String,
#[serde(rename = "phoneNumber")]
pub phone_number: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LogicAppReceiver {
pub name: String,
#[serde(rename = "resourceId")]
pub resource_id: String,
#[serde(rename = "callbackUrl")]
pub callback_url: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AzureFunctionReceiver {
pub name: String,
#[serde(rename = "functionAppResourceId")]
pub function_app_resource_id: String,
#[serde(rename = "functionName")]
pub function_name: String,
#[serde(rename = "httpTriggerUrl")]
pub http_trigger_url: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ArmRoleReceiver {
pub name: String,
#[serde(rename = "roleId")]
pub role_id: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ReceiverStatus {
NotSpecified,
Enabled,
Disabled,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EnableRequest {
#[serde(rename = "receiverName")]
pub receiver_name: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorResponse {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ActionGroupPatchBody {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<ActionGroupPatch>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ActionGroupPatch {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub enabled: Option<bool>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LocalizableString {
pub value: String,
#[serde(rename = "localizedValue", default, skip_serializing_if = "Option::is_none")]
pub localized_value: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BaselineMetadataValue {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<LocalizableString>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BaselineResponse {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<LocalizableString>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub timestamps: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub baseline: Vec<Baseline>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub metdata: Vec<BaselineMetadataValue>,
#[serde(rename = "predictionResultType", default, skip_serializing_if = "Option::is_none")]
pub prediction_result_type: Option<baseline_response::PredictionResultType>,
#[serde(rename = "errorType", default, skip_serializing_if = "Option::is_none")]
pub error_type: Option<baseline_response::ErrorType>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<BaselineProperties>,
}
pub mod baseline_response {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum PredictionResultType {}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ErrorType {}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BaselineProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub timespan: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub interval: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub aggregation: Option<String>,
#[serde(rename = "internalOperationId", default, skip_serializing_if = "Option::is_none")]
pub internal_operation_id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Baseline {
pub sensitivity: baseline::Sensitivity,
#[serde(rename = "lowThresholds")]
pub low_thresholds: Vec<f64>,
#[serde(rename = "highThresholds")]
pub high_thresholds: Vec<f64>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub timestamps: Vec<String>,
#[serde(rename = "PredictionResultType", default, skip_serializing_if = "Option::is_none")]
pub prediction_result_type: Option<baseline::PredictionResultType>,
#[serde(rename = "ErrorType", default, skip_serializing_if = "Option::is_none")]
pub error_type: Option<baseline::ErrorType>,
}
pub mod baseline {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Sensitivity {
Low,
Medium,
High,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum PredictionResultType {}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ErrorType {}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TimeSeriesInformation {
pub sensitivities: Vec<String>,
pub values: Vec<f64>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub timestamps: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CalculateBaselineResponse {
#[serde(rename = "type")]
pub type_: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub timestamps: Vec<String>,
pub baseline: Vec<Baseline>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub statistics: Option<calculate_baseline_response::Statistics>,
#[serde(rename = "internalOperationId", default, skip_serializing_if = "Option::is_none")]
pub internal_operation_id: Option<String>,
#[serde(rename = "errorType", default, skip_serializing_if = "Option::is_none")]
pub error_type: Option<calculate_baseline_response::ErrorType>,
}
pub mod calculate_baseline_response {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Statistics {
#[serde(rename = "isEligible", default, skip_serializing_if = "Option::is_none")]
pub is_eligible: Option<bool>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub status: Vec<String>,
#[serde(rename = "seasonalityPeriod", default, skip_serializing_if = "Option::is_none")]
pub seasonality_period: Option<i32>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ErrorType {}
}
|
#[doc = "Register `ETH_MACVR` reader"]
pub type R = crate::R<ETH_MACVR_SPEC>;
#[doc = "Field `SNPSVER` reader - SNPSVER"]
pub type SNPSVER_R = crate::FieldReader;
#[doc = "Field `USERVER` reader - USERVER"]
pub type USERVER_R = crate::FieldReader;
impl R {
#[doc = "Bits 0:7 - SNPSVER"]
#[inline(always)]
pub fn snpsver(&self) -> SNPSVER_R {
SNPSVER_R::new((self.bits & 0xff) as u8)
}
#[doc = "Bits 8:15 - USERVER"]
#[inline(always)]
pub fn userver(&self) -> USERVER_R {
USERVER_R::new(((self.bits >> 8) & 0xff) as u8)
}
}
#[doc = "The version register identifies the version of the Ethernet peripheral.\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_macvr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct ETH_MACVR_SPEC;
impl crate::RegisterSpec for ETH_MACVR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`eth_macvr::R`](R) reader structure"]
impl crate::Readable for ETH_MACVR_SPEC {}
#[doc = "`reset()` method sets ETH_MACVR to value 0x4042"]
impl crate::Resettable for ETH_MACVR_SPEC {
const RESET_VALUE: Self::Ux = 0x4042;
}
|
use std::io;
use std::net::SocketAddr;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::{Duration, Instant};
use bytes::Bytes;
use failure::{format_err, Error};
use futures::prelude::*;
use futures::ready;
use log::{debug, info, warn};
use tokio::time::{delay_until, interval, Delay, Interval};
use crate::packet::Packet;
use crate::protocol::handshake::Handshake;
use crate::protocol::sender;
use crate::protocol::sender::{SenderAlgorithmAction, SenderMetrics};
use crate::{CongestCtrl, ConnectionSettings, SrtCongestCtrl};
pub struct SenderSink<T, CC> {
sock: T,
sender: sender::Sender,
/// The congestion control
_congest_ctrl: CC,
/// The send timer
snd_wait: Option<Delay>,
/// The interval to report stats with
stats_interval: Interval,
}
impl<T, CC> SenderSink<T, CC>
where
T: Stream<Item = Result<(Packet, SocketAddr), Error>>
+ Sink<(Packet, SocketAddr), Error = Error>
+ Unpin,
CC: CongestCtrl + Unpin,
{
pub fn new(
sock: T,
congest_ctrl: CC,
settings: ConnectionSettings,
handshake: Handshake,
) -> SenderSink<T, CC> {
info!(
"Sending started to {:?}, with latency={:?}",
settings.remote, settings.tsbpd_latency
);
SenderSink {
sock,
sender: sender::Sender::new(settings, handshake, SrtCongestCtrl),
_congest_ctrl: congest_ctrl,
snd_wait: None,
stats_interval: interval(Duration::from_secs(1)),
}
}
/// Set the interval to get statistics on
/// Defaults to one second
pub fn set_stats_interval(&mut self, ivl: Duration) {
self.stats_interval = interval(ivl);
}
pub fn settings(&self) -> &ConnectionSettings {
&self.sender.settings()
}
pub fn remote(&self) -> SocketAddr {
self.sender.settings().remote
}
pub fn metrics(&self) -> SenderMetrics {
self.sender.metrics()
}
fn sock(&mut self) -> Pin<&mut T> {
Pin::new(&mut self.sock)
}
fn send_packets(&mut self, cx: &mut Context) -> Result<(), Error> {
while let Poll::Ready(()) = self.sock().as_mut().poll_ready(cx)? {
match self.sender.pop_output() {
Some(packet) => self.sock().start_send(packet)?,
None => break,
}
}
let _ = self.sock().poll_flush(cx)?;
Ok(())
}
fn check_sender_flushed(&mut self, cx: &mut Context) -> Result<bool, Error> {
if let Poll::Ready(_) = self.sock().poll_flush(cx)? {
// if everything is flushed, return Ok
if self.sender.is_flushed() {
return Ok(true);
}
}
Ok(false)
}
fn receive_packets(&mut self, cx: &mut Context) -> Result<(), Error> {
// do we have any packets to handle?
while let Poll::Ready(a) = self.sock().poll_next(cx) {
match a {
Some(Ok(packet)) => {
debug!("Got packet: {:?}", packet);
self.sender.handle_packet(packet, Instant::now()).unwrap();
}
Some(Err(e)) => warn!("Failed to decode packet: {:?}", e),
// stream has ended, means shutdown
None => {
return Err(format_err!("Unexpected EOF of underlying stream"));
}
}
}
Ok(())
}
fn check_snd_timer(&mut self, cx: &mut Context) -> bool {
if let Some(timer) = &mut self.snd_wait {
match Pin::new(timer).poll(cx) {
Poll::Pending => return false,
Poll::Ready(_) => {
self.snd_wait = None;
self.sender.handle_snd_timer(Instant::now());
}
}
}
true
}
fn process_next_action(&mut self, cx: &mut Context) -> Poll<Result<(), Error>> {
use SenderAlgorithmAction::*;
match self.sender.next_action() {
WaitForData | WaitUntilAck => {
cx.waker().wake_by_ref();
Poll::Pending
}
WaitUntil(t) => {
self.snd_wait = Some(delay_until(t.into()));
cx.waker().wake_by_ref();
Poll::Pending
}
Close => Poll::Ready(Err(io::Error::new(
io::ErrorKind::ConnectionAborted,
"Connection received shutdown",
)
.into())),
}
}
fn poll_sink_flushed(&mut self, cx: &mut Context) -> Poll<Result<(), Error>> {
if self.check_sender_flushed(cx)? {
// TODO: this is wrong for KeepAlive
debug!("Returning ready");
return Poll::Ready(Ok(()));
}
self.receive_packets(cx)?;
self.send_packets(cx)?;
if !self.check_snd_timer(cx) {
return Poll::Pending;
}
self.process_next_action(cx)
}
fn poll_sink_closed(&mut self, cx: &mut Context) -> Poll<Result<(), Error>> {
self.sender.handle_close(Instant::now());
self.send_packets(cx)?;
self.sock().poll_close(cx)
}
}
impl<T, CC> Sink<(Instant, Bytes)> for SenderSink<T, CC>
where
T: Stream<Item = Result<(Packet, SocketAddr), Error>>
+ Sink<(Packet, SocketAddr), Error = Error>
+ Unpin,
CC: CongestCtrl + Unpin,
{
type Error = Error;
fn start_send(mut self: Pin<&mut Self>, item: (Instant, Bytes)) -> Result<(), Error> {
self.sender.handle_data(item);
Ok(())
}
fn poll_ready(self: Pin<&mut Self>, _cx: &mut Context) -> Poll<Result<(), Error>> {
Poll::Ready(Ok(()))
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Error>> {
self.get_mut().poll_sink_flushed(cx)
}
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Error>> {
ready!(self.as_mut().poll_sink_flushed(cx))?;
self.as_mut().poll_sink_closed(cx)
}
}
// Stats streaming
impl<T, CC> Stream for SenderSink<T, CC>
where
T: Stream<Item = Result<(Packet, SocketAddr), Error>>
+ Sink<(Packet, SocketAddr), Error = Error>
+ Unpin,
CC: CongestCtrl + Unpin,
{
type Item = Result<SenderMetrics, Error>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
ready!(Pin::new(&mut self.stats_interval).poll_next(cx));
Poll::Ready(Some(Ok(self.metrics())))
}
}
|
use esolangs::brainfuck::{brainfuck, brainfuck_include};
#[test]
fn mandelbrot() {
brainfuck_include!("tests/bf/mandelbrot.b");
}
#[test]
fn numwarp() {
brainfuck_include!("tests/bf/numwarp.b");
}
#[test]
fn dfbi() {
brainfuck_include!("tests/bf/dbfi.b");
}
// http://brainfuck.org/tests.b
#[test]
fn test_1() {
brainfuck! {
>,>+++++++++,>+++++++++++[<++++++<++++++<+>>>-]<<.>.< < -.>.>.<<.
}
}
#[test]
fn test_2() {
brainfuck! {
++++[>++++++<-]>[>+++++>+++++++<<-]>>++++<[[>[[>>+<<-]<]>>>-]>-[>+>+<<-]>]
+++++[>+++++++<<++>-]>.<<.
}
}
#[test]
fn test_3() {
brainfuck! {
[]++++++++++[>>+>+>++++++[<<+<+++>>>-]<<<<-]
"A*$";?@![#>>+<<]>[>>]<<<<[>++<[-]]>.>.
}
}
|
use super::bit;
use super::timer::{Timers};
use super::cartridge::{Cartridge};
pub struct Bus {
ram1: [u8; 4 * 1024],
ram2: [u8; 4 * 1024],
highRam: [u8; 127],
cart: Option<Cartridge>,
pub interruptEnableRegister: u8,
pub interruptRequestRegister: u8,
pub timerRegisters: Timers
}
pub enum IntrFlags {
VBlank = 0,
LCD = 1,
Timer = 2,
Serial = 3,
Joypad = 4
}
impl Bus {
pub fn new() -> Self {
Self {
ram1: [0; 4 * 1024],
ram2: [0; 4 * 1024],
highRam: [0; 127],
cart: None,
interruptEnableRegister: 0,
interruptRequestRegister: 0,
timerRegisters: Timers::new(),
}
}
pub fn insertCartridge(&mut self, c: Cartridge) {
self.cart = Some(c);
}
pub fn cpuRead(&self, addr: u16) -> u8 {
match addr {
0x0000..= 0x3FFF => {
match &self.cart {
Some(x) => x.readRom(addr),
None => panic!("Cartridge not inserted"),
}
},
0x4000..= 0x7FFF => {
match &self.cart {
Some(x) => x.readRom(addr),
None => panic!("Cartridge not inserted"),
}
},
0x8000..= 0x9FFF => {
todo!("Vram not implemented")
},
0xA000..= 0xBFFF => {
match &self.cart {
Some(x) => x.readRam(addr),
None => panic!("Cartridge not inserted"),
}
},
0xC000..= 0xCFFF => {self.ram1[(addr & 0x0fff) as usize]},
0xD000..= 0xDFFF => {self.ram2[(addr & 0x0fff) as usize]},
0xE000..= 0xFDFF => {
if addr <= 0xEFFF {
self.ram1[(addr & 0x0fff) as usize]
} else {
self.ram2[(addr & 0x0fff) as usize]
}
},
0xFE00..= 0xFE9F => {
todo!("Sprite table not implemented");
},
0xFEA0..= 0xFEFF => {
panic!("Unusable memory")
},
0xFF00..= 0xFF7F => {
match addr & 0x00FF {
0x00 => {todo!("Controller not implemented")},
0x01..= 0x02 => {todo!("Communication not implemented")},
0x04..= 0x07 => {
match addr & 0x000F {
0x4 => {((self.timerRegisters.divRegister & 0xFF00) >> 8) as u8},
0x5 => {self.timerRegisters.timaRegister},
0x6 => {self.timerRegisters.tmaRegister},
0x7 => {self.timerRegisters.tacRegister},
_ => {0}
}},
0x0F => {self.interruptRequestRegister},
0x10..= 0x26 => {/* Sound, not implementing*/0},
0x30..= 0x3F => {/* Waveform RAM, not implementing*/0},
0x40..= 0x4B => {todo!("LCD register not implemented")},
0x4F => {/* GBC VRAM Bank Select */0},
0x50 => {/* Set to disable boot ROM ??*/0},
0x51..= 0x55 => {/* GBC HDMA */0},
0x68..= 0x69 => {/* GBC BCP/OCP */0},
0x70 => {/* GBC WRAM Bank Select */0}
_ => {panic!("Unknown write to {}", addr)}
}
},
0xFF80..= 0xFFFE => {
self.highRam[((addr & 0x00ff) - 0x0080) as usize]
},
0xFFFF => {
self.interruptEnableRegister
}
}
}
pub fn cpuWrite(&mut self, addr: u16, data: u8) {
match addr {
0x0000..= 0x3FFF => {panic!("Tried to write to ROM")},
0x4000..= 0x7FFF => {panic!("Tried to write to ROM")},
0x8000..= 0x9FFF => {
todo!("Vram not implemented")
},
0xA000..= 0xBFFF => {
match &mut self.cart {
Some(x) => x.writeRam(addr, data),
None => panic!("Cartridge not inserted"),
}
},
0xC000..= 0xCFFF => {
self.ram1[(addr & 0x0fff) as usize] = data;
},
0xD000..= 0xDFFF => {
self.ram2[(addr & 0x0fff) as usize] = data;
},
0xE000..= 0xFDFF => {
if addr <= 0xEFFF {
self.ram1[(addr & 0x0fff) as usize] = data;
} else {
self.ram2[(addr & 0x0fff) as usize] = data;
}
},
0xFE00..= 0xFE9F => {
todo!("Sprite table not implemented");
},
0xFEA0..= 0xFEFF => {
panic!("Unusable memory");
},
0xFF00..= 0xFF7F => {
match addr & 0x00FF {
0x00 => {todo!("Controller not implemented")},
0x01..= 0x02 => {todo!("Communication not implemented")},
0x04..= 0x07 => {
match addr & 0x000F {
0x4 => {self.timerRegisters.divRegister = 0},
0x5 => {self.timerRegisters.timaWrite(data);},
0x6 => {self.timerRegisters.tmaWrite(data)},
0x7 => {self.timerRegisters.tacRegister = data},
_ => {}
}},
0x0F => {self.interruptRequestRegister = data},
0x10..= 0x26 => {/* Sound, not implementing*/},
0x30..= 0x3F => {/* Waveform RAM, not implementing*/},
0x40..= 0x4B => {todo!("LCD register not implemented")},
0x4F => {/* GBC VRAM Bank Select */},
0x50 => {/* Set to disable boot ROM ??*/},
0x51..= 0x55 => {/* GBC HDMA */},
0x68..= 0x69 => {/* GBC BCP/OCP */},
0x70 => {/* GBC WRAM Bank Select */}
_ => {panic!("Unknown write to {}", addr)}
}
},
0xFF80..= 0xFFFE => {
self.highRam[((addr & 0x00ff) - 0x0080) as usize] = data;
},
0xFFFF => {
self.interruptEnableRegister = data;
}
}
}
pub fn requestInterrupt(&mut self, i: IntrFlags) {
self.interruptRequestRegister = bit::set(self.interruptRequestRegister, i as usize);
}
pub fn getInterruptRequest(&self, i: IntrFlags) -> bool {
bit::get(self.interruptRequestRegister, i as usize)
}
pub fn resetInterruptRequest(&mut self, i: IntrFlags) {
self.interruptRequestRegister = bit::clr(self.interruptRequestRegister, i as usize);
}
pub fn getInterruptEnable(&self, i: IntrFlags) -> bool{
bit::get(self.interruptEnableRegister, i as usize)
}
}
/*
0000 3FFF 16 KiB ROM bank 00 From cartridge, usually a fixed bank
4000 7FFF 16 KiB ROM Bank 01~NN From cartridge, switchable bank via mapper (if any)
8000 9FFF 8 KiB Video RAM (VRAM) In CGB mode, switchable bank 0/1
A000 BFFF 8 KiB External RAM From cartridge, switchable bank if any
C000 CFFF 4 KiB Work RAM (WRAM)
D000 DFFF 4 KiB Work RAM (WRAM) In CGB mode, switchable bank 1~7
E000 FDFF Mirror of C000~DDFF (ECHO RAM) Nintendo says use of this area is prohibited.
FE00 FE9F Sprite attribute table (OAM)
FEA0 FEFF Not Usable Nintendo says use of this area is prohibited
FF00 FF7F I/O Registers
FF80 FFFE High RAM (HRAM)
FFFF FFFF Interrupts Enable Register (IE)
*/
|
/*
Copyright 2019-2023 Didier Plaindoux
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
use std::marker::PhantomData;
use crate::parser::parser::Combine;
use crate::parser::parser::Parse;
use crate::parser::response::Response::Reject;
use crate::parser::response::Response::Success;
use crate::stream::position::Position;
use crate::stream::stream::Stream;
pub struct ParserStream<'a, P, A, S, L>(&'a P, S, PhantomData<A>, PhantomData<L>)
where
P: Combine<A> + Parse<A, S>,
S: Stream<Pos = L>,
L: Position;
impl<'a, P, A, S, L> ParserStream<'a, P, A, S, L>
where
P: Combine<A> + Parse<A, S>,
S: Stream<Pos = L>,
L: Position,
{
#[inline]
pub fn new(p: &'a P, s: S) -> Self {
ParserStream(p, s, PhantomData, PhantomData)
}
}
impl<'a, P, A, S, L> Clone for ParserStream<'a, P, A, S, L>
where
P: Combine<A> + Parse<A, S>,
S: Stream<Pos = L>,
L: Position,
{
fn clone(&self) -> Self {
ParserStream(self.0, self.1.clone(), PhantomData, PhantomData)
}
}
impl<'a, P, A, S, L> Stream for ParserStream<'a, P, A, S, L>
where
P: Combine<A> + Parse<A, S>,
S: Stream<Pos = L>,
L: Position,
{
type Item = A;
type Pos = L;
fn position(&self) -> Self::Pos {
self.1.position()
}
fn next(&self) -> (Option<Self::Item>, Self) {
match self.0.parse(self.1.clone()) {
Success(a, s, _) => (Some(a), ParserStream::new(self.0, s)),
Reject(_, _) => (None, ParserStream::new(self.0, self.1.clone())),
}
}
}
|
#[derive(Debug, Copy, Clone)]
pub struct Squircle {
pub p0: kurbo::Point,
pub p1: kurbo::Point,
pub p2: kurbo::Point,
pub radius: f64,
pub smoothness: f64,
}
impl Squircle {
pub fn to_curve(&self) -> Vec<kurbo::Point> {
let Squircle {
p0,
p1,
p2,
radius,
smoothness: xi,
} = *self;
if radius <= 0.0 {
return vec![p1];
}
let v0 = p0 - p1;
let v1 = p2 - p1;
let length0 = v0.hypot();
let length1 = v1.hypot();
let n0 = v0 / length0;
let n1 = v1 / length1;
let alpha = n0.dot(n1).acos();
let t = 1.0 / (alpha / 2.0).tan();
// clamp radius and amount of smoothing
let smoothing_length = (t + xi) * radius;
let smoothing = smoothing_length.min(length0).min(length1);
let (radius, xi) = if smoothing < t * radius {
(smoothing / t, 0.0)
} else {
(radius, (smoothing / radius - t).max(0.0))
};
let pc = p1 + n0 * radius * t;
let ccw = v0.cross(v1) > 0.0;
let n = if ccw {
kurbo::Vec2 { x: -n0.y, y: n0.x }
} else {
kurbo::Vec2 { x: n0.y, y: -n0.x }
};
let center = pc + n * radius;
let phi = std::f64::consts::PI - alpha;
let phi0 = 0.5 * phi * xi;
let phi1 = phi - 2.0 * phi0;
let phi0 = if ccw { -phi0 } else { phi0 };
let phi1 = if ccw { -phi1 } else { phi1 };
let (s0, c0) = phi0.sin_cos();
let (s1, c1) = (phi0 + phi1).sin_cos();
let vc = (0.5 * phi0.abs()).tan();
let ab = (vc + xi) * radius;
let sp0 = kurbo::Vec2 {
x: (c0 * -n.x + s0 * n.y),
y: (s0 * -n.x - c0 * n.y),
};
let sp1 = kurbo::Vec2 {
x: (c1 * -n.x + s1 * n.y),
y: (s1 * -n.x - c1 * n.y),
};
let c00 = p1 + n0 * smoothing;
let c01 = p1 + n0 * (smoothing - 2.0 * ab / 3.0);
let c02 = p1 + n0 * ((t - vc) * radius);
let c03 = center + radius * sp0;
let c10 = p1 + n1 * smoothing;
let c11 = p1 + n1 * (smoothing - 2.0 * ab / 3.0);
let c12 = p1 + n1 * ((t - vc) * radius);
let c13 = center + radius * sp1;
let phi2 = (phi1) / 2.0;
let (s2, c2) = (phi0 + phi2).sin_cos();
let sp2 = kurbo::Vec2 {
x: (c2 * -n.x + s2 * n.y),
y: (s2 * -n.x - c2 * n.y),
};
let alp = 4.0 / 3.0 * (phi2 / 4.0).tan();
let x02 = center + radius * sp2;
let x00 = c03
+ radius
* kurbo::Vec2 {
x: -alp * sp0.y,
y: alp * sp0.x,
};
let x01 = x02
+ radius
* kurbo::Vec2 {
x: alp * sp2.y,
y: -alp * sp2.x,
};
let x03 = x02
+ radius
* kurbo::Vec2 {
x: -alp * sp2.y,
y: alp * sp2.x,
};
let x04 = c13
+ radius
* kurbo::Vec2 {
x: alp * sp1.y,
y: -alp * sp1.x,
};
vec![
c00, c01, c02, c03, x00, x01, x02, x03, x04, c13, c12, c11, c10,
]
}
}
|
use crate::Number;
use super::Term;
///A term which divides one stored term by another
pub struct FractionTerm<T: Number>
{
numerator: Box<dyn Term<T> + Send + Sync>,
denominator: Box<dyn Term<T> + Send + Sync>
}
impl<T: Number> FractionTerm<T>
{
///Creates a fraction term from the given numerator and denominator terms
///
/// # Examples
///
/// ```
/// use crate::parametrizer::term::fractionterm::FractionTerm;
/// use crate::parametrizer::term::variableterm::VariableTerm;
/// use crate::parametrizer::term::constantterm::ConstantTerm;
/// use crate::parametrizer::term::Term;
///
/// let const1 = ConstantTerm::new(6);
/// let const2 = ConstantTerm::new(2);
/// let const3 = ConstantTerm::new(10);
/// let variable = VariableTerm::new();
///
/// let frac1 = FractionTerm::new(Box::new(const1), Box::new(const2));
/// let frac2 = FractionTerm::new(Box::new(const3), Box::new(variable));
///
/// assert_eq!(3, frac1.evaluate(1));
/// assert_eq!(2, frac2.evaluate(5));
/// ```
///
/// ```should_panic
/// use crate::parametrizer::term::fractionterm::FractionTerm;
/// use crate::parametrizer::term::variableterm::VariableTerm;
/// use crate::parametrizer::term::constantterm::ConstantTerm;
/// use crate::parametrizer::term::Term;
///
/// let const1 = ConstantTerm::new(6);
/// let variable = VariableTerm::new();
///
/// let frac1 = FractionTerm::new(Box::new(const1), Box::new(variable));
/// frac1.evaluate(0);
/// ```
pub fn new(numerator: Box<dyn Term<T> + Send + Sync>, denominator: Box<dyn Term<T> + Send + Sync>) -> FractionTerm<T>
{
return FractionTerm::<T> { numerator, denominator };
}
}
impl<T: Number> Term<T> for FractionTerm<T>
{
///Divides the numerator by the denominator.
///
/// # Panics
/// Panics if the denominator evaluates to 0
fn evaluate(&self, t: T) -> T
{
let d = self.denominator.evaluate(t);
if d == T::zero() //If the denominator is 0, panic
{
panic!("Cannot divide by 0 in parametrized InverseTerm. Make sure the function you set as your denominator is never zero on your inputs.");
}
else
{
return self.numerator.evaluate(t) / d;
}
}
}
|
#[doc = "Register `HASH_CSR19` reader"]
pub type R = crate::R<HASH_CSR19_SPEC>;
#[doc = "Register `HASH_CSR19` writer"]
pub type W = crate::W<HASH_CSR19_SPEC>;
#[doc = "Field `CS19` reader - CS19"]
pub type CS19_R = crate::FieldReader<u32>;
#[doc = "Field `CS19` writer - CS19"]
pub type CS19_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 32, O, u32>;
impl R {
#[doc = "Bits 0:31 - CS19"]
#[inline(always)]
pub fn cs19(&self) -> CS19_R {
CS19_R::new(self.bits)
}
}
impl W {
#[doc = "Bits 0:31 - CS19"]
#[inline(always)]
#[must_use]
pub fn cs19(&mut self) -> CS19_W<HASH_CSR19_SPEC, 0> {
CS19_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "HASH context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hash_csr19::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 [`hash_csr19::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct HASH_CSR19_SPEC;
impl crate::RegisterSpec for HASH_CSR19_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`hash_csr19::R`](R) reader structure"]
impl crate::Readable for HASH_CSR19_SPEC {}
#[doc = "`write(|w| ..)` method takes [`hash_csr19::W`](W) writer structure"]
impl crate::Writable for HASH_CSR19_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets HASH_CSR19 to value 0"]
impl crate::Resettable for HASH_CSR19_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use super::{traits::*, transaction::Transaction};
use crate::{Geometry, TableFlags, WriteMap, RO, RW};
use anyhow::Context;
use std::{
collections::BTreeMap,
fs::DirBuilder,
ops::Deref,
path::{Path, PathBuf},
};
use tempfile::tempdir;
#[derive(Debug)]
enum DbFolder {
Persisted(std::path::PathBuf),
Temporary(tempfile::TempDir),
}
impl DbFolder {
fn path(&self) -> &Path {
match self {
Self::Persisted(p) => p.as_path(),
Self::Temporary(temp_dir) => temp_dir.path(),
}
}
}
#[derive(Debug)]
pub struct Database {
inner: crate::Database<WriteMap>,
folder: DbFolder,
}
impl Database {
pub fn path(&self) -> &Path {
self.folder.path()
}
fn open_db(
mut builder: crate::DatabaseBuilder<WriteMap>,
folder: DbFolder,
chart: &DatabaseChart,
read_only: bool,
) -> anyhow::Result<Self> {
builder.set_max_tables(std::cmp::max(chart.len(), 1));
builder.set_flags(crate::DatabaseFlags {
mode: if read_only {
crate::Mode::ReadOnly
} else {
crate::Mode::ReadWrite {
sync_mode: crate::SyncMode::Durable,
}
},
no_rdahead: true,
coalesce: true,
..Default::default()
});
Ok(Self {
inner: builder.open(folder.path()).with_context(|| {
format!("failed to open database at {}", folder.path().display())
})?,
folder,
})
}
fn new(chart: &DatabaseChart, folder: DbFolder, read_only: bool) -> anyhow::Result<Self> {
let mut builder = crate::Database::<WriteMap>::new();
builder.set_max_tables(chart.len());
builder.set_geometry(Geometry {
size: Some(..isize::MAX as usize),
growth_step: None,
shrink_threshold: None,
page_size: None,
});
builder.set_rp_augment_limit(16 * 256 * 1024);
if read_only {
Self::open_db(builder, folder, chart, true)
} else {
let _ = DirBuilder::new().recursive(true).create(folder.path());
let this = Self::open_db(builder, folder, chart, false)?;
let tx = this.inner.begin_rw_txn()?;
for (table, settings) in chart {
tx.create_table(
Some(table),
if settings.dup_sort {
TableFlags::DUP_SORT
} else {
TableFlags::default()
},
)?;
}
tx.commit()?;
Ok(this)
}
}
pub fn create(chart: &DatabaseChart, path: Option<PathBuf>) -> anyhow::Result<Database> {
let folder = if let Some(path) = path {
DbFolder::Persisted(path)
} else {
let path = tempdir()?;
DbFolder::Temporary(path)
};
Self::new(chart, folder, false)
}
pub fn open(chart: &DatabaseChart, path: &Path) -> anyhow::Result<Database> {
Self::new(chart, DbFolder::Persisted(path.to_path_buf()), true)
}
}
impl Deref for Database {
type Target = crate::Database<WriteMap>;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl Database {
pub fn begin_read(&self) -> anyhow::Result<Transaction<'_, RO>> {
Ok(Transaction {
inner: self.inner.begin_ro_txn()?,
})
}
pub fn begin_readwrite(&self) -> anyhow::Result<Transaction<'_, RW>> {
Ok(Transaction {
inner: self.inner.begin_rw_txn()?,
})
}
}
#[derive(Debug)]
pub struct UntypedTable<T>(pub T)
where
T: Table;
impl<T> Table for UntypedTable<T>
where
T: Table,
{
const NAME: &'static str = T::NAME;
type Key = Vec<u8>;
type Value = Vec<u8>;
type SeekKey = Vec<u8>;
}
impl<T> UntypedTable<T>
where
T: Table,
{
pub fn encode_key(key: T::Key) -> <<T as Table>::Key as Encodable>::Encoded {
key.encode()
}
pub fn decode_key(encoded: &[u8]) -> anyhow::Result<T::Key>
where
<T as Table>::Key: Decodable,
{
<T::Key as Decodable>::decode(encoded)
}
pub fn encode_value(value: T::Value) -> <<T as Table>::Value as Encodable>::Encoded {
value.encode()
}
pub fn decode_value(encoded: &[u8]) -> anyhow::Result<T::Value> {
<T::Value as Decodable>::decode(encoded)
}
pub fn encode_seek_key(value: T::SeekKey) -> <<T as Table>::SeekKey as Encodable>::Encoded {
value.encode()
}
}
#[macro_export]
macro_rules! table {
($(#[$docs:meta])+ ( $name:ident ) $key:ty [ $seek_key:ty ] => $value:ty) => {
$(#[$docs])+
///
#[doc = concat!("Takes [`", stringify!($key), "`] as a key and returns [`", stringify!($value), "`]")]
#[derive(Clone, Copy, Debug, Default)]
pub struct $name;
impl $crate::orm::Table for $name {
const NAME: &'static str = stringify!($name);
type Key = $key;
type SeekKey = $seek_key;
type Value = $value;
}
impl $name {
pub const fn untyped(self) -> $crate::orm::UntypedTable<Self> {
$crate::orm::UntypedTable(self)
}
}
impl std::fmt::Display for $name {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", <Self as $crate::orm::Table>::NAME)
}
}
};
($(#[$docs:meta])+ ( $name:ident ) $key:ty => $value:ty) => {
table!(
$(#[$docs])+
( $name ) $key [ $key ] => $value
);
};
}
#[macro_export]
macro_rules! dupsort {
($(#[$docs:meta])+ ( $table_name:ident ) $key:ty [$seek_key:ty] => $value:ty [$seek_value:ty] ) => {
table!(
$(#[$docs])+
///
#[doc = concat!("`DUPSORT` table with seek value type being: [`", stringify!($seek_value), "`].")]
( $table_name ) $key [$seek_key] => $value
);
impl $crate::orm::DupSort for $table_name {
type SeekValue = $seek_value;
}
};
($(#[$docs:meta])+ ( $table_name:ident ) $key:ty [$seek_key:ty] => $value:ty ) => {
dupsort!(
$(#[$docs])+
( $table_name ) $key [$seek_key] => $value [$value]
);
};
($(#[$docs:meta])+ ( $table_name:ident ) $key:ty => $value:ty [$seek_value:ty] ) => {
dupsort!(
$(#[$docs])+
( $table_name ) $key [$key] => $value [$seek_value]
);
};
($(#[$docs:meta])+ ( $table_name:ident ) $key:ty => $value:ty ) => {
dupsort!(
$(#[$docs])+
( $table_name ) $key [$key] => $value [$value]
);
};
}
#[derive(Clone, Debug, Default)]
pub struct TableSettings {
pub dup_sort: bool,
}
/// Contains settings for each table in the database to be created or opened.
pub type DatabaseChart = BTreeMap<&'static str, TableSettings>;
#[macro_export]
macro_rules! table_info {
($t:ty) => {
(
<$t as $crate::orm::Table>::NAME,
$crate::orm::TableSettings {
dup_sort: $crate::impls::impls!($t: $crate::orm::DupSort),
},
)
};
}
|
#[doc = "Register `GINTSTS` reader"]
pub type R = crate::R<GINTSTS_SPEC>;
#[doc = "Register `GINTSTS` writer"]
pub type W = crate::W<GINTSTS_SPEC>;
#[doc = "Field `CMOD` reader - Current mode of operation"]
pub type CMOD_R = crate::BitReader;
#[doc = "Field `MMIS` reader - Mode mismatch interrupt"]
pub type MMIS_R = crate::BitReader;
#[doc = "Field `MMIS` writer - Mode mismatch interrupt"]
pub type MMIS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `OTGINT` reader - OTG interrupt"]
pub type OTGINT_R = crate::BitReader;
#[doc = "Field `SOF` reader - Start of frame"]
pub type SOF_R = crate::BitReader;
#[doc = "Field `SOF` writer - Start of frame"]
pub type SOF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RXFLVL` reader - RxFIFO non-empty"]
pub type RXFLVL_R = crate::BitReader;
#[doc = "Field `NPTXFE` reader - Non-periodic TxFIFO empty"]
pub type NPTXFE_R = crate::BitReader;
#[doc = "Field `GINAKEFF` reader - Global IN non-periodic NAK effective"]
pub type GINAKEFF_R = crate::BitReader;
#[doc = "Field `GOUTNAKEFF` reader - Global OUT NAK effective"]
pub type GOUTNAKEFF_R = crate::BitReader;
#[doc = "Field `ESUSP` reader - Early suspend"]
pub type ESUSP_R = crate::BitReader;
#[doc = "Field `ESUSP` writer - Early suspend"]
pub type ESUSP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `USBSUSP` reader - USB suspend"]
pub type USBSUSP_R = crate::BitReader;
#[doc = "Field `USBSUSP` writer - USB suspend"]
pub type USBSUSP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `USBRST` reader - USB reset"]
pub type USBRST_R = crate::BitReader;
#[doc = "Field `USBRST` writer - USB reset"]
pub type USBRST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `ENUMDNE` reader - Enumeration done"]
pub type ENUMDNE_R = crate::BitReader;
#[doc = "Field `ENUMDNE` writer - Enumeration done"]
pub type ENUMDNE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `ISOODRP` reader - Isochronous OUT packet dropped interrupt"]
pub type ISOODRP_R = crate::BitReader;
#[doc = "Field `ISOODRP` writer - Isochronous OUT packet dropped interrupt"]
pub type ISOODRP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `EOPF` reader - End of periodic frame interrupt"]
pub type EOPF_R = crate::BitReader;
#[doc = "Field `EOPF` writer - End of periodic frame interrupt"]
pub type EOPF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `IEPINT` reader - IN endpoint interrupt"]
pub type IEPINT_R = crate::BitReader;
#[doc = "Field `OEPINT` reader - OUT endpoint interrupt"]
pub type OEPINT_R = crate::BitReader;
#[doc = "Field `IISOIXFR` reader - Incomplete isochronous IN transfer"]
pub type IISOIXFR_R = crate::BitReader;
#[doc = "Field `IISOIXFR` writer - Incomplete isochronous IN transfer"]
pub type IISOIXFR_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `IPXFR_INCOMPISOOUT` reader - Incomplete periodic transfer(Host mode)/Incomplete isochronous OUT transfer(Device mode)"]
pub type IPXFR_INCOMPISOOUT_R = crate::BitReader;
#[doc = "Field `IPXFR_INCOMPISOOUT` writer - Incomplete periodic transfer(Host mode)/Incomplete isochronous OUT transfer(Device mode)"]
pub type IPXFR_INCOMPISOOUT_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RSTDET` reader - Reset detected interrupt"]
pub type RSTDET_R = crate::BitReader;
#[doc = "Field `RSTDET` writer - Reset detected interrupt"]
pub type RSTDET_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `HPRTINT` reader - Host port interrupt"]
pub type HPRTINT_R = crate::BitReader;
#[doc = "Field `HCINT` reader - Host channels interrupt"]
pub type HCINT_R = crate::BitReader;
#[doc = "Field `PTXFE` reader - Periodic TxFIFO empty"]
pub type PTXFE_R = crate::BitReader;
#[doc = "Field `CIDSCHG` reader - Connector ID status change"]
pub type CIDSCHG_R = crate::BitReader;
#[doc = "Field `CIDSCHG` writer - Connector ID status change"]
pub type CIDSCHG_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `DISCINT` reader - Disconnect detected interrupt"]
pub type DISCINT_R = crate::BitReader;
#[doc = "Field `DISCINT` writer - Disconnect detected interrupt"]
pub type DISCINT_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SRQINT` reader - Session request/new session detected interrupt"]
pub type SRQINT_R = crate::BitReader;
#[doc = "Field `SRQINT` writer - Session request/new session detected interrupt"]
pub type SRQINT_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `WKUPINT` reader - Resume/remote wakeup detected interrupt"]
pub type WKUPINT_R = crate::BitReader;
#[doc = "Field `WKUPINT` writer - Resume/remote wakeup detected interrupt"]
pub type WKUPINT_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - Current mode of operation"]
#[inline(always)]
pub fn cmod(&self) -> CMOD_R {
CMOD_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - Mode mismatch interrupt"]
#[inline(always)]
pub fn mmis(&self) -> MMIS_R {
MMIS_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - OTG interrupt"]
#[inline(always)]
pub fn otgint(&self) -> OTGINT_R {
OTGINT_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - Start of frame"]
#[inline(always)]
pub fn sof(&self) -> SOF_R {
SOF_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - RxFIFO non-empty"]
#[inline(always)]
pub fn rxflvl(&self) -> RXFLVL_R {
RXFLVL_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - Non-periodic TxFIFO empty"]
#[inline(always)]
pub fn nptxfe(&self) -> NPTXFE_R {
NPTXFE_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 6 - Global IN non-periodic NAK effective"]
#[inline(always)]
pub fn ginakeff(&self) -> GINAKEFF_R {
GINAKEFF_R::new(((self.bits >> 6) & 1) != 0)
}
#[doc = "Bit 7 - Global OUT NAK effective"]
#[inline(always)]
pub fn goutnakeff(&self) -> GOUTNAKEFF_R {
GOUTNAKEFF_R::new(((self.bits >> 7) & 1) != 0)
}
#[doc = "Bit 10 - Early suspend"]
#[inline(always)]
pub fn esusp(&self) -> ESUSP_R {
ESUSP_R::new(((self.bits >> 10) & 1) != 0)
}
#[doc = "Bit 11 - USB suspend"]
#[inline(always)]
pub fn usbsusp(&self) -> USBSUSP_R {
USBSUSP_R::new(((self.bits >> 11) & 1) != 0)
}
#[doc = "Bit 12 - USB reset"]
#[inline(always)]
pub fn usbrst(&self) -> USBRST_R {
USBRST_R::new(((self.bits >> 12) & 1) != 0)
}
#[doc = "Bit 13 - Enumeration done"]
#[inline(always)]
pub fn enumdne(&self) -> ENUMDNE_R {
ENUMDNE_R::new(((self.bits >> 13) & 1) != 0)
}
#[doc = "Bit 14 - Isochronous OUT packet dropped interrupt"]
#[inline(always)]
pub fn isoodrp(&self) -> ISOODRP_R {
ISOODRP_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bit 15 - End of periodic frame interrupt"]
#[inline(always)]
pub fn eopf(&self) -> EOPF_R {
EOPF_R::new(((self.bits >> 15) & 1) != 0)
}
#[doc = "Bit 18 - IN endpoint interrupt"]
#[inline(always)]
pub fn iepint(&self) -> IEPINT_R {
IEPINT_R::new(((self.bits >> 18) & 1) != 0)
}
#[doc = "Bit 19 - OUT endpoint interrupt"]
#[inline(always)]
pub fn oepint(&self) -> OEPINT_R {
OEPINT_R::new(((self.bits >> 19) & 1) != 0)
}
#[doc = "Bit 20 - Incomplete isochronous IN transfer"]
#[inline(always)]
pub fn iisoixfr(&self) -> IISOIXFR_R {
IISOIXFR_R::new(((self.bits >> 20) & 1) != 0)
}
#[doc = "Bit 21 - Incomplete periodic transfer(Host mode)/Incomplete isochronous OUT transfer(Device mode)"]
#[inline(always)]
pub fn ipxfr_incompisoout(&self) -> IPXFR_INCOMPISOOUT_R {
IPXFR_INCOMPISOOUT_R::new(((self.bits >> 21) & 1) != 0)
}
#[doc = "Bit 23 - Reset detected interrupt"]
#[inline(always)]
pub fn rstdet(&self) -> RSTDET_R {
RSTDET_R::new(((self.bits >> 23) & 1) != 0)
}
#[doc = "Bit 24 - Host port interrupt"]
#[inline(always)]
pub fn hprtint(&self) -> HPRTINT_R {
HPRTINT_R::new(((self.bits >> 24) & 1) != 0)
}
#[doc = "Bit 25 - Host channels interrupt"]
#[inline(always)]
pub fn hcint(&self) -> HCINT_R {
HCINT_R::new(((self.bits >> 25) & 1) != 0)
}
#[doc = "Bit 26 - Periodic TxFIFO empty"]
#[inline(always)]
pub fn ptxfe(&self) -> PTXFE_R {
PTXFE_R::new(((self.bits >> 26) & 1) != 0)
}
#[doc = "Bit 28 - Connector ID status change"]
#[inline(always)]
pub fn cidschg(&self) -> CIDSCHG_R {
CIDSCHG_R::new(((self.bits >> 28) & 1) != 0)
}
#[doc = "Bit 29 - Disconnect detected interrupt"]
#[inline(always)]
pub fn discint(&self) -> DISCINT_R {
DISCINT_R::new(((self.bits >> 29) & 1) != 0)
}
#[doc = "Bit 30 - Session request/new session detected interrupt"]
#[inline(always)]
pub fn srqint(&self) -> SRQINT_R {
SRQINT_R::new(((self.bits >> 30) & 1) != 0)
}
#[doc = "Bit 31 - Resume/remote wakeup detected interrupt"]
#[inline(always)]
pub fn wkupint(&self) -> WKUPINT_R {
WKUPINT_R::new(((self.bits >> 31) & 1) != 0)
}
}
impl W {
#[doc = "Bit 1 - Mode mismatch interrupt"]
#[inline(always)]
#[must_use]
pub fn mmis(&mut self) -> MMIS_W<GINTSTS_SPEC, 1> {
MMIS_W::new(self)
}
#[doc = "Bit 3 - Start of frame"]
#[inline(always)]
#[must_use]
pub fn sof(&mut self) -> SOF_W<GINTSTS_SPEC, 3> {
SOF_W::new(self)
}
#[doc = "Bit 10 - Early suspend"]
#[inline(always)]
#[must_use]
pub fn esusp(&mut self) -> ESUSP_W<GINTSTS_SPEC, 10> {
ESUSP_W::new(self)
}
#[doc = "Bit 11 - USB suspend"]
#[inline(always)]
#[must_use]
pub fn usbsusp(&mut self) -> USBSUSP_W<GINTSTS_SPEC, 11> {
USBSUSP_W::new(self)
}
#[doc = "Bit 12 - USB reset"]
#[inline(always)]
#[must_use]
pub fn usbrst(&mut self) -> USBRST_W<GINTSTS_SPEC, 12> {
USBRST_W::new(self)
}
#[doc = "Bit 13 - Enumeration done"]
#[inline(always)]
#[must_use]
pub fn enumdne(&mut self) -> ENUMDNE_W<GINTSTS_SPEC, 13> {
ENUMDNE_W::new(self)
}
#[doc = "Bit 14 - Isochronous OUT packet dropped interrupt"]
#[inline(always)]
#[must_use]
pub fn isoodrp(&mut self) -> ISOODRP_W<GINTSTS_SPEC, 14> {
ISOODRP_W::new(self)
}
#[doc = "Bit 15 - End of periodic frame interrupt"]
#[inline(always)]
#[must_use]
pub fn eopf(&mut self) -> EOPF_W<GINTSTS_SPEC, 15> {
EOPF_W::new(self)
}
#[doc = "Bit 20 - Incomplete isochronous IN transfer"]
#[inline(always)]
#[must_use]
pub fn iisoixfr(&mut self) -> IISOIXFR_W<GINTSTS_SPEC, 20> {
IISOIXFR_W::new(self)
}
#[doc = "Bit 21 - Incomplete periodic transfer(Host mode)/Incomplete isochronous OUT transfer(Device mode)"]
#[inline(always)]
#[must_use]
pub fn ipxfr_incompisoout(&mut self) -> IPXFR_INCOMPISOOUT_W<GINTSTS_SPEC, 21> {
IPXFR_INCOMPISOOUT_W::new(self)
}
#[doc = "Bit 23 - Reset detected interrupt"]
#[inline(always)]
#[must_use]
pub fn rstdet(&mut self) -> RSTDET_W<GINTSTS_SPEC, 23> {
RSTDET_W::new(self)
}
#[doc = "Bit 28 - Connector ID status change"]
#[inline(always)]
#[must_use]
pub fn cidschg(&mut self) -> CIDSCHG_W<GINTSTS_SPEC, 28> {
CIDSCHG_W::new(self)
}
#[doc = "Bit 29 - Disconnect detected interrupt"]
#[inline(always)]
#[must_use]
pub fn discint(&mut self) -> DISCINT_W<GINTSTS_SPEC, 29> {
DISCINT_W::new(self)
}
#[doc = "Bit 30 - Session request/new session detected interrupt"]
#[inline(always)]
#[must_use]
pub fn srqint(&mut self) -> SRQINT_W<GINTSTS_SPEC, 30> {
SRQINT_W::new(self)
}
#[doc = "Bit 31 - Resume/remote wakeup detected interrupt"]
#[inline(always)]
#[must_use]
pub fn wkupint(&mut self) -> WKUPINT_W<GINTSTS_SPEC, 31> {
WKUPINT_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 = "OTG_FS core interrupt register (OTG_FS_GINTSTS)\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`gintsts::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 [`gintsts::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct GINTSTS_SPEC;
impl crate::RegisterSpec for GINTSTS_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`gintsts::R`](R) reader structure"]
impl crate::Readable for GINTSTS_SPEC {}
#[doc = "`write(|w| ..)` method takes [`gintsts::W`](W) writer structure"]
impl crate::Writable for GINTSTS_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets GINTSTS to value 0x0400_0020"]
impl crate::Resettable for GINTSTS_SPEC {
const RESET_VALUE: Self::Ux = 0x0400_0020;
}
|
//! Small program that convert uint to hex (and vice versa)
#![warn(
missing_docs,
absolute_paths_not_starting_with_crate,
anonymous_parameters,
box_pointers,
clashing_extern_declarations,
deprecated_in_future,
elided_lifetimes_in_paths,
explicit_outlives_requirements,
indirect_structural_match,
keyword_idents,
macro_use_extern_crate,
meta_variable_misuse,
missing_copy_implementations,
missing_crate_level_docs,
missing_debug_implementations,
missing_doc_code_examples,
non_ascii_idents,
private_doc_tests,
single_use_lifetimes,
trivial_casts,
trivial_numeric_casts,
unaligned_references,
unreachable_pub,
unsafe_code,
unstable_features,
unused_crate_dependencies,
unused_extern_crates,
unused_import_braces,
unused_lifetimes,
unused_qualifications,
unused_results,
variant_size_differences
)] // unsafe_op_in_unsafe_fn is unstable
#![warn(clippy::all)]
/// Convert a String from UInt to hex format OR from Hex to Int format
///
/// Example:
/// ```
/// let res = hex_uint_converter::convert_uint_or_hex("1").unwrap();
/// ```
pub fn convert_uint_or_hex(str_to_parse: &str) -> Result<String, String> {
if str_to_parse.contains("0x") {
// Try to parse Hex to Int
let formated_str = str_to_parse.trim_start_matches("0x");
let number = match u128::from_str_radix(&formated_str, 16) {
Ok(n) => n,
Err(_) => {
return Err(format!(
"Error, the value {:?} is not an hexadecimal value!",
str_to_parse
))
}
};
Ok(number.to_string())
} else {
// Try to parse Int to Hex
let number: u128 = match str_to_parse.parse() {
Ok(n) => n,
Err(_) => {
return Err(format!(
"Error, the value {:?} is not an unsigned integer!",
str_to_parse
))
}
};
Ok(format!("0x{:x}", number))
}
}
#[test]
fn basic_tests() {
assert_eq!(convert_uint_or_hex("1").unwrap(), "0x1");
assert_eq!(convert_uint_or_hex("0x1").unwrap(), "1");
assert_eq!(convert_uint_or_hex("0xF").unwrap(), "15");
assert_eq!(convert_uint_or_hex("15").unwrap(), "0xf");
assert_eq!(convert_uint_or_hex("bad_value").is_err(), true);
assert_eq!(convert_uint_or_hex("0xbad_value").is_err(), true);
}
|
#![cfg_attr(test, feature(test))]
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
use bytes::Bytes;
mod byte_buffer;
mod compression_type;
mod encoding_type;
mod error;
mod node;
mod node_types;
mod options;
mod printer;
mod reader;
mod sixbit;
mod text_reader;
mod to_text_xml;
mod types;
mod value;
mod writer;
use crate::error::Result;
use crate::text_reader::TextXmlReader;
use crate::to_text_xml::TextXmlWriter;
// Public exports
pub use crate::compression_type::CompressionType;
pub use crate::encoding_type::EncodingType;
pub use crate::error::KbinError;
pub use crate::node::{Node, NodeCollection};
pub use crate::node_types::StandardType;
pub use crate::options::{Options, OptionsBuilder};
pub use crate::printer::Printer;
pub use crate::reader::Reader;
pub use crate::to_text_xml::ToTextXml;
pub use crate::value::{Value, ValueArray};
pub use crate::writer::{Writeable, Writer};
const SIGNATURE: u8 = 0xA0;
const SIG_COMPRESSED: u8 = 0x42;
const SIG_UNCOMPRESSED: u8 = 0x45;
const ARRAY_MASK: u8 = 1 << 6; // 1 << 6 = 64
pub fn is_binary_xml(input: &[u8]) -> bool {
input.len() > 2 &&
input[0] == SIGNATURE &&
(input[1] == SIG_COMPRESSED || input[1] == SIG_UNCOMPRESSED)
}
pub fn from_binary(input: Bytes) -> Result<(NodeCollection, EncodingType)> {
let reader = Reader::new(input)?;
let encoding = reader.encoding();
let collection = reader
.collect::<Option<_>>()
.ok_or(KbinError::NoNodeCollection)?;
Ok((collection, encoding))
}
pub fn from_text_xml(input: &[u8]) -> Result<(NodeCollection, EncodingType)> {
let mut reader = TextXmlReader::new(input);
let collection = reader
.as_node_collection()?
.ok_or(KbinError::NoNodeCollection)?;
let encoding = reader.encoding();
Ok((collection, encoding))
}
pub fn from_bytes(input: Bytes) -> Result<(NodeCollection, EncodingType)> {
if is_binary_xml(&input) {
from_binary(input)
} else {
from_text_xml(&input)
}
}
#[inline]
pub fn from_slice(input: &[u8]) -> Result<(NodeCollection, EncodingType)> {
from_binary(Bytes::from(input.to_vec()))
}
pub fn to_binary<T>(input: &T) -> Result<Vec<u8>>
where
T: Writeable,
{
let mut writer = Writer::new();
writer.to_binary(input).map_err(Into::into)
}
pub fn to_binary_with_options<T>(options: Options, input: &T) -> Result<Vec<u8>>
where
T: Writeable,
{
let mut writer = Writer::with_options(options);
writer.to_binary(input).map_err(Into::into)
}
pub fn to_text_xml<T>(input: &T) -> Result<Vec<u8>>
where
T: ToTextXml,
{
let writer = TextXmlWriter::new();
writer.into_text_xml(input)
}
|
use std::{self, env, fs};
mod parking_lot;
enum Mode {
File,
Interactive,
}
fn main() {
let args: Vec<String> = env::args().collect();
let mode = if args.len() == 1 {
Mode::Interactive
} else {
Mode::File
};
let mut parking = parking_lot::ParkingLot::new();
match mode {
Mode::Interactive => loop {
let mut command = String::new();
std::io::stdin().read_line(&mut command).unwrap();
println!("{}", parking_lot::stringify(parking.repl(&command)));
},
Mode::File => {
let contents =
fs::read_to_string(&args[1]).expect("Something went wrong reading the file");
for command in contents.lines() {
println!("\ncommand: '{}'", command);
println!("{}", parking_lot::stringify(parking.repl(&command)));
}
}
}
}
|
struct Solution;
impl Solution {
pub fn valid_mountain_array(a: Vec<i32>) -> bool {
let n = a.len();
if n < 3 {
return false;
}
let mut idx = 0;
// 递增
while idx + 1 < n && a[idx] < a[idx + 1] {
idx += 1;
}
// 最高点不能是数组的第一个位置或最后一个位置
if idx == 0 || idx == n - 1 {
return false;
}
// 递减
while idx + 1 < n && a[idx] > a[idx + 1] {
idx += 1;
}
idx + 1 == n
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_valid_mountain_array() {
assert_eq!(Solution::valid_mountain_array(vec![2, 1]), false);
assert_eq!(Solution::valid_mountain_array(vec![3, 5, 5]), false);
assert_eq!(Solution::valid_mountain_array(vec![0, 3, 2, 1]), true);
}
}
|
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 5