text stringlengths 8 4.13M |
|---|
use failure;
use pnet_packet::ip::IpNextHeaderProtocols::{Icmp, Tcp, Udp};
use serde::{Deserialize, Deserializer};
use serde_json;
use std::convert::From;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::net::IpAddr;
use std::path::Path;
/// Connection state for a flow
#[derive(Debug, Deserialize)]
pub enum ConnState {
/// Connection attempt seen, no reply.
S0,
/// Connection established, not terminated.
S1,
/// Normal establishment and termination. Note
/// that this is the same symbol as for state S1.
/// You can tell the two apart because for S1 there
/// will not be any byte counts in the summary, while
/// for SF there will be.
SF,
/// Connection attempt rejected.
REJ,
/// Connection established and close attempt by originator
/// seen (but no reply from responder).
S2,
/// Connection established and close attempt by responder seen
/// (but no reply from originator).
S3,
/// Connection established, originator aborted (sent a RST).
RSTO,
/// Responder sent a RST.
RSTR,
/// Originator sent a SYN followed by a RST, we never saw a
/// SYN-ACK from the responder.
RSTOS0,
/// Responder sent a SYN ACK followed by a RST, we never saw
/// a SYN from the (purported) originator.
RSTRH,
/// Originator sent a SYN followed by a FIN, we never saw a
/// SYN ACK from the responder (hence the connection was “half” open).
SH,
/// Responder sent a SYN ACK followed by a FIN, we never saw
/// a SYN from the originator.
SHR,
/// No SYN seen, just midstream traffic (a “partial connection”
/// that was not later closed).
OTH,
/// Unknown. used as a default
UNK,
}
impl Default for ConnState {
/// Returns a default state
fn default() -> Self {
ConnState::UNK
}
}
/// History entry for connection state
#[derive(Debug, PartialEq)]
pub enum HistoryEntry {
/// s a SYN w/o the ACK bit set
Syn,
/// h a SYN+ACK (“handshake”)
Handshake,
/// a a pure ACK
Ack,
/// d packet with payload (“data”)
Data,
/// f packet with FIN bit set
Fin,
/// r packet with RST bit set
Rst,
/// c packet with a bad checksum
BadChecksum,
/// t packet with retransmitted payload
Retransmit,
/// i inconsistent packet (e.g. FIN+RST bits set)
Inconsistent,
/// q multi-flag packet (SYN+FIN or SYN+RST bits set)
MultiFlag,
/// ^ connection direction was flipped by Bro’s heuristic
DirectionFlipped,
// Used so we have something to use for invalid input
Unknown,
}
impl From<char> for HistoryEntry {
/// Parses a char into a HistoryEntry
fn from(c: char) -> Self {
match c {
's' => HistoryEntry::Syn,
'h' => HistoryEntry::Handshake,
'a' => HistoryEntry::Ack,
'd' => HistoryEntry::Data,
'f' => HistoryEntry::Fin,
'r' => HistoryEntry::Rst,
'c' => HistoryEntry::BadChecksum,
't' => HistoryEntry::Retransmit,
'i' => HistoryEntry::Inconsistent,
'q' => HistoryEntry::MultiFlag,
'^' => HistoryEntry::DirectionFlipped,
_ => HistoryEntry::Unknown,
}
}
}
/// Represents a transport protocol, as supported by Bro
#[derive(Debug, Deserialize)]
pub enum TransportProtocol {
/// An unknown transport-layer protocol.
#[serde(rename = "unknown_transport")]
Unknown,
/// TCP
#[serde(rename = "tcp")]
Tcp,
/// UDP
#[serde(rename = "udp")]
Udp,
/// ICMP
#[serde(rename = "icmp")]
Icmp,
}
impl TransportProtocol {
/// Returns the IP nextProtocol code for a transport protocol
pub fn code(&self) -> u8 {
match *self {
TransportProtocol::Unknown => 0x00,
TransportProtocol::Tcp => Tcp.0,
TransportProtocol::Udp => Udp.0,
TransportProtocol::Icmp => Icmp.0,
}
}
}
/// Used to deserialize a floating-point timestamp (in seconds) as an integer timestamp (in
/// nanoseconds)
pub fn parse_bro_timestamp<'de, D>(deserializer: D) -> Result<u64, D::Error>
where
D: Deserializer<'de>,
{
// Get the time as a float in seconds
// Multiply by 1M to convert to microseconds
// This is the default accuracy of bro
let microseconds = f64::deserialize(deserializer)? * 1e6;
// Convert into an integer, and multiply to get nanoseconds
Ok((microseconds as u64) * 1000)
}
#[derive(Debug, Deserialize)]
pub struct Connection {
#[serde(rename = "ts")]
#[serde(deserialize_with = "parse_bro_timestamp")]
pub timestamp: u64,
pub uid: String,
#[serde(rename = "id.orig_h")]
pub orig_ip: IpAddr,
#[serde(rename = "id.resp_h")]
pub resp_ip: IpAddr,
#[serde(rename = "id.orig_p")]
pub orig_port: u16,
#[serde(rename = "id.resp_p")]
pub resp_port: u16,
#[serde(rename = "proto")]
pub trans_protocol: TransportProtocol,
pub service: Option<String>,
#[serde(deserialize_with = "parse_bro_timestamp")]
#[serde(default)]
pub duration: u64,
pub orig_bytes: Option<i64>,
pub resp_bytes: Option<i64>,
pub conn_state: Option<ConnState>,
pub missed_bytes: Option<i64>,
#[serde(default)]
pub history: String,
pub orig_pkts: Option<i64>,
pub orig_ip_bytes: Option<i64>,
pub resp_pkts: Option<i64>,
pub resp_ip_bytes: Option<i64>,
}
impl Connection {
pub fn load_connections(
path: &Path,
) -> Result<impl Iterator<Item = Connection>, failure::Error> {
// Open the connection log
let conn_log_file: File = File::open(path)?;
let conn_log_reader = BufReader::new(conn_log_file);
// Parse each line
let connections = conn_log_reader.lines().flatten().flat_map(|line| {
// Parse the line as json
serde_json::from_str(&line)
});
Ok(connections)
}
}
|
//! Utilities for using `hyper` with `runtime`.
use futures::prelude::*;
use super::tokio02_ext::Compat as Tokio02Compat;
use futures::task::Poll;
use hyper::server::accept::Accept;
use hyper::Server;
use runtime::net::{TcpListener, TcpStream};
use runtime::task::Spawner;
use std::net::SocketAddr;
use std::pin::Pin;
#[derive(Debug)]
pub struct AddrIncoming {
inner: TcpListener,
}
impl Accept for AddrIncoming {
type Conn = Tokio02Compat<TcpStream>;
type Error = std::io::Error;
fn poll_accept(
self: Pin<&mut Self>,
cx: &mut futures::task::Context<'_>,
) -> Poll<Option<Result<Self::Conn, Self::Error>>> {
Pin::new(&mut self.get_mut().inner.incoming())
.poll_next(cx)
.map(|x| x.map(|x| x.map(Tokio02Compat)))
}
}
pub trait ServerBindExt {
type Builder;
/// Binds to the provided address, and returns a [`Builder`](Builder).
///
/// # Panics
///
/// This method will panic if binding to the address fails.
fn bind2(addr: &SocketAddr) -> Self::Builder;
fn bind2_mut(addr: &mut SocketAddr) -> Self::Builder;
}
impl ServerBindExt for Server<AddrIncoming, ()> {
type Builder = hyper::server::Builder<AddrIncoming, Tokio02Compat<Spawner>>;
fn bind2(addr: &SocketAddr) -> Self::Builder {
let incoming = TcpListener::bind(addr).unwrap_or_else(|e| {
panic!("error binding to {}: {}", addr, e);
});
Server::builder(AddrIncoming { inner: incoming })
.executor(Tokio02Compat::new(Spawner::new()))
}
fn bind2_mut(addr: &mut SocketAddr) -> Self::Builder {
let incoming = TcpListener::bind(&*addr).unwrap_or_else(|e| {
panic!("error binding to {}: {}", addr, e);
});
if let Ok(l_addr) = incoming.local_addr() {
*addr = l_addr;
}
Server::builder(AddrIncoming { inner: incoming })
.executor(Tokio02Compat::new(Spawner::new()))
}
}
|
// Long string literals
fn main() -> &'static str {
let str = "AAAAAAAAAAAAAAaAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAaAA \
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAaAa";
let str = "AAAAAAAAAAAAAAaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAaAAAAAAAAAAAAAAAAAAAAAA\
AAAAAAAAAAAaAa";
let str = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
let too_many_lines = "Hello";
// Make sure we don't break after an escape character.
let odd_length_name = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\
\n\n";
let even_length_name = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\
\n\n\n";
let really_long_variable_name = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
"stuff"
}
|
#[doc = "PPU region address 0 (slave structure)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [addr0](addr0) module"]
pub type ADDR0 = crate::Reg<u32, _ADDR0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _ADDR0;
#[doc = "`read()` method returns [addr0::R](addr0::R) reader structure"]
impl crate::Readable for ADDR0 {}
#[doc = "`write(|w| ..)` method takes [addr0::W](addr0::W) writer structure"]
impl crate::Writable for ADDR0 {}
#[doc = "PPU region address 0 (slave structure)"]
pub mod addr0;
#[doc = "PPU region attributes 0 (slave structure)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [att0](att0) module"]
pub type ATT0 = crate::Reg<u32, _ATT0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _ATT0;
#[doc = "`read()` method returns [att0::R](att0::R) reader structure"]
impl crate::Readable for ATT0 {}
#[doc = "`write(|w| ..)` method takes [att0::W](att0::W) writer structure"]
impl crate::Writable for ATT0 {}
#[doc = "PPU region attributes 0 (slave structure)"]
pub mod att0;
#[doc = "PPU region address 1 (master structure)\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [addr1](addr1) module"]
pub type ADDR1 = crate::Reg<u32, _ADDR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _ADDR1;
#[doc = "`read()` method returns [addr1::R](addr1::R) reader structure"]
impl crate::Readable for ADDR1 {}
#[doc = "PPU region address 1 (master structure)"]
pub mod addr1;
#[doc = "PPU region attributes 1 (master structure)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [att1](att1) module"]
pub type ATT1 = crate::Reg<u32, _ATT1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _ATT1;
#[doc = "`read()` method returns [att1::R](att1::R) reader structure"]
impl crate::Readable for ATT1 {}
#[doc = "`write(|w| ..)` method takes [att1::W](att1::W) writer structure"]
impl crate::Writable for ATT1 {}
#[doc = "PPU region attributes 1 (master structure)"]
pub mod att1;
|
// Copyright 2019 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Generated using ./xlib_generator.sh
#[link(name = "X11")]
extern "C" {}
#[link(name = "Xext")]
extern "C" {}
/* automatically generated by rust-bindgen */
pub const ExposureMask: u32 = 32768;
pub const Expose: u32 = 12;
pub const ClientMessage: u32 = 33;
pub const ZPixmap: u32 = 2;
pub const PMinSize: u32 = 16;
pub const PMaxSize: u32 = 32;
pub const VisualScreenMask: u32 = 2;
pub const VisualDepthMask: u32 = 4;
pub const VisualRedMaskMask: u32 = 16;
pub const VisualGreenMaskMask: u32 = 32;
pub const VisualBlueMaskMask: u32 = 64;
pub const ShmCompletion: u32 = 0;
pub type XID = ::std::os::raw::c_ulong;
pub type Atom = ::std::os::raw::c_ulong;
pub type VisualID = ::std::os::raw::c_ulong;
pub type Time = ::std::os::raw::c_ulong;
pub type Window = XID;
pub type Drawable = XID;
pub type Font = XID;
pub type Pixmap = XID;
pub type Colormap = XID;
pub type XPointer = *mut ::std::os::raw::c_char;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct _XExtData {
pub number: ::std::os::raw::c_int,
pub next: *mut _XExtData,
pub free_private: ::std::option::Option<
unsafe extern "C" fn(extension: *mut _XExtData) -> ::std::os::raw::c_int,
>,
pub private_data: XPointer,
}
pub type XExtData = _XExtData;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct XGCValues {
pub function: ::std::os::raw::c_int,
pub plane_mask: ::std::os::raw::c_ulong,
pub foreground: ::std::os::raw::c_ulong,
pub background: ::std::os::raw::c_ulong,
pub line_width: ::std::os::raw::c_int,
pub line_style: ::std::os::raw::c_int,
pub cap_style: ::std::os::raw::c_int,
pub join_style: ::std::os::raw::c_int,
pub fill_style: ::std::os::raw::c_int,
pub fill_rule: ::std::os::raw::c_int,
pub arc_mode: ::std::os::raw::c_int,
pub tile: Pixmap,
pub stipple: Pixmap,
pub ts_x_origin: ::std::os::raw::c_int,
pub ts_y_origin: ::std::os::raw::c_int,
pub font: Font,
pub subwindow_mode: ::std::os::raw::c_int,
pub graphics_exposures: ::std::os::raw::c_int,
pub clip_x_origin: ::std::os::raw::c_int,
pub clip_y_origin: ::std::os::raw::c_int,
pub clip_mask: Pixmap,
pub dash_offset: ::std::os::raw::c_int,
pub dashes: ::std::os::raw::c_char,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct _XGC {
_unused: [u8; 0],
}
pub type GC = *mut _XGC;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct Visual {
pub ext_data: *mut XExtData,
pub visualid: VisualID,
pub class: ::std::os::raw::c_int,
pub red_mask: ::std::os::raw::c_ulong,
pub green_mask: ::std::os::raw::c_ulong,
pub blue_mask: ::std::os::raw::c_ulong,
pub bits_per_rgb: ::std::os::raw::c_int,
pub map_entries: ::std::os::raw::c_int,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct Depth {
pub depth: ::std::os::raw::c_int,
pub nvisuals: ::std::os::raw::c_int,
pub visuals: *mut Visual,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct _XDisplay {
_unused: [u8; 0],
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct Screen {
pub ext_data: *mut XExtData,
pub display: *mut _XDisplay,
pub root: Window,
pub width: ::std::os::raw::c_int,
pub height: ::std::os::raw::c_int,
pub mwidth: ::std::os::raw::c_int,
pub mheight: ::std::os::raw::c_int,
pub ndepths: ::std::os::raw::c_int,
pub depths: *mut Depth,
pub root_depth: ::std::os::raw::c_int,
pub root_visual: *mut Visual,
pub default_gc: GC,
pub cmap: Colormap,
pub white_pixel: ::std::os::raw::c_ulong,
pub black_pixel: ::std::os::raw::c_ulong,
pub max_maps: ::std::os::raw::c_int,
pub min_maps: ::std::os::raw::c_int,
pub backing_store: ::std::os::raw::c_int,
pub save_unders: ::std::os::raw::c_int,
pub root_input_mask: ::std::os::raw::c_long,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct _XImage {
pub width: ::std::os::raw::c_int,
pub height: ::std::os::raw::c_int,
pub xoffset: ::std::os::raw::c_int,
pub format: ::std::os::raw::c_int,
pub data: *mut ::std::os::raw::c_char,
pub byte_order: ::std::os::raw::c_int,
pub bitmap_unit: ::std::os::raw::c_int,
pub bitmap_bit_order: ::std::os::raw::c_int,
pub bitmap_pad: ::std::os::raw::c_int,
pub depth: ::std::os::raw::c_int,
pub bytes_per_line: ::std::os::raw::c_int,
pub bits_per_pixel: ::std::os::raw::c_int,
pub red_mask: ::std::os::raw::c_ulong,
pub green_mask: ::std::os::raw::c_ulong,
pub blue_mask: ::std::os::raw::c_ulong,
pub obdata: XPointer,
pub f: _XImage_funcs,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct _XImage_funcs {
pub create_image: ::std::option::Option<
unsafe extern "C" fn(
arg1: *mut _XDisplay,
arg2: *mut Visual,
arg3: ::std::os::raw::c_uint,
arg4: ::std::os::raw::c_int,
arg5: ::std::os::raw::c_int,
arg6: *mut ::std::os::raw::c_char,
arg7: ::std::os::raw::c_uint,
arg8: ::std::os::raw::c_uint,
arg9: ::std::os::raw::c_int,
arg10: ::std::os::raw::c_int,
) -> *mut _XImage,
>,
pub destroy_image:
::std::option::Option<unsafe extern "C" fn(arg1: *mut _XImage) -> ::std::os::raw::c_int>,
pub get_pixel: ::std::option::Option<
unsafe extern "C" fn(
arg1: *mut _XImage,
arg2: ::std::os::raw::c_int,
arg3: ::std::os::raw::c_int,
) -> ::std::os::raw::c_ulong,
>,
pub put_pixel: ::std::option::Option<
unsafe extern "C" fn(
arg1: *mut _XImage,
arg2: ::std::os::raw::c_int,
arg3: ::std::os::raw::c_int,
arg4: ::std::os::raw::c_ulong,
) -> ::std::os::raw::c_int,
>,
pub sub_image: ::std::option::Option<
unsafe extern "C" fn(
arg1: *mut _XImage,
arg2: ::std::os::raw::c_int,
arg3: ::std::os::raw::c_int,
arg4: ::std::os::raw::c_uint,
arg5: ::std::os::raw::c_uint,
) -> *mut _XImage,
>,
pub add_pixel: ::std::option::Option<
unsafe extern "C" fn(
arg1: *mut _XImage,
arg2: ::std::os::raw::c_long,
) -> ::std::os::raw::c_int,
>,
}
pub type XImage = _XImage;
pub type Display = _XDisplay;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct XKeyEvent {
pub type_: ::std::os::raw::c_int,
pub serial: ::std::os::raw::c_ulong,
pub send_event: ::std::os::raw::c_int,
pub display: *mut Display,
pub window: Window,
pub root: Window,
pub subwindow: Window,
pub time: Time,
pub x: ::std::os::raw::c_int,
pub y: ::std::os::raw::c_int,
pub x_root: ::std::os::raw::c_int,
pub y_root: ::std::os::raw::c_int,
pub state: ::std::os::raw::c_uint,
pub keycode: ::std::os::raw::c_uint,
pub same_screen: ::std::os::raw::c_int,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct XButtonEvent {
pub type_: ::std::os::raw::c_int,
pub serial: ::std::os::raw::c_ulong,
pub send_event: ::std::os::raw::c_int,
pub display: *mut Display,
pub window: Window,
pub root: Window,
pub subwindow: Window,
pub time: Time,
pub x: ::std::os::raw::c_int,
pub y: ::std::os::raw::c_int,
pub x_root: ::std::os::raw::c_int,
pub y_root: ::std::os::raw::c_int,
pub state: ::std::os::raw::c_uint,
pub button: ::std::os::raw::c_uint,
pub same_screen: ::std::os::raw::c_int,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct XMotionEvent {
pub type_: ::std::os::raw::c_int,
pub serial: ::std::os::raw::c_ulong,
pub send_event: ::std::os::raw::c_int,
pub display: *mut Display,
pub window: Window,
pub root: Window,
pub subwindow: Window,
pub time: Time,
pub x: ::std::os::raw::c_int,
pub y: ::std::os::raw::c_int,
pub x_root: ::std::os::raw::c_int,
pub y_root: ::std::os::raw::c_int,
pub state: ::std::os::raw::c_uint,
pub is_hint: ::std::os::raw::c_char,
pub same_screen: ::std::os::raw::c_int,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct XCrossingEvent {
pub type_: ::std::os::raw::c_int,
pub serial: ::std::os::raw::c_ulong,
pub send_event: ::std::os::raw::c_int,
pub display: *mut Display,
pub window: Window,
pub root: Window,
pub subwindow: Window,
pub time: Time,
pub x: ::std::os::raw::c_int,
pub y: ::std::os::raw::c_int,
pub x_root: ::std::os::raw::c_int,
pub y_root: ::std::os::raw::c_int,
pub mode: ::std::os::raw::c_int,
pub detail: ::std::os::raw::c_int,
pub same_screen: ::std::os::raw::c_int,
pub focus: ::std::os::raw::c_int,
pub state: ::std::os::raw::c_uint,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct XFocusChangeEvent {
pub type_: ::std::os::raw::c_int,
pub serial: ::std::os::raw::c_ulong,
pub send_event: ::std::os::raw::c_int,
pub display: *mut Display,
pub window: Window,
pub mode: ::std::os::raw::c_int,
pub detail: ::std::os::raw::c_int,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct XKeymapEvent {
pub type_: ::std::os::raw::c_int,
pub serial: ::std::os::raw::c_ulong,
pub send_event: ::std::os::raw::c_int,
pub display: *mut Display,
pub window: Window,
pub key_vector: [::std::os::raw::c_char; 32usize],
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct XExposeEvent {
pub type_: ::std::os::raw::c_int,
pub serial: ::std::os::raw::c_ulong,
pub send_event: ::std::os::raw::c_int,
pub display: *mut Display,
pub window: Window,
pub x: ::std::os::raw::c_int,
pub y: ::std::os::raw::c_int,
pub width: ::std::os::raw::c_int,
pub height: ::std::os::raw::c_int,
pub count: ::std::os::raw::c_int,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct XGraphicsExposeEvent {
pub type_: ::std::os::raw::c_int,
pub serial: ::std::os::raw::c_ulong,
pub send_event: ::std::os::raw::c_int,
pub display: *mut Display,
pub drawable: Drawable,
pub x: ::std::os::raw::c_int,
pub y: ::std::os::raw::c_int,
pub width: ::std::os::raw::c_int,
pub height: ::std::os::raw::c_int,
pub count: ::std::os::raw::c_int,
pub major_code: ::std::os::raw::c_int,
pub minor_code: ::std::os::raw::c_int,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct XNoExposeEvent {
pub type_: ::std::os::raw::c_int,
pub serial: ::std::os::raw::c_ulong,
pub send_event: ::std::os::raw::c_int,
pub display: *mut Display,
pub drawable: Drawable,
pub major_code: ::std::os::raw::c_int,
pub minor_code: ::std::os::raw::c_int,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct XVisibilityEvent {
pub type_: ::std::os::raw::c_int,
pub serial: ::std::os::raw::c_ulong,
pub send_event: ::std::os::raw::c_int,
pub display: *mut Display,
pub window: Window,
pub state: ::std::os::raw::c_int,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct XCreateWindowEvent {
pub type_: ::std::os::raw::c_int,
pub serial: ::std::os::raw::c_ulong,
pub send_event: ::std::os::raw::c_int,
pub display: *mut Display,
pub parent: Window,
pub window: Window,
pub x: ::std::os::raw::c_int,
pub y: ::std::os::raw::c_int,
pub width: ::std::os::raw::c_int,
pub height: ::std::os::raw::c_int,
pub border_width: ::std::os::raw::c_int,
pub override_redirect: ::std::os::raw::c_int,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct XDestroyWindowEvent {
pub type_: ::std::os::raw::c_int,
pub serial: ::std::os::raw::c_ulong,
pub send_event: ::std::os::raw::c_int,
pub display: *mut Display,
pub event: Window,
pub window: Window,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct XUnmapEvent {
pub type_: ::std::os::raw::c_int,
pub serial: ::std::os::raw::c_ulong,
pub send_event: ::std::os::raw::c_int,
pub display: *mut Display,
pub event: Window,
pub window: Window,
pub from_configure: ::std::os::raw::c_int,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct XMapEvent {
pub type_: ::std::os::raw::c_int,
pub serial: ::std::os::raw::c_ulong,
pub send_event: ::std::os::raw::c_int,
pub display: *mut Display,
pub event: Window,
pub window: Window,
pub override_redirect: ::std::os::raw::c_int,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct XMapRequestEvent {
pub type_: ::std::os::raw::c_int,
pub serial: ::std::os::raw::c_ulong,
pub send_event: ::std::os::raw::c_int,
pub display: *mut Display,
pub parent: Window,
pub window: Window,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct XReparentEvent {
pub type_: ::std::os::raw::c_int,
pub serial: ::std::os::raw::c_ulong,
pub send_event: ::std::os::raw::c_int,
pub display: *mut Display,
pub event: Window,
pub window: Window,
pub parent: Window,
pub x: ::std::os::raw::c_int,
pub y: ::std::os::raw::c_int,
pub override_redirect: ::std::os::raw::c_int,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct XConfigureEvent {
pub type_: ::std::os::raw::c_int,
pub serial: ::std::os::raw::c_ulong,
pub send_event: ::std::os::raw::c_int,
pub display: *mut Display,
pub event: Window,
pub window: Window,
pub x: ::std::os::raw::c_int,
pub y: ::std::os::raw::c_int,
pub width: ::std::os::raw::c_int,
pub height: ::std::os::raw::c_int,
pub border_width: ::std::os::raw::c_int,
pub above: Window,
pub override_redirect: ::std::os::raw::c_int,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct XGravityEvent {
pub type_: ::std::os::raw::c_int,
pub serial: ::std::os::raw::c_ulong,
pub send_event: ::std::os::raw::c_int,
pub display: *mut Display,
pub event: Window,
pub window: Window,
pub x: ::std::os::raw::c_int,
pub y: ::std::os::raw::c_int,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct XResizeRequestEvent {
pub type_: ::std::os::raw::c_int,
pub serial: ::std::os::raw::c_ulong,
pub send_event: ::std::os::raw::c_int,
pub display: *mut Display,
pub window: Window,
pub width: ::std::os::raw::c_int,
pub height: ::std::os::raw::c_int,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct XConfigureRequestEvent {
pub type_: ::std::os::raw::c_int,
pub serial: ::std::os::raw::c_ulong,
pub send_event: ::std::os::raw::c_int,
pub display: *mut Display,
pub parent: Window,
pub window: Window,
pub x: ::std::os::raw::c_int,
pub y: ::std::os::raw::c_int,
pub width: ::std::os::raw::c_int,
pub height: ::std::os::raw::c_int,
pub border_width: ::std::os::raw::c_int,
pub above: Window,
pub detail: ::std::os::raw::c_int,
pub value_mask: ::std::os::raw::c_ulong,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct XCirculateEvent {
pub type_: ::std::os::raw::c_int,
pub serial: ::std::os::raw::c_ulong,
pub send_event: ::std::os::raw::c_int,
pub display: *mut Display,
pub event: Window,
pub window: Window,
pub place: ::std::os::raw::c_int,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct XCirculateRequestEvent {
pub type_: ::std::os::raw::c_int,
pub serial: ::std::os::raw::c_ulong,
pub send_event: ::std::os::raw::c_int,
pub display: *mut Display,
pub parent: Window,
pub window: Window,
pub place: ::std::os::raw::c_int,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct XPropertyEvent {
pub type_: ::std::os::raw::c_int,
pub serial: ::std::os::raw::c_ulong,
pub send_event: ::std::os::raw::c_int,
pub display: *mut Display,
pub window: Window,
pub atom: Atom,
pub time: Time,
pub state: ::std::os::raw::c_int,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct XSelectionClearEvent {
pub type_: ::std::os::raw::c_int,
pub serial: ::std::os::raw::c_ulong,
pub send_event: ::std::os::raw::c_int,
pub display: *mut Display,
pub window: Window,
pub selection: Atom,
pub time: Time,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct XSelectionRequestEvent {
pub type_: ::std::os::raw::c_int,
pub serial: ::std::os::raw::c_ulong,
pub send_event: ::std::os::raw::c_int,
pub display: *mut Display,
pub owner: Window,
pub requestor: Window,
pub selection: Atom,
pub target: Atom,
pub property: Atom,
pub time: Time,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct XSelectionEvent {
pub type_: ::std::os::raw::c_int,
pub serial: ::std::os::raw::c_ulong,
pub send_event: ::std::os::raw::c_int,
pub display: *mut Display,
pub requestor: Window,
pub selection: Atom,
pub target: Atom,
pub property: Atom,
pub time: Time,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct XColormapEvent {
pub type_: ::std::os::raw::c_int,
pub serial: ::std::os::raw::c_ulong,
pub send_event: ::std::os::raw::c_int,
pub display: *mut Display,
pub window: Window,
pub colormap: Colormap,
pub new: ::std::os::raw::c_int,
pub state: ::std::os::raw::c_int,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct XClientMessageEvent {
pub type_: ::std::os::raw::c_int,
pub serial: ::std::os::raw::c_ulong,
pub send_event: ::std::os::raw::c_int,
pub display: *mut Display,
pub window: Window,
pub message_type: Atom,
pub format: ::std::os::raw::c_int,
pub data: XClientMessageEvent__bindgen_ty_1,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union XClientMessageEvent__bindgen_ty_1 {
pub b: [::std::os::raw::c_char; 20usize],
pub s: [::std::os::raw::c_short; 10usize],
pub l: [::std::os::raw::c_long; 5usize],
_bindgen_union_align: [u64; 5usize],
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct XMappingEvent {
pub type_: ::std::os::raw::c_int,
pub serial: ::std::os::raw::c_ulong,
pub send_event: ::std::os::raw::c_int,
pub display: *mut Display,
pub window: Window,
pub request: ::std::os::raw::c_int,
pub first_keycode: ::std::os::raw::c_int,
pub count: ::std::os::raw::c_int,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct XErrorEvent {
pub type_: ::std::os::raw::c_int,
pub display: *mut Display,
pub resourceid: XID,
pub serial: ::std::os::raw::c_ulong,
pub error_code: ::std::os::raw::c_uchar,
pub request_code: ::std::os::raw::c_uchar,
pub minor_code: ::std::os::raw::c_uchar,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct XAnyEvent {
pub type_: ::std::os::raw::c_int,
pub serial: ::std::os::raw::c_ulong,
pub send_event: ::std::os::raw::c_int,
pub display: *mut Display,
pub window: Window,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct XGenericEvent {
pub type_: ::std::os::raw::c_int,
pub serial: ::std::os::raw::c_ulong,
pub send_event: ::std::os::raw::c_int,
pub display: *mut Display,
pub extension: ::std::os::raw::c_int,
pub evtype: ::std::os::raw::c_int,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct XGenericEventCookie {
pub type_: ::std::os::raw::c_int,
pub serial: ::std::os::raw::c_ulong,
pub send_event: ::std::os::raw::c_int,
pub display: *mut Display,
pub extension: ::std::os::raw::c_int,
pub evtype: ::std::os::raw::c_int,
pub cookie: ::std::os::raw::c_uint,
pub data: *mut ::std::os::raw::c_void,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union _XEvent {
pub type_: ::std::os::raw::c_int,
pub xany: XAnyEvent,
pub xkey: XKeyEvent,
pub xbutton: XButtonEvent,
pub xmotion: XMotionEvent,
pub xcrossing: XCrossingEvent,
pub xfocus: XFocusChangeEvent,
pub xexpose: XExposeEvent,
pub xgraphicsexpose: XGraphicsExposeEvent,
pub xnoexpose: XNoExposeEvent,
pub xvisibility: XVisibilityEvent,
pub xcreatewindow: XCreateWindowEvent,
pub xdestroywindow: XDestroyWindowEvent,
pub xunmap: XUnmapEvent,
pub xmap: XMapEvent,
pub xmaprequest: XMapRequestEvent,
pub xreparent: XReparentEvent,
pub xconfigure: XConfigureEvent,
pub xgravity: XGravityEvent,
pub xresizerequest: XResizeRequestEvent,
pub xconfigurerequest: XConfigureRequestEvent,
pub xcirculate: XCirculateEvent,
pub xcirculaterequest: XCirculateRequestEvent,
pub xproperty: XPropertyEvent,
pub xselectionclear: XSelectionClearEvent,
pub xselectionrequest: XSelectionRequestEvent,
pub xselection: XSelectionEvent,
pub xcolormap: XColormapEvent,
pub xclient: XClientMessageEvent,
pub xmapping: XMappingEvent,
pub xerror: XErrorEvent,
pub xkeymap: XKeymapEvent,
pub xgeneric: XGenericEvent,
pub xcookie: XGenericEventCookie,
pub pad: [::std::os::raw::c_long; 24usize],
_bindgen_union_align: [u64; 24usize],
}
pub type XEvent = _XEvent;
extern "C" {
pub fn XOpenDisplay(arg1: *const ::std::os::raw::c_char) -> *mut Display;
}
extern "C" {
pub fn XInternAtom(
arg1: *mut Display,
arg2: *const ::std::os::raw::c_char,
arg3: ::std::os::raw::c_int,
) -> Atom;
}
extern "C" {
pub fn XCreateGC(
arg1: *mut Display,
arg2: Drawable,
arg3: ::std::os::raw::c_ulong,
arg4: *mut XGCValues,
) -> GC;
}
extern "C" {
pub fn XCreateSimpleWindow(
arg1: *mut Display,
arg2: Window,
arg3: ::std::os::raw::c_int,
arg4: ::std::os::raw::c_int,
arg5: ::std::os::raw::c_uint,
arg6: ::std::os::raw::c_uint,
arg7: ::std::os::raw::c_uint,
arg8: ::std::os::raw::c_ulong,
arg9: ::std::os::raw::c_ulong,
) -> Window;
}
extern "C" {
pub fn XRootWindowOfScreen(arg1: *mut Screen) -> Window;
}
extern "C" {
pub fn XDefaultVisualOfScreen(arg1: *mut Screen) -> *mut Visual;
}
extern "C" {
pub fn XBlackPixelOfScreen(arg1: *mut Screen) -> ::std::os::raw::c_ulong;
}
extern "C" {
pub fn XDefaultScreenOfDisplay(arg1: *mut Display) -> *mut Screen;
}
extern "C" {
pub fn XScreenNumberOfScreen(arg1: *mut Screen) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn XSetWMProtocols(
arg1: *mut Display,
arg2: Window,
arg3: *mut Atom,
arg4: ::std::os::raw::c_int,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn XClearWindow(arg1: *mut Display, arg2: Window) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn XCloseDisplay(arg1: *mut Display) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn XConnectionNumber(arg1: *mut Display) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn XDefaultDepthOfScreen(arg1: *mut Screen) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn XDestroyWindow(arg1: *mut Display, arg2: Window) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn XFlush(arg1: *mut Display) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn XFree(arg1: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn XFreeGC(arg1: *mut Display, arg2: GC) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn XMapRaised(arg1: *mut Display, arg2: Window) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn XNextEvent(arg1: *mut Display, arg2: *mut XEvent) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn XPending(arg1: *mut Display) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn XSelectInput(
arg1: *mut Display,
arg2: Window,
arg3: ::std::os::raw::c_long,
) -> ::std::os::raw::c_int;
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct XSizeHints {
pub flags: ::std::os::raw::c_long,
pub x: ::std::os::raw::c_int,
pub y: ::std::os::raw::c_int,
pub width: ::std::os::raw::c_int,
pub height: ::std::os::raw::c_int,
pub min_width: ::std::os::raw::c_int,
pub min_height: ::std::os::raw::c_int,
pub max_width: ::std::os::raw::c_int,
pub max_height: ::std::os::raw::c_int,
pub width_inc: ::std::os::raw::c_int,
pub height_inc: ::std::os::raw::c_int,
pub min_aspect: XSizeHints__bindgen_ty_1,
pub max_aspect: XSizeHints__bindgen_ty_1,
pub base_width: ::std::os::raw::c_int,
pub base_height: ::std::os::raw::c_int,
pub win_gravity: ::std::os::raw::c_int,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct XSizeHints__bindgen_ty_1 {
pub x: ::std::os::raw::c_int,
pub y: ::std::os::raw::c_int,
}
extern "C" {
pub fn XDestroyImage(ximage: *mut XImage) -> ::std::os::raw::c_int;
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct XVisualInfo {
pub visual: *mut Visual,
pub visualid: VisualID,
pub screen: ::std::os::raw::c_int,
pub depth: ::std::os::raw::c_int,
pub class: ::std::os::raw::c_int,
pub red_mask: ::std::os::raw::c_ulong,
pub green_mask: ::std::os::raw::c_ulong,
pub blue_mask: ::std::os::raw::c_ulong,
pub colormap_size: ::std::os::raw::c_int,
pub bits_per_rgb: ::std::os::raw::c_int,
}
extern "C" {
pub fn XAllocSizeHints() -> *mut XSizeHints;
}
extern "C" {
pub fn XGetVisualInfo(
arg1: *mut Display,
arg2: ::std::os::raw::c_long,
arg3: *mut XVisualInfo,
arg4: *mut ::std::os::raw::c_int,
) -> *mut XVisualInfo;
}
extern "C" {
pub fn XSetWMNormalHints(arg1: *mut Display, arg2: Window, arg3: *mut XSizeHints);
}
pub type ShmSeg = ::std::os::raw::c_ulong;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct XShmCompletionEvent {
pub type_: ::std::os::raw::c_int,
pub serial: ::std::os::raw::c_ulong,
pub send_event: ::std::os::raw::c_int,
pub display: *mut Display,
pub drawable: Drawable,
pub major_code: ::std::os::raw::c_int,
pub minor_code: ::std::os::raw::c_int,
pub shmseg: ShmSeg,
pub offset: ::std::os::raw::c_ulong,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct XShmSegmentInfo {
pub shmseg: ShmSeg,
pub shmid: ::std::os::raw::c_int,
pub shmaddr: *mut ::std::os::raw::c_char,
pub readOnly: ::std::os::raw::c_int,
}
extern "C" {
pub fn XShmQueryExtension(arg1: *mut Display) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn XShmGetEventBase(arg1: *mut Display) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn XShmAttach(arg1: *mut Display, arg2: *mut XShmSegmentInfo) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn XShmDetach(arg1: *mut Display, arg2: *mut XShmSegmentInfo) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn XShmPutImage(
arg1: *mut Display,
arg2: Drawable,
arg3: GC,
arg4: *mut XImage,
arg5: ::std::os::raw::c_int,
arg6: ::std::os::raw::c_int,
arg7: ::std::os::raw::c_int,
arg8: ::std::os::raw::c_int,
arg9: ::std::os::raw::c_uint,
arg10: ::std::os::raw::c_uint,
arg11: ::std::os::raw::c_int,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn XShmCreateImage(
arg1: *mut Display,
arg2: *mut Visual,
arg3: ::std::os::raw::c_uint,
arg4: ::std::os::raw::c_int,
arg5: *mut ::std::os::raw::c_char,
arg6: *mut XShmSegmentInfo,
arg7: ::std::os::raw::c_uint,
arg8: ::std::os::raw::c_uint,
) -> *mut XImage;
}
|
//! Contains stage builders to put in parallel executors when processing images, as well
//! as the definitions of the underlying stages themselves.
use std::f64::consts::PI;
use std::iter::FromIterator;
use std::{borrow::Cow, collections::HashSet};
use conv::ValueInto;
use image::imageops::colorops;
use image::{imageops, Pixel};
use imageproc::{
definitions::{Clamp, Image},
geometric_transformations,
geometric_transformations::Interpolation,
};
use rand::distributions::Uniform;
use rand::Rng;
use crate::traits::{ImageStage, StageBuilder};
use crate::Tags;
/* Label constants for different tags, should be moved into a config file eventually */
mod consts {
#![allow(clippy::missing_docs_in_private_items)]
pub(super) const CWISE_LABEL: &str = "Rotated 90 degrees clockwise";
pub(super) const CCWISE_LABEL: &str = "Rotated 90 degrees counterclockwise";
pub(super) const UPSIDE_DOWN_LABEL: &str = "Upside-down";
pub(super) const OFF_AXIS_LABEL: &str = "Rotated off-axis";
pub(super) const BRIGHTEN_LABEL: &str = "Bright";
pub(super) const DARKEN_LABEL: &str = "Dark";
pub(super) const BLURRED_LABEL: &str = "Blurred";
}
use consts::*;
/// Converts the radians `rad` to degrees.
fn rad_to_deg(rad: f64) -> f64 {
rad * 180. / PI
}
/// Converts the degrees `deg` to radians.
fn deg_to_rad(deg: f64) -> f64 {
deg * PI / 180.
}
/// Creates a builder which will yield `samples` stages, which will rotate the image
/// (without changing the dimensions) between `-deg_limit` and `deg_limit` degrees. It's recommended
/// this value be less than 90, and to combine this stage with `RotationBuilder` for off-axis rotations
/// larger than that. In practice, generally a less extreme value (probably under 30 degrees) is preferable.
pub struct OffAxisRotationBuilder {
/// The number of variations to build when `build_stage` is called.
pub samples: usize,
/// The maximum number of degrees in either direction which a generated stage may rotate an image.
pub deg_limit: f64,
}
impl<P, R> StageBuilder<P, R> for OffAxisRotationBuilder
where
P: Pixel + Send + Sync + 'static,
<P as Pixel>::Subpixel: Default + Send + Sync + ValueInto<f32> + Clamp<f32>,
R: Rng,
{
fn should_execute(&self, tags: &Tags) -> bool {
!tags.0.contains(OFF_AXIS_LABEL)
}
fn variations(&self) -> usize {
self.samples
}
fn build_stage(&self, rng: &mut R) -> Vec<Box<dyn ImageStage<P> + Send + Sync>> {
let rad_limit = deg_to_rad(self.deg_limit);
let range = (-rad_limit)..rad_limit;
rng.sample_iter(Uniform::from(range))
.take(self.samples)
.map(|radians| {
Box::new(OffAxisStage { radians }) as Box<dyn ImageStage<_> + Send + Sync>
})
.collect()
}
}
/// The actual stage that rotates the image, upon `execute` it will return a new image
/// rotated about the center by `radians` degrees.
pub struct OffAxisStage {
/// The number of radians to rotate by.
radians: f64,
}
impl<P> ImageStage<P> for OffAxisStage
where
P: Pixel + Send + Sync + 'static,
<P as Pixel>::Subpixel: Default + Send + Sync + ValueInto<f32> + Clamp<f32>,
{
fn execute(&self, img: &Image<P>) -> (Image<P>, Tags) {
(
geometric_transformations::rotate_about_center(
img,
self.radians as f32,
Interpolation::Bicubic,
P::from_slice(&[Default::default(); 4]).to_owned(),
),
Tags(HashSet::from_iter([OFF_AXIS_LABEL.to_owned()])),
)
}
fn name(&self) -> Cow<str> {
format!("rot_{:.2}_deg", rad_to_deg(self.radians)).into()
}
}
/// Not to be confused with `OffAxisRotationBuilder`, this "rotates" the image
/// as if you were to change its exif orientation data - that is to say it simply will
/// create three stages that rotate the image by multiples of 90, 180, and 270 degrees.
pub struct RotationBuilder;
impl<P: Pixel + 'static, R: Rng> StageBuilder<P, R> for RotationBuilder {
fn should_execute(&self, tags: &Tags) -> bool {
!(tags.0.contains(CWISE_LABEL)
|| tags.0.contains(CCWISE_LABEL)
|| tags.0.contains(UPSIDE_DOWN_LABEL))
}
fn variations(&self) -> usize {
3
}
fn build_stage(&self, _: &mut R) -> Vec<Box<dyn ImageStage<P> + Send + Sync>> {
vec![
Box::new(ClockwiseStage),
Box::new(CclockwiseStage),
Box::new(UpsideDownStage),
]
}
}
/// A stage that rotates an image 90 degrees clockwise.
pub struct ClockwiseStage;
impl<P: Pixel + 'static> ImageStage<P> for ClockwiseStage {
fn execute(&self, img: &Image<P>) -> (Image<P>, Tags) {
(
imageops::rotate90(img),
Tags(HashSet::from_iter([CWISE_LABEL.to_owned()])),
)
}
fn name(&self) -> Cow<str> {
"clowise".into()
}
}
/// A stage that rotates an image 90 degrees counterclockwise.
pub struct CclockwiseStage;
impl<P: Pixel + 'static> ImageStage<P> for CclockwiseStage {
fn execute(&self, img: &Image<P>) -> (Image<P>, Tags) {
(
imageops::rotate270(img),
Tags(HashSet::from_iter([CCWISE_LABEL.to_owned()])),
)
}
fn name(&self) -> Cow<str> {
"couwise".into()
}
}
/// A stage that flips an image upside down.
pub struct UpsideDownStage;
impl<P: Pixel + 'static> ImageStage<P> for UpsideDownStage {
fn execute(&self, img: &Image<P>) -> (Image<P>, Tags) {
(
imageops::rotate180(img),
Tags(HashSet::from_iter([UPSIDE_DOWN_LABEL.to_owned()])),
)
}
fn name(&self) -> Cow<str> {
"up_down".into()
}
}
/// A builder that will yield two stages: a brighten and darken stage, which will change the image
/// pixel intensity across all channels by a random value between `min_luma` and `max_luma`. Note that
/// `i32` is significantly higher than the 8-bit channel value, so this range should be fairly small or
/// all pixels will end up becoming black/white.
pub struct LuminosityBuilder {
/// The minimum degree of intensity we can brighten/darken by.
pub min_luma: i32,
/// The maximum degree of intensity we can brighten/daren by.
pub max_luma: i32,
}
impl<P: Pixel + 'static, R: Rng> StageBuilder<P, R> for LuminosityBuilder {
fn variations(&self) -> usize {
2
}
fn should_execute(&self, tags: &Tags) -> bool {
!(tags.0.contains(BRIGHTEN_LABEL) || tags.0.contains(DARKEN_LABEL))
}
fn build_stage(&self, rng: &mut R) -> Vec<Box<dyn ImageStage<P> + Send + Sync>> {
vec![
Box::new(LuminosityStage {
value: rng.gen_range(self.min_luma..self.max_luma),
}),
Box::new(LuminosityStage {
value: rng.gen_range(-self.max_luma..-self.min_luma),
}),
]
}
}
/// The actual stage that alters brightness and darkness in an image. It will shift all pixels
/// by a constant `value`, negative for darkening and positive for brightening.
pub struct LuminosityStage {
/// The number to add to all pixel channels in the image.
value: i32,
}
impl<P: Pixel + 'static> ImageStage<P> for LuminosityStage {
fn execute(&self, img: &Image<P>) -> (Image<P>, Tags) {
let mut img = img.clone();
colorops::brighten_in_place(&mut img, self.value);
(
img,
Tags(HashSet::from_iter([if self.value < 0 {
DARKEN_LABEL.to_owned()
} else {
BRIGHTEN_LABEL.to_owned()
}])),
)
}
fn name(&self) -> Cow<str> {
if self.value < 0 {
format!("dark_{}", self.value).into()
} else {
format!("bright_{}", self.value).into()
}
}
}
/// A builder that will create `samples` stages that will perform a gaussian blur on the image
/// with a standard deviation between `min_sigma` and `max_sigma` (this is esssentially a uniform
/// distribution over a normal distribution of blurred versions of the image).
pub struct BlurBuilder {
/// The number of blurred variants to create
pub samples: usize,
/// The minimum standard deviation in the gaussian blur kernel
pub min_sigma: f32,
/// The maximum standard deviation in the gaussian blur kernel
pub max_sigma: f32,
}
impl<P: Pixel + 'static, R: Rng> StageBuilder<P, R> for BlurBuilder {
fn variations(&self) -> usize {
self.samples
}
fn should_execute(&self, tags: &Tags) -> bool {
!(tags.0.contains(BLURRED_LABEL))
}
fn build_stage(&self, rng: &mut R) -> Vec<Box<dyn ImageStage<P> + Send + Sync>> {
rng.sample_iter(Uniform::from(self.min_sigma..self.max_sigma))
.take(self.samples)
.map(|sigma| Box::new(BlurStage { sigma }) as Box<dyn ImageStage<_> + Send + Sync>)
.collect()
}
}
/// The actual stage which blurs the image, it will blur the input image with a gaussian blur
/// whose kernel's standard deviation is `sigma`.
pub struct BlurStage {
/// The standard deviation of the gaussian blur kernel.
pub sigma: f32,
}
impl<P: Pixel + 'static> ImageStage<P> for BlurStage {
fn execute(&self, img: &Image<P>) -> (Image<P>, Tags) {
(
imageops::blur(img, self.sigma),
Tags(HashSet::from_iter([BLURRED_LABEL.to_owned()])),
)
}
fn name(&self) -> Cow<str> {
format!("blur_{:0.2}", self.sigma).into()
}
}
|
use crate::common::factories::prelude::*;
use common::rsip::{self, headers::*, prelude::*, Method, Uri};
impl Randomized for rsip::Request {
fn default() -> Self {
Self {
method: Method::default(),
uri: common::CONFIG.default_addr().into(),
version: Default::default(),
headers: Randomized::default(),
body: vec![],
}
}
}
impl Randomized for Method {
fn default() -> Self {
Method::Register
}
}
impl Randomized for Headers {
fn default() -> Self {
let mut headers: Headers = Default::default();
let base_uri: Uri = common::CONFIG.default_addr().into();
let from_uri = base_uri.clone().with_user("filippos");
let to_uri = base_uri.clone().with_user("fil").with_port(5090);
headers.push(typed::To::from(to_uri.clone()).into());
headers.push(typed::From::from(from_uri.clone()).into());
headers.push(
typed::CSeq {
seq: 1,
method: Method::Register,
}
.into(),
);
headers.push(CallId::default().into());
headers.push(MaxForwards::default().into());
headers.push(typed::Via::from(base_uri.clone().stripped()).into());
headers.push(ContentLength::default().into());
headers.push(UserAgent::default().into());
headers
}
}
impl Randomized for rsip::Response {
fn default() -> Self {
Self {
status_code: Default::default(),
version: Default::default(),
headers: Randomized::default(),
body: vec![],
}
}
}
|
// TODO: ? line trailing backslash
// TODO: ? modes? lisp compat
// TODO: multiline comment
use std::io::BufRead;
use nom::IResult;
use nom::error::ParseError;
// use nom::error::Error;
// use nom::Err;
use nom::character::complete::char;
use nom::character::complete::space0;
use nom::character::complete::space1;
use nom::character::complete::alpha1;
use nom::character::complete::alphanumeric1;
use nom::character::complete::digit1;
use nom::character::complete::one_of;
use nom::bytes::complete::tag;
use nom::bytes::complete::is_not;
use nom::sequence::preceded;
use nom::sequence::delimited;
use nom::sequence::terminated;
use nom::sequence::pair;
use nom::sequence::tuple;
use nom::multi::many0;
use nom::multi::separated_list0;
use nom::multi::fold_many0;
use nom::branch::alt;
use nom::combinator::opt;
use nom::combinator::recognize;
use nom::combinator::map;
use nom::combinator::verify;
use nom::combinator::rest;
use nom::combinator::all_consuming;
mod tree;
mod stack;
use stack::Stack;
#[derive(Debug)]
pub enum Literal
{
Number(i32),
String(String),
}
#[derive(Debug)]
pub enum Special
{
Square,
Curly,
}
#[derive(Debug)]
pub enum Form
{
Literal(Literal),
Id(String),
Special(Special),
}
#[derive(Debug)]
struct Line
{
line_no: usize,
depth: usize,
tree: Tree,
comment: String,
}
pub type Tree = tree::Tree<Form>;
type ResultOf <'S, T> = IResult<&'S str, T>;
type Result <'S> = ResultOf<'S, Tree>;
pub fn parse (input: impl BufRead)
-> std::result::Result<Tree, nom::Err<nom::error::Error<usize>>>
{
let lines = input
.lines()
.enumerate()
.map(|(n, line)| (n, line.unwrap()))
.filter(|(_, line)| line.len() > 0)
.map(p_line);
#[derive(Debug)]
struct Frame <'L>
{
depth: usize,
tree: &'L mut Tree,
}
let mut root = Tree::root();
let mut prev = None as Option<&mut Tree>;
let mut stack = Stack::new(Frame { depth: 0, tree: &mut root });
for line in lines
{
let line = line?;
if (is_tree_empty(&line.tree))
{
continue
}
/*
>>>
*/
if (line.depth > stack.head().depth)
{
match prev.take()
{
None => {},
Some(prev) =>
{
stack.push(Frame { depth: line.depth, tree: prev });
}
}
}
/*
<<<
*/
else
{
while (line.depth < stack.head().depth)
{
stack.pop()
}
assert!(line.depth == stack.head().depth, "incorrect_nesting_pop, LINE {}", line.line_no);
}
/*
===
*/
let prev_tree = stack.head().tree.concat(line.tree);
let prev_tree = unsafe
{
let r = (prev_tree as *mut Tree);
(&mut * r)
};
prev = Some(prev_tree);
}
Ok(root)
}
fn p_line ((line_no, input): (usize, String))
-> std::result::Result<Line, nom::Err<nom::error::Error<usize>>>
{
let line_no = (line_no + 1);
let p = tuple
((
p_indent,
p_list_naked,
map(opt(p_comment), |comment| comment.map_or_else(|| "".into(), |s| s.into())),
));
let p = map(p, |(depth, tree, comment)|
{
Line
{
line_no,
depth,
tree,
comment,
}
});
let p = all_consuming(p);
let mut p = p;
p(&input)
.map(|(_, line)| line)
.map_err(|err| err.map_input(|_| line_no))
}
fn p_comment (input: &str) -> ResultOf<&str>
{
let p = preceded(tag(";"), rest);
let mut p = p;
p(input)
}
fn p_indent (input: &str) -> ResultOf<usize>
{
let p = space0;
let p = map(p, |s: &str| s.len());
let mut p = p;
p(input)
}
fn p_form (input: &str) -> Result
{
let p = alt((
p_list,
p_id,
p_num,
p_str,
));
let mut p = p;
p(input)
}
fn p_list (input: &str) -> Result
{
let p_list_round = p_list_qualified("(", ")");
let p_list_square = p_list_qualified("[", "]");
let p_list_square = map(p_list_square, |mut tree|
{
tree.prepend(Tree::Leaf(Form::Special(Special::Square)));
tree
});
let p_list_curly = p_list_qualified("{", "}");
let p_list_curly = map(p_list_curly, |mut tree|
{
tree.prepend(Tree::Leaf(Form::Special(Special::Curly)));
tree
});
let p = alt
((
p_list_round,
p_list_square,
p_list_curly,
));
let mut p = p;
p(input)
}
fn p_list_qualified (open: &'static str, close: &'static str) -> impl FnMut(&str) -> Result
{
move |input|
{
let p = preceded
(
tag(open),
ws(p_list_naked),
);
let p = terminated(p, opt(tag(close)));
let mut p = p;
p(input)
}
}
fn p_list_naked (input: &str) -> Result
{
let p = separated_list0(space1, p_form);
let mut p = map(p, Tree::Branch);
p(input)
}
fn p_id (input: &str) -> Result
{
let whitelist = "_-~!@#$%&?*+=<>";
let p = pair
(
alt((alpha1, recognize(one_of(whitelist)))),
many0(alt((alphanumeric1, recognize(one_of(whitelist))))),
);
let p = recognize(p);
let mut p = map(p, |s: &str| Tree::Leaf(Form::Id(s.into())));
p(input)
}
fn p_num (input: &str) -> Result
{
let p = digit1;
let p = recognize(p);
let p = map(p, |s: &str|
{
let n = Literal::Number(s.parse().unwrap()); // map_res
let n = Form::Literal(n);
let n = Tree::Leaf(n);
n
});
let mut p = p;
p(input)
}
fn p_str (input: &str) -> Result
{
let escape_list = one_of("\"\\nrt");
let escape = preceded(tag("\\"), escape_list);
let escape = map(escape, |c|
{
match c
{
'\\' => '\\'.to_string(),
'"' => '"'.to_string(),
'n' => "\n".to_string(),
'r' => "\r".to_string(),
't' => "\t".to_string(),
_ => panic!(),
}
});
let literal = is_not("\"\\");
let literal = verify(literal, |s: &str| (! s.is_empty()));
let literal = map(literal, |s: &str| s.to_string());
let fragment = alt
((
escape,
literal,
));
let contents = fold_many0
(
fragment,
String::new,
|mut total, s|
{
total.push_str(&s);
total
},
);
let p = delimited(char('"'), contents, char('"'));
let p = map(p, |s|
{
let s = Literal::String(s);
let s = Form::Literal(s);
let s = Tree::Leaf(s);
s
});
let mut p = p;
p(input)
}
fn ws <'a, F: 'a, O, E> (inner: F)
-> impl FnMut(&'a str) -> IResult<&'a str, O, E>
where
E: ParseError<&'a str>,
F: Fn(&'a str) -> IResult<&'a str, O, E>,
{
delimited
(
space0,
inner,
space0,
)
}
fn is_tree_empty (tree: &Tree) -> bool
{
match tree
{
Tree::Leaf(_) => panic!(),
Tree::Branch(vec) => vec.is_empty(),
}
}
|
fn use_errorchain() {
use error_chain::error_chain;
error_chain! {
// 把std Error映射为自定义Error
foreign_links {
Io(std::io::Error);
StripPrefixError(::std::path::StripPrefixError);
}
// 自定义错误类型
errors {
Single {
description("MyError!")
display("Single Error")
}
Duple(t: String) {
description("MyError!")
display("Dutple {} Error", t)
}
Multi(len: u32, data: Vec<u32>) {
description("MyError!")
display("Multi len {} data {:?} Error", len, data)
}
}
}
}
|
use crossdisplay::tui::{Direction, EditorEvent, KeyCode, KeyEvent, KeyModifier};
use std::collections::HashMap;
type KeyMap = HashMap<KeyEvent, EditorEvent>;
pub enum Mode {
Insert,
Normal,
Command,
}
pub struct Mapper {
nmaps: KeyMap,
imaps: KeyMap,
cmaps: KeyMap,
}
impl Mapper {
fn new() -> Self {
Self {
nmaps: KeyMap::new(),
imaps: KeyMap::new(),
cmaps: KeyMap::new(),
}
}
fn get_map(&self, mode: &Mode) -> &KeyMap {
use Mode::*;
match mode {
Normal => &self.nmaps,
Insert => &self.imaps,
Command => &self.cmaps,
}
}
fn get_map_mut(&mut self, mode: &Mode) -> &mut KeyMap {
use Mode::*;
match mode {
Normal => &mut self.nmaps,
Insert => &mut self.imaps,
Command => &mut self.cmaps,
}
}
pub fn get_mapping(&self, mode: &Mode, event: &KeyEvent) -> Option<EditorEvent> {
Some(self.get_map(mode).get(event)?.clone())
}
pub fn insert_mapping(mut self, mode: &Mode, key: KeyEvent, event: EditorEvent) -> Self {
self.get_map_mut(mode).insert(key, event);
self
}
}
pub fn key_builder() -> Mapper {
use Mode::*;
Mapper::new()
.insert_mapping(
&Normal,
KeyEvent::new(KeyCode::Esc, KeyModifier::NONE),
EditorEvent::Quit,
)
.insert_mapping(
&Normal,
KeyEvent::new(KeyCode::Char('j'), KeyModifier::NONE),
EditorEvent::Cursor(Direction::Down(1)),
)
.insert_mapping(
&Normal,
KeyEvent::new(KeyCode::Char('k'), KeyModifier::NONE),
EditorEvent::Cursor(Direction::Up(1)),
)
.insert_mapping(
&Normal,
KeyEvent::new(KeyCode::Char('h'), KeyModifier::NONE),
EditorEvent::Cursor(Direction::Left(1)),
)
.insert_mapping(
&Normal,
KeyEvent::new(KeyCode::Char('l'), KeyModifier::NONE),
EditorEvent::Cursor(Direction::Right(1)),
)
.insert_mapping(
&Normal,
KeyEvent::new(KeyCode::Char('e'), KeyModifier::Control),
EditorEvent::Scroll(Direction::Down(1), Direction::Up(1)),
)
.insert_mapping(
&Normal,
KeyEvent::new(KeyCode::Char('y'), KeyModifier::Control),
EditorEvent::Scroll(Direction::Up(1), Direction::Down(1)),
)
.insert_mapping(
&Normal,
KeyEvent::new(KeyCode::Char(':'), KeyModifier::NONE),
EditorEvent::ModeCommand,
)
.insert_mapping(
&Command,
KeyEvent::new(KeyCode::Esc, KeyModifier::NONE),
EditorEvent::ModeNormal,
)
.insert_mapping(
&Normal,
KeyEvent::new(KeyCode::Char('i'), KeyModifier::NONE),
EditorEvent::ModeInsert,
)
.insert_mapping(
&Insert,
KeyEvent::new(KeyCode::Esc, KeyModifier::NONE),
EditorEvent::ModeNormal,
)
}
|
use crate::*;
use crate::logger::LogLevel;
#[no_mangle]
pub extern "C" fn dhc_init() {
crate::init();
}
#[no_mangle]
pub unsafe extern "C" fn dhc_log(level: LogLevel, msg: *const u8, msg_len: usize) {
let string = std::str::from_utf8_unchecked(std::slice::from_raw_parts(msg, msg_len));
if level == LogLevel::Fatal {
panic!("{}", string);
}
log!(level.to_log(), "{}", string);
}
#[no_mangle]
pub extern "C" fn dhc_log_is_enabled(level: LogLevel) -> bool {
log_enabled!(level.to_log())
}
#[no_mangle]
pub extern "C" fn dhc_xinput_is_enabled() -> bool {
Context::instance().xinput_enabled()
}
#[no_mangle]
pub extern "C" fn dhc_update() {
Context::instance().update();
}
#[no_mangle]
pub extern "C" fn dhc_get_device_count() -> usize {
Context::instance().device_count()
}
#[no_mangle]
pub extern "C" fn dhc_get_inputs(index: usize) -> DeviceInputs {
Context::instance().device_state(index)
}
#[no_mangle]
pub unsafe extern "C" fn dhc_get_axis(inputs: *const DeviceInputs, axis_type: AxisType) -> f64 {
(*inputs).get_axis(axis_type).get().into()
}
#[no_mangle]
pub unsafe extern "C" fn dhc_get_button(inputs: *const DeviceInputs, button_type: ButtonType) -> bool {
(*inputs).get_button(button_type).get()
}
#[no_mangle]
pub unsafe extern "C" fn dhc_get_hat(inputs: *const DeviceInputs, hat_type: HatType) -> Hat {
(*inputs).get_hat(hat_type)
}
|
mod client;
mod model;
pub use self::client::get;
pub use self::model::{Giteki, GitekiInformation, RequestParameters, Response};
|
use crate::cmap::PoolGeneration;
/// Struct used to track the latest status of the pool.
#[derive(Clone, Debug)]
struct PoolStatus {
/// The current generation of the pool.
generation: PoolGeneration,
}
/// Create a channel for publishing and receiving updates to the pool's generation.
pub(super) fn channel(init: PoolGeneration) -> (PoolGenerationPublisher, PoolGenerationSubscriber) {
let (sender, receiver) = tokio::sync::watch::channel(PoolStatus { generation: init });
(
PoolGenerationPublisher { sender },
PoolGenerationSubscriber { receiver },
)
}
/// Struct used to publish updates to the pool's generation.
#[derive(Debug)]
pub(super) struct PoolGenerationPublisher {
sender: tokio::sync::watch::Sender<PoolStatus>,
}
impl PoolGenerationPublisher {
/// Publish a new generation.
pub(super) fn publish(&self, new_generation: PoolGeneration) {
let new_status = PoolStatus {
generation: new_generation,
};
// if nobody is listening, this will return an error, which we don't mind.
let _: std::result::Result<_, _> = self.sender.send(new_status);
}
}
/// Subscriber used to get the latest generation of the pool.
#[derive(Clone, Debug)]
pub(crate) struct PoolGenerationSubscriber {
receiver: tokio::sync::watch::Receiver<PoolStatus>,
}
impl PoolGenerationSubscriber {
/// Get a copy of the latest generation.
pub(crate) fn generation(&self) -> PoolGeneration {
self.receiver.borrow().generation.clone()
}
}
|
//! Easy and ready access to the database of The Central Bank of The Republic of Turkey (CBRT).
//!
//! This crate provides two main mechanisms for acquiring data from the database:
//!
//! - Operational FFI functions.
//! + [`tcmb_evds_c_get_data`](crate::tcmb_evds_c_get_data)
//! + [`tcmb_evds_c_get_advanced_data`](crate::tcmb_evds_c_get_advanced_data)
//! + [`tcmb_evds_c_get_data_group`](crate::tcmb_evds_c_get_data_group)
//! + [`tcmb_evds_c_get_categories`](crate::tcmb_evds_c_get_categories)
//! + [`tcmb_evds_c_get_advanced_data_group`](crate::tcmb_evds_c_get_advanced_data_group)
//! + [`tcmb_evds_c_get_series_list`](crate::tcmb_evds_c_get_series_list)
//! - [`evds_c`](crate::evds_c) includes auxiliary enums and structures for the functions to make all of the web service
//! operations to make users able to utilize these functions in **C language**.
//!
//! Required auxiliary enums and structures of FFI functions are given in the [`evds_c`](crate::evds_c) module. These
//! entities make users able to use FFI functions that supply all of the EVDS operations. In addition, most parameters
//! of the functions are checked to make valid requests. As a result of the
//! checking, detailed and specified error types are returned to easily handle and fix the errors. Additionally, the
//! operational functions requires **ascii_mode** to convert a format having non-English characters of the response
//! text to another format including only English characters. Moreover, the mode as an argument converts non-utf8
//! characters to asterisk (*) **if there is**. Therefore, the response text becomes safe against non-ascii characters.
//! To use [`evds_c`](crate::evds_c) in C language, users should build the crate and use both built
//! *libtcmb_evds_c.so*, *libtcmb_evds_c.dylib* or *libtcmb_evds_c.dll* for multiple platforms and *tcmb_evds_c.h* file
//! in the target folder or should download one of the pre-built libraries from
//! [github](https://github.com/asari555/tcmb_evds_c).
//!
//! # Usage
//!
//! For implementations of other functions, please move on their stages.
//!
//! [`tcmb_evds_c_get_data`](crate::tcmb_evds_c_get_data) usage example.
//!
//! ```
//! #include "tcmb_evds_c.h"
//!
//! int main() {
//! // declaration of required arguments for get data operation.
//! TcmbEvdsInput data_series;
//! TcmbEvdsInput date;
//!
//! // declaring common variables for creating Evds common struct for each FFI function.
//! TcmbEvdsInput api_key;
//! TcmbEvdsReturnFormat return_format;
//!
//! bool ascii_mode;
//!
//!
//! data_series.input_ptr = "TP.DK.USD.S";
//! data_series.string_capacity = strlen(data_series.input_ptr);
//!
//! date.input_ptr = "13-12-2011, 12-12-2012";
//! date.string_capacity = strlen(date.input_ptr);
//!
//! api_key.input_ptr = "VALID_API_KEY";
//! api_key.string_capacity = strlen(api_key.input_ptr);
//!
//! return_format = Csv
//!
//! ascii_mode = false;
//!
//!
//! // due to the fact that data_result may include error, please check it first.
//! TcmbEvdsResult data_result = tcmb_evds_c_get_data(data_series, date, api_key, return_format, ascii_mode);
//!
//! return 0;
//! }
//! ```
//!
//!
//! [`tcmb_evds_c_get_advanced_data`](crate::tcmb_evds_c_get_advanced_data) usage example.
//!
//! ```
//! #include "tcmb_evds_c.h"
//!
//! int main() {
//! // declaration of required arguments for get data operation.
//! TcmbEvdsInput data_series;
//! TcmbEvdsInput date;
//!
//! // declaration of frequency formulas entities.
//! TcmbEvdsAggregationType aggregation_type;
//! TcmbEvdsFormula formula;
//! TcmbEvdsDataFrequency data_frequency;
//!
//! // declaring common variables for creating Evds common struct for each FFI function.
//! TcmbEvdsInput api_key;
//! TcmbEvdsReturnFormat return_format;
//!
//! bool ascii_mode;
//!
//!
//! data_series.input_ptr = "TP.DK.USD.A";
//! data_series.string_capacity = strlen(data_series.input_ptr);
//!
//! date.input_ptr = "13-12-2011";
//! date.string_capacity = strlen(date.input_ptr);
//!
//! aggregation_type = End;
//! formula = Level;
//! data_frequency = Monthly;
//!
//! api_key.input_ptr = "VALID_API_KEY";
//! api_key.string_capacity = strlen(api_key.input_ptr);
//!
//! return_format = Json;
//!
//! ascii_mode = false;
//!
//!
//! // due to the fact that data_result may include error, please check it first.
//! TcmbEvdsResult advanced_data_result =
//! tcmb_evds_c_get_advanced_data(
//! data_series,
//! date,
//! aggregation_type,
//! formula,
//! data_frequency,
//! api_key,
//! return_format,
//! ascii_mode
//! );
//!
//! return 0;
//! }
//! ```
//!
//! # Features
//!
//! - Provides all of the EVDS web service operations.
//! - Most of the function parameters in the module are automatically checked inside the functions.
//! - Users are responsible to give valid and correct arguments to related parameters not supporting auto control.
//! - C specific.
//!
//! # User Guide
//!
//! First of all, please take a look at *benioku.md* for Turkish or *readme.md* files before using the crate.
//!
//! Additional resource for understanding some parameters, learning various data series and details of web services are
//! mentioned in [`kullanim kilavuzu`] for Turkish and [`user guide`].
//!
//!
//! [`user guide`]: <https://evds2.tcmb.gov.tr/help/videos/EVDS_Web_Service_Usage_Guide.pdf>
//! [`kullanim kilavuzu`]: <https://evds2.tcmb.gov.tr/help/videos/EVDS_Web_Servis_Kullanim_Kilavuzu.pdf>
//!
//! # Appendix
//!
//! To understand *ytl_mode* required in some functions and what is "YTL", please follow [`what is YTL?`].
//!
//! [`what is YTL?`]: <https://en.wikipedia.org/wiki/Revaluation_of_the_Turkish_lira>
// #[deny(missing_docs)]
/// contains two main elements that are used in operations of
/// [`evds_basic`](crate::evds_basic) and [`evds_currency`](crate::evds_currency).
///
/// [`ReturnFormat`](crate::common::ReturnFormat) specifies format of the database response and
/// [`ApiKey`](crate::common::ApiKey) is created to supply valid key to the functions making request operations.
/// [`Evds`](crate::common::Evds) becomes connection between the functions and both
/// [`ReturnFormat`](crate::common::ReturnFormat) and [`ApiKey`](crate::common::ApiKey) variables.
///
/// # Usage
///
/// The each element is explained and exampled in their definition parts. This usage illustrates
/// combined version of common elements on Evds structure to be used in related functions.
///
/// ```
/// # use std::error::Error;
/// # use tcmb_evds_c::common::{ApiKey, ReturnFormat, Evds};
/// # use tcmb_evds_c::error::ReturnError;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// #
/// // Please use a valid key here.
/// let api_key = ApiKey::from("users_valid_key")?;
///
/// let return_format = ReturnFormat::Json;
///
/// let evds = Evds::from(api_key, return_format);
///
/// # Ok(())
/// # }
/// ```
mod common;
/// contains date elements that are used in some functions of [`evds_basic`](crate::evds_basic) and
/// [`evds_currency`](crate::evds_currency).
///
/// [`Date`](crate::date::Date) and [`DateRange`](crate::date::DateRange) are created to supply single date and multiple
/// dates called date range. [`DatePreference`](crate::date::DatePreference) includes [`Date`](crate::date::Date) or
/// [`DateRange`](crate::date::DateRange) and supplies date options to related functions of
/// [`evds_basic`](crate::evds_basic) and [`evds_currency`](crate::evds_currency).
///
/// # Usage
///
/// The each element is explained and exampled in their definitions parts.
///
/// ```
/// # use std::error::Error;
/// # use tcmb_evds_c::date::{Date, DateRange, DatePreference};
/// # use tcmb_evds_c::error::ReturnError;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// #
/// // Single date example.
/// let date = Date::from("13-12-2011")?;
///
/// let date_preference = DatePreference::Single(date);
///
///
/// // Multiple dates example.
/// let date_range = DateRange::from("13-12-2011", "13-12-2020")?;
///
/// let date_preference = DatePreference::Multiple(date_range);
///
/// # Ok(())
/// # }
/// ```
mod date;
/// contains specified error options that are returned from the functions of
/// [`evds_basic`](crate::evds_basic) and [`evds_currency`](crate::evds_currency) to illustrate why the error occurs.
///
/// One of the [`ReturnError`](crate::error::ReturnError) options is returned when something goes wrong with requesting
/// data or giving parameter to the functions. Therefore, users are able to handle specified error types and to
/// stringify them in a standard format.
mod error;
/// provides most of the EVDS web services except requesting advanced currency data that means currency data with
/// frequency formulas.
mod evds_basic;
/// provides only currency operations with methods of [`CurrencySeries`] and [`MultipleCurrencySeries`].
///
/// This module built on two main structures and their methods operating currency services. The basic difference between
/// these structures is number of currency types. [`CurrencySeries`](crate::evds_currency::CurrencySeries) serves
/// methods using a currency type. In contrast, [`MultipleCurrencySeries`](crate::evds_currency::MultipleCurrencySeries)
/// serves a method using more than a currency type to get currencies data.
///
/// `CurrencySeries` is composed of [`CurrencyCode`], `ExchangeType`, `DatePreference` and `ytl_mode` to supply
/// adequate information to make requesting data about **a currency** via related **operational methods**.
///
/// `MultipleCurrencySeries` is composed of [`CurrencyCodes`], `ExchangeType`, `DatePreference` and `ytl_mode` to
/// supply adequate information to make requesting data about **given currencies** via **an operational method**.
///
/// Usage schematic and hierarchy of this module:
///
/// - [`CurrencySeries`] -> [`get_data`] ( [`Evds`] ) or [`get_advanced_data`] ( [`Evds`], [`AdvancedProcesses`] )
///
/// > `CurrencySeries` requires below struct as a difference:
/// > + [`CurrencyCode`]
///
/// - [`MultipleCurrencySeries`] -> [`get_multiple_data`] ( [`Evds`])
///
/// > `MultipleCurrencySeries` requires below struct as a difference:
/// > + [`CurrencyCodes`]
///
/// Both `CurrencySeries` and `MultipleCurrencySeries` requires common structures and a variable:
///
/// - [`ExchangeType`]
/// - [`DatePreference`]
/// - `ytl_mode: bool`
///
/// Generic view of operational methods:
///
/// - [`get_data`]
///
/// - [`get_advanced_data`]
///
/// - [`get_multiple_data`]
///
/// To use the operational methods, the related structures for the required operation should be built firstly. Then,
/// the methods can be used with the common structure that is [`Evds`].
///
/// *More details of operational functions and their usage are included in their stages.*
///
/// [`CurrencySeries`]: crate::evds_currency::CurrencySeries
/// [`MultipleCurrencySeries`]: crate::evds_currency::MultipleCurrencySeries
///
/// [`Evds`]: crate::common::Evds
/// [`DatePreference`]: crate::date::DatePreference
/// [`ExchangeType`]: crate::evds_currency::ExchangeType
///
/// [`CurrencySeries`]: crate::evds_currency::CurrencySeries
/// [`CurrencyCode`]: crate::evds_currency::CurrencyCode
/// [`AdvancedProcesses`]: crate::evds_currency::frequency_formulas::AdvancedProcesses
///
/// [`MultipleCurrencySeries`]: crate::evds_currency::MultipleCurrencySeries
/// [`CurrencyCodes`]: crate::evds_currency::CurrencyCodes
///
/// [`get_data`]: crate::evds_currency::CurrencySeries::get_data
/// [`get_advanced_data`]: crate::evds_currency::CurrencySeries::get_advanced_data
/// [`get_multiple_data`]: crate::evds_currency::MultipleCurrencySeries::get_multiple_data
mod evds_currency;
mod traits;
/// provides auxiliary enums and structures to FFI to use abilities of the EVDS web services in C language.
///
/// This module has almost the same structural concept with the [`tcmb_evds_c`] crate. [`advanced_entities`],
/// [`common_entities`] and [`error_handling`]. These modules are responsible to supply required arguments for
/// related parameters declared with various operational functions.
///
/// Enum and struct of this module includes lucid explanation and its detailed usage example in its
/// section.
///
/// The related output library of the crate is built in the folder where the `Cargo build --release` command builds. To
/// see the corresponding function names, enum and struct types in terms of **C**, please look at `target/tcmb_evds_c.h`
/// automatically built C header file. In addition, to utilize the crate in C language, please first build the crate and
/// then link one of related **libtcmb_evds_c** libraries and include **tcmb_evd1s_c.h** files in target folder.
///
/// [`tcmb_evds_c`]: crate
/// [`advanced_entities`]: crate::evds_c::advanced_entities
/// [`common_entities`]: crate::evds_c::common_entities
/// [`error_handling`]: crate::evds_c::error_handling
pub mod evds_c;
#[cfg(feature = "async_mode")]
mod request_async;
#[cfg(feature = "sync_mode")]
mod request_sync;
extern crate libc;
use crate::evds_currency::{CurrencySeries, frequency_formulas};
use crate::evds_c::{common_entities::*, error_handling::*};
use crate::evds_c::advanced_entities::{TcmbEvdsAggregationType, TcmbEvdsDataFrequency, TcmbEvdsFormula};
use crate::evds_c::{generate_date_preference, generate_evds, return_response};
use crate::evds_c::data_series::parse_series;
use crate::traits::converting_to_rust_enum::ConvertingToRustEnum;
use libc::c_uint;
/// gets data requested via any valid data series from EVDS.
///
/// # Error
///
/// This function returns error when invalid data series, date, or api key is supplied or there is a bad internet
/// connection.
///
/// # Example
///
/// ```C
///
/// #include "tcmb_evds_c.h"
///
///
/// int main() {
///
/// // declaration of required arguments.
/// TcmbEvdsInput data_series;
/// TcmbEvdsInput date;
/// TcmbEvdsInput api_key;
/// TcmbEvdsReturnFormat return_format;
/// bool ascii_mode;
///
///
/// // value assignments.
/// data_series.input_ptr = "TP.DK.USD.S";
/// data_series.string_capacity = strlen(data_series.input_ptr);
///
/// date.input_ptr = "13-12-2011";
/// date.string_capacity = strlen(date.input_ptr);
///
/// api_key.input_ptr = "VALID_API_KEY";
/// api_key.string_capacity = strlen(api_key.input_ptr);
/// return_format = Csv;
///
/// ascii_mode = false;
///
///
/// // requesting data.
/// TcmbEvdsResult data_result = tcmb_evds_c_get_data(data_series, date, api_key, return_format, ascii_mode);
///
///
/// // handling error and printing the result.
/// if (!tcmb_evds_c_is_error(data_result)) { printf("\nNO ERROR!\n"); };
/// printf("\nError: %s", tcmb_evds_c_is_error(data_result) ? "true" : "false");
///
/// char* data_result_message = calloc(data_result.string_capacity, sizeof(char));
/// memmove(data_result_message, data_result.output_ptr, data_result.string_capacity * sizeof(char));
///
/// printf("%s", data_result_message);
///
/// free(data_result_message);
///
/// return 0;
/// }
/// ```
#[no_mangle]
pub extern "C" fn tcmb_evds_c_get_data(
data_series: TcmbEvdsInput,
date: TcmbEvdsInput,
api_key: TcmbEvdsInput,
return_format: TcmbEvdsReturnFormat,
ascii_mode: bool
) -> TcmbEvdsResult {
let (rust_data_series, data_series_error_state) = data_series.get_input("data_series");
let (rust_date, date_error_state) = date.get_input("date");
let parameter_error = ReturnErrorC::ParameterError;
if data_series_error_state {
return TcmbEvdsResult::generate_result(rust_data_series, parameter_error);
}
if date_error_state {
return TcmbEvdsResult::generate_result(rust_date, parameter_error);
}
let date_preference_result = generate_date_preference(&rust_date);
let date_preference = match date_preference_result {
Ok(preference) => preference,
Err(error_result) => return error_result,
};
let evds_result = generate_evds(api_key, return_format);
let evds = match evds_result {
Ok(evds) => evds,
Err(error_result) => return error_result,
};
// Requesting data from the Tcmb Evds.
let requested_response =
evds_basic::get_data(
&rust_data_series,
&date_preference,
&evds
);
return_response(requested_response, ascii_mode)
}
/// gets currency data with frequency formulas from EVDS.
///
/// # Error
///
/// This function returns error when invalid currency series, date, aggregation type, formula, data frequency, or api
/// key is supplied or there is a bad internet connection.
///
/// # Example
///
/// ```C
///
/// #include "tcmb_evds_c.h"
///
///
/// int main() {
///
/// // declaration of required arguments.
/// TcmbEvdsInput data_series;
/// TcmbEvdsInput date;
///
/// TcmbEvdsAggregationType aggregation_type;
/// TcmbEvdsFormula formula;
/// TcmbEvdsDataFrequency data_frequency;
///
/// TcmbEvdsInput api_key;
/// TcmbEvdsReturnFormat return_format;
///
/// bool ascii_mode;
///
///
/// // value assignments.
/// data_series.input_ptr = "TP.DK.USD.A";
/// data_series.string_capacity = strlen(data_series.input_ptr);
///
/// date.input_ptr = "13-12-2011";
/// date.string_capacity = strlen(date.input_ptr);
///
/// aggregation_type = End;
/// formula = Level;
/// data_frequency = Monthly;
///
/// api_key.input_ptr = "VALID_API_KEY";
/// api_key.string_capacity = strlen(api_key.input_ptr);
///
/// return_format = Json;
///
/// ascii_mode = false;
///
///
/// // requesting data.
/// TcmbEvdsResult advanced_data_result =
/// tcmb_evds_c_get_advanced_data(
/// data_series,
/// date,
/// aggregation_type,
/// formula,
/// data_frequency,
/// api_key,
/// return_format,
/// ascii_mode
/// );
///
///
/// // handling error and printing the result.
/// if (!tcmb_evds_c_is_error(advanced_data_result)) { printf("\nNO ERROR!\n"); };
/// printf("\nError: %s", tcmb_evds_c_is_error(advanced_data_result) ? "true" : "false");
///
/// char* advanced_data_result_message = calloc(advanced_data_result.string_capacity, sizeof(char));
/// memmove(
/// advanced_data_result_message,
/// advanced_data_result.output_ptr,
/// advanced_data_result.string_capacity * sizeof(char)
/// );
///
/// printf("%s", advanced_data_result_message);
///
/// free(advanced_data_result_message);
///
/// return 0;
/// }
/// ```
#[no_mangle]
pub extern "C" fn tcmb_evds_c_get_advanced_data(
currency_series: TcmbEvdsInput,
date: TcmbEvdsInput,
aggregation_type: TcmbEvdsAggregationType,
formula: TcmbEvdsFormula,
data_frequency: TcmbEvdsDataFrequency,
api_key: TcmbEvdsInput,
return_format: TcmbEvdsReturnFormat,
ascii_mode: bool
) -> TcmbEvdsResult {
let (rust_data_series, data_series_error_state) =
currency_series.get_input(
"currency_series"
);
let (rust_date, date_error_state) = date.get_input("date");
let rust_aggregation_type = aggregation_type.convert();
let rust_formula = formula.convert();
let rust_data_frequency = data_frequency.convert();
let parameter_error = ReturnErrorC::ParameterError;
if data_series_error_state {
return TcmbEvdsResult::generate_result(rust_data_series, parameter_error);
}
if date_error_state {
return TcmbEvdsResult::generate_result(rust_date, parameter_error);
}
let advanced_processes =
frequency_formulas::AdvancedProcesses::from(
rust_aggregation_type,
rust_formula,
rust_data_frequency
);
let data_series_parts = parse_series(&rust_data_series);
if let Err(return_error) = data_series_parts { return handle_return_error(return_error); };
let data_series_parts = data_series_parts.unwrap();
let date_preference_result = generate_date_preference(&rust_date);
let date_preference = match date_preference_result {
Ok(preference) => preference,
Err(error_result) => return error_result,
};
let currency_series = CurrencySeries {
ytl_mode: data_series_parts.ytl_mode,
exchange_type: data_series_parts.exchange_type,
currency_code: data_series_parts.currency_code,
date_preference
};
let evds_result = generate_evds(api_key, return_format);
let evds = match evds_result {
Ok(evds) => evds,
Err(error_result) => return error_result,
};
// Requesting advanced currency data from the Tcmb Evds.
let requested_response =
currency_series.get_advanced_data(
&evds,
&advanced_processes
);
return_response(requested_response, ascii_mode)
}
/// gets all series data related given data group from EVDS.
///
/// # Error
///
/// This function returns error when invalid data_group, date, or api key is supplied or there is a bad internet
/// connection.
///
/// # Example
///
/// ```C
///
/// #include "tcmb_evds_c.h"
///
///
/// int main() {
///
/// // declaration of required arguments.
/// TcmbEvdsInput data_group;
/// TcmbEvdsInput date;
///
/// TcmbEvdsInput api_key;
/// TcmbEvdsReturnFormat return_format;
///
/// bool ascii_mode;
///
///
/// // value assignments.
/// data_group.input_ptr = "bie_yssk";
/// data_group.string_capacity = strlen(data_group.input_ptr);
///
/// date.input_ptr = "01-06-2017,07-09-2017";
/// date.string_capacity = strlen(date.input_ptr);
///
/// api_key.input_ptr = "VALID_API_KEY";
/// api_key.string_capacity = strlen(api_key.input_ptr);
///
/// return_format = Json;
///
/// ascii_mode = false;
///
///
/// // requesting data.
/// TcmbEvdsResult data_group =
/// tcmb_evds_c_get_data_group(
/// data_group,
/// date,
/// api_key,
/// return_format,
/// ascii_mode
/// );
///
///
/// // handling error and printing the result.
/// if (!tcmb_evds_c_is_error(data_group)) { printf("\nNO ERROR!\n"); };
/// printf("\nError: %s", tcmb_evds_c_is_error(data_group) ? "true" : "false");
///
/// char* data_group_message = calloc(data_group.string_capacity, sizeof(char));
/// memmove(data_group_message, data_group.output_ptr, data_group.string_capacity * sizeof(char));
///
/// printf("%s", data_group_message);
///
/// free(data_group_message);
///
/// return 0;
/// }
/// ```
#[no_mangle]
pub extern "C" fn tcmb_evds_c_get_data_group(
data_group: TcmbEvdsInput,
date: TcmbEvdsInput,
api_key: TcmbEvdsInput,
return_format: TcmbEvdsReturnFormat,
ascii_mode: bool
) -> TcmbEvdsResult {
let (rust_data_group, data_group_error_state) = data_group.get_input("data_group");
let (rust_date, date_error_state) = date.get_input("date");
let parameter_error = ReturnErrorC::ParameterError;
if data_group_error_state {
return TcmbEvdsResult::generate_result(rust_data_group, parameter_error);
}
if date_error_state {
return TcmbEvdsResult::generate_result(rust_date, parameter_error);
}
let date_preference_result = generate_date_preference(&rust_date);
let date_preference = match date_preference_result {
Ok(preference) => preference,
Err(error_result) => return error_result,
};
let evds_result = generate_evds(api_key, return_format);
let evds = match evds_result {
Ok(evds) => evds,
Err(error_result) => return error_result,
};
// Requesting data group from the Tcmb Evds.
let requested_response =
evds_basic::get_data_group(
&rust_data_group,
&date_preference,
&evds
);
return_response(requested_response, ascii_mode)
}
/// gets categories list from EVDS.
///
/// # Error
///
/// This function returns error when invalid api key is supplied or there is a bad internet connection.
///
/// # Example
///
/// ```C
///
/// #include "tcmb_evds_c.h"
///
///
/// int main() {
///
/// // declaration of required arguments.
/// TcmbEvdsInput api_key;
/// TcmbEvdsReturnFormat return_format;
///
/// bool ascii_mode;
///
///
/// // value assignments.
/// api_key.input_ptr = "VALID_API_KEY";
/// api_key.string_capacity = strlen(api_key.input_ptr);
///
/// return_format = Json;
///
/// ascii_mode = false;
///
///
/// // requesting data.
/// TcmbEvdsResult categories = tcmb_evds_c_get_categories(api_key, return_format, ascii_mode);
///
///
/// // handling error and printing the result.
/// if (!tcmb_evds_c_is_error(categories)) { printf("\nNO ERROR!\n"); };
/// printf("\nError: %s", tcmb_evds_c_is_error(categories) ? "true" : "false");
///
/// char* categories_message = calloc(categories.string_capacity, sizeof(char));
/// memmove(categories_message, categories.output_ptr, categories.string_capacity * sizeof(char));
///
/// printf("%s", categories_message);
///
/// free(categories_message);
///
/// return 0;
/// }
/// ```
#[no_mangle]
pub extern "C" fn tcmb_evds_c_get_categories(
api_key: TcmbEvdsInput,
return_format: TcmbEvdsReturnFormat,
ascii_mode: bool
) -> TcmbEvdsResult {
let evds_result = generate_evds(api_key, return_format);
let evds = match evds_result {
Ok(evds) => evds,
Err(error_result) => return error_result,
};
// Requesting categories data from the Tcmb Evds.
let requested_response = evds_basic::get_categories(&evds);
return_response(requested_response, ascii_mode)
}
/// gets data groups from EVDS.
///
/// # Error
///
/// This function returns error when invalid mode, code, or api key is supplied or there is a bad internet connection.
///
/// # Example
///
/// ```C
///
/// #include "tcmb_evds_c.h"
///
///
/// int main() {
///
/// // declaration of required arguments.
/// unsigned int mode;
/// TcmbEvdsInput code;
/// TcmbEvdsInput api_key;
/// TcmbEvdsReturnFormat return_format;
/// bool ascii_mode;
///
///
/// // value assignments.
/// mode = 1;
///
/// code.input_ptr = "bie_yssk";
/// code.string_capacity = strlen(code.input_ptr);
///
/// api_key.input_ptr = "VALID_API_KEY";
/// api_key.string_capacity = strlen(api_key.input_ptr);
///
/// return_format = Json;
///
/// ascii_mode = false;
///
///
/// // requesting data.
/// TcmbEvdsResult advanced_data_group =
/// tcmb_evds_c_get_advanced_data_group(
/// mode,
/// code,
/// api_key,
/// return_format,
/// ascii_mode
/// );
///
///
/// // handling error and printing the result.
/// if (!tcmb_evds_c_is_error(advanced_data_group)) { printf("\nNO ERROR!\n"); };
/// printf("\nError: %s", tcmb_evds_c_is_error(advanced_data_group) ? "true" : "false");
///
/// char* advanced_data_group_message = calloc(advanced_data_group.string_capacity, sizeof(char));
/// memmove(
/// advanced_data_group_message,
/// advanced_data_group.output_ptr,
/// advanced_data_group.string_capacity * sizeof(char)
/// );
///
/// printf("%s", advanced_data_group_message);
///
/// free(advanced_data_group_message);
///
/// return 0;
/// }
/// ```
#[no_mangle]
pub extern "C" fn tcmb_evds_c_get_advanced_data_group(
mode: c_uint,
code: TcmbEvdsInput,
api_key: TcmbEvdsInput,
return_format: TcmbEvdsReturnFormat,
ascii_mode: bool
) -> TcmbEvdsResult {
let (rust_code, code_error_state) = code.get_input("code");
if code_error_state {
return TcmbEvdsResult::generate_result(rust_code, ReturnErrorC::ParameterError);
}
let evds_result = generate_evds(api_key, return_format);
let evds = match evds_result {
Ok(evds) => evds,
Err(error_result) => return error_result,
};
// Requesting advanced data group from the Tcmb Evds.
let requested_response = evds_basic::get_advanced_data_group(mode, &rust_code, &evds);
return_response(requested_response, ascii_mode)
}
/// gets series list from EVDS.
///
/// # Error
///
/// This function returns error when invalid code, or api_key is given or there is a bad internet connection.
///
/// # Example
///
/// ```C
///
/// #include "tcmb_evds_c.h"
///
///
/// int main() {
///
/// // declaration of required arguments.
/// TcmbEvdsInput code;
/// TcmbEvdsInput api_key;
/// TcmbEvdsReturnFormat return_format;
/// bool ascii_mode;
///
///
/// // value assignments.
/// code.input_ptr = "bie_yssk";
/// code.string_capacity = 8;
///
/// api_key.input_ptr = "VALID_API_KEY";
/// api_key.string_capacity = 10;
///
/// return_format = Csv;
///
/// ascii_mode = false;
///
///
/// // requesting data.
/// TcmbEvdsResult series_list = tcmb_evds_c_get_series_list(code, api_key, return_format, ascii_mode);
///
///
/// // handling error and printing the result.
/// if (!tcmb_evds_c_is_error(series_list)) { printf("\nNO ERROR!\n"); };
/// printf("\nError: %s", tcmb_evds_c_is_error(series_list) ? "true" : "false");
///
/// char* series_list_message = calloc(series_list.string_capacity, sizeof(char));
/// memmove(series_list_message, series_list.output_ptr, series_list.string_capacity * sizeof(char));
///
/// printf("%s", series_list_message);
///
/// free(series_list_message);
///
/// return 0;
/// }
/// ```
#[no_mangle]
pub extern "C" fn tcmb_evds_c_get_series_list(
code: evds_c::common_entities::TcmbEvdsInput,
api_key: TcmbEvdsInput,
return_format: TcmbEvdsReturnFormat,
ascii_mode: bool
) -> TcmbEvdsResult {
let (rust_code, code_error_state) = code.get_input("code");
if code_error_state {
return TcmbEvdsResult::generate_result(rust_code, ReturnErrorC::ParameterError);
}
let evds_result = generate_evds(api_key, return_format);
let evds = match evds_result {
Ok(evds) => evds,
Err(error_result) => return error_result,
};
// Requesting series list from the Tcmb Evds.
let requested_response = evds_basic::get_series_list(&rust_code, &evds);
return_response(requested_response, ascii_mode)
}
/// provides users an ability to check whether the result includes error or not.
///
/// # Example
///
/// ```C
/// // requesting data.
/// TcmbEvdsResult series_list = tcmb_evds_c_get_series_list(code, api_key, return_format, ascii_mode);
///
///
/// // handling error.
/// printf("\nError: %s", tcmb_evds_c_is_error(series_list) ? "true" : "false");
/// ```
#[no_mangle]
pub extern "C" fn tcmb_evds_c_is_error(result: TcmbEvdsResult) -> bool {
if let ReturnErrorC::NoError = result.error_type { return false; }
true
} |
mod cmd;
mod common;
mod feed;
mod schema;
mod websub;
use clap::Parser;
#[derive(Parser)]
enum Cmd {
Run(cmd::run::Opt),
Subscribe(cmd::subscribe::Opt),
Unsubscribe(cmd::unsubscribe::Opt),
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
env_logger::init();
let cmd = Cmd::parse();
match cmd {
Cmd::Run(opt) => cmd::run::main(opt).await,
Cmd::Subscribe(opt) => cmd::subscribe::main(opt).await,
Cmd::Unsubscribe(opt) => cmd::unsubscribe::main(opt).await,
}
}
|
extern crate diesel;
extern crate keyword_data_migration;
use keyword_data_migration::database_connection::establish_connection;
use keyword_data_migration::keywords::repository::save_keyword;
fn main() {
let connection = establish_connection();
match save_keyword(&connection, 6000 as i64, "dvd neuerscheinungen") {
Err(e) => println!("{:?}", e),
_ => (),
}
}
|
use std::any::Any;
use std::error::Error;
use crate::block::Block;
use crate::node::NodeTrait;
use crate::node::Node;
use std::collections::HashMap;
pub trait Resolver {
fn resolve<T: Any + Sized>(&self, path: Vec<String>) -> Result<(T, Vec<String>), Box<Error>>;
fn tree(&self, path: String, depth: u32) -> Vec<String>;
}
//todo define our own error struct, and return Result<Block,MyError>
type DecodeBlockFn<T> = fn(Block) -> Node<T>;
pub trait BlockDecoder<T: NodeTrait> {
fn register(&mut self, codec: u64, decoder: DecodeBlockFn<T>);
fn decode(&self, block: Block) -> Node<T>;
}
pub struct SafeBlockDecoder<T: NodeTrait> {
decoders: HashMap<u64, DecodeBlockFn<T>>
}
impl<T: NodeTrait> BlockDecoder<T> for SafeBlockDecoder<T> {
fn register(&mut self, codec: u64, decoder: fn(Block) -> Node<T>) {
//todo thread safe
self.decoders.insert(codec, decoder);
}
fn decode(&self, block: Block) -> Node<T> {
let codec = block.block.cid().codec.into();
let decoder = self.decoders.get(&codec).unwrap();
decoder(block)
}
}
#[cfg(test)]
mod tests {
use super::NodeTrait;
use crate::node::Link;
use crate::node::NodeStat;
use std::error::Error;
use crate::core::SafeBlockDecoder;
use std::collections::HashMap;
use crate::core::DecodeBlockFn;
use crate::block::BlockTrait;
use cid::Cid;
use crate::core::Resolver;
use std::any::Any;
use crate::core::BlockDecoder;
use crate::block::Block;
use crate::node::Node;
#[derive(Clone, Debug)]
pub struct MyNode {}
impl ToString for MyNode {
fn to_string(&self) -> String {
unimplemented!()
}
}
impl Resolver for MyNode {
fn resolve<T: Any + Sized>(&self, path: Vec<String>) -> Result<(T, Vec<String>), Box<Error>> {
unimplemented!()
}
fn tree(&self, path: String, depth: u32) -> Vec<String> {
unimplemented!()
}
}
impl BlockTrait for MyNode {
fn raw_data(&self) -> Vec<u8> {
unimplemented!()
}
fn cid(&self) -> Cid {
unimplemented!()
}
}
impl NodeTrait for MyNode {
fn resolve_link(&self, path: Vec<String>) -> Result<(Link, Vec<String>), Box<Error>> {
unimplemented!()
}
fn links(&self) -> Vec<Link> {
unimplemented!()
}
fn stat(&self) -> Result<NodeStat, Box<Error>> {
unimplemented!()
}
fn size(&self) -> Result<u64, Box<Error>> {
unimplemented!()
}
}
fn f(block: Block) -> Node<MyNode> {
unimplemented!()
}
#[test]
fn it_works() {
let hash_map: HashMap<u64, DecodeBlockFn<MyNode>> = HashMap::new();
let mut safe_block_decoder = SafeBlockDecoder {
decoders: hash_map
};
safe_block_decoder.register(1, f);
}
} |
#[allow(unused_variables)]
#[allow(dead_code)]
fn pancake_sort(mut old_slice: Vec<i32>) -> Vec<i32> {
let mut new_slice: Vec<i32> = vec!();
for count in 0..old_slice.len() {
// old & slow (presumably) way of
// finding the minimum value of our vec
//
// let mut min_value = old_slice[0];
// for i in &old_slice {
// match i.cmp(&mut min_value) {
// Ordering::Less => {
// min_value = *i;
// },
// _ => {}
// }
// }
// better way to find min value of vec:
let min_value = *old_slice.iter().min().unwrap();
let position_of_min_value = old_slice.iter().position(|i| *i == min_value).unwrap();
old_slice.remove(position_of_min_value);
new_slice.push(min_value);
}
new_slice
}
#[test]
fn no_value() {
assert_eq!(pancake_sort(vec!()), vec!());
}
#[test]
fn one_value() {
assert_eq!(pancake_sort(vec!(1)), vec!(1));
}
#[test]
fn lots_of_values() {
assert_eq!(pancake_sort(vec!(9, 1, 17, -2, -99, -80)), vec!(-99, -80, -2, 1, 9, 17));
}
|
pub mod pb {
tonic::include_proto!("grpc.examples.echo");
}
use futures::Stream;
use std::net::SocketAddr;
use std::pin::Pin;
use tokio::sync::mpsc;
use tonic::{transport::Server, Request, Response, Status, Streaming};
use pb::{EchoRequest, EchoResponse};
type EchoResult<T> = Result<Response<T>, Status>;
type ResponseStream = Pin<Box<dyn Stream<Item = Result<EchoResponse, Status>> + Send + Sync>>;
#[derive(Debug)]
pub struct EchoServer {
addr: SocketAddr,
}
#[tonic::async_trait]
impl pb::echo_server::Echo for EchoServer {
async fn unary_echo(&self, request: Request<EchoRequest>) -> EchoResult<EchoResponse> {
let message = format!("{} (from {})", request.into_inner().message, self.addr);
Ok(Response::new(EchoResponse { message }))
}
type ServerStreamingEchoStream = ResponseStream;
async fn server_streaming_echo(
&self,
_: Request<EchoRequest>,
) -> EchoResult<Self::ServerStreamingEchoStream> {
Err(Status::unimplemented("not implemented"))
}
async fn client_streaming_echo(
&self,
_: Request<Streaming<EchoRequest>>,
) -> EchoResult<EchoResponse> {
Err(Status::unimplemented("not implemented"))
}
type BidirectionalStreamingEchoStream = ResponseStream;
async fn bidirectional_streaming_echo(
&self,
_: Request<Streaming<EchoRequest>>,
) -> EchoResult<Self::BidirectionalStreamingEchoStream> {
Err(Status::unimplemented("not implemented"))
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let addrs = ["[::1]:50051", "[::1]:50052"];
let (tx, mut rx) = mpsc::unbounded_channel();
for addr in &addrs {
let addr = addr.parse()?;
let tx = tx.clone();
let server = EchoServer { addr };
let serve = Server::builder()
.add_service(pb::echo_server::EchoServer::new(server))
.serve(addr);
tokio::spawn(async move {
if let Err(e) = serve.await {
eprintln!("Error = {:?}", e);
}
tx.send(()).unwrap();
});
}
rx.recv().await;
Ok(())
} |
/// Producer for PHP code.
use ::indextree::NodeId;
use ::repr::Program;
use ::repr::variable::{Variable, VariableType};
use ::unindent::unindent;
// TODO: We want these code segments to be stored somewhere...
/// Create a preamble for php code.
fn preamble() -> String {
let preamble = unindent(&format!("
<?php>
namespace {};
", "Stub"));
// todo: Figure out namespace and includes.
preamble
}
pub fn output<T>(mut outstream: T, arena: &Program) where T: ::std::io::Write {
let preamble = preamble().into_bytes();
outstream.write(&preamble);
// todo: My indexree will probably store a HashMap for these. For now another linear search.
let mut structs = Vec::new();
for i in 0..arena.len() {
let i = NodeId(i);
let is_struct = {
let ref node = arena[i];
match node.downcast_ref::<Variable>() {
Some(var) => var.vartype == VariableType::Struct,
None => false
}
};
if is_struct {
structs.push(i);
}
}
for id in structs {
let s = arena[id].downcast_ref::<Variable>().unwrap();
// Preamble
let mut output = format!("class {} {{\n", s.name.camel_case());
// Fields
for child in id.children(arena).into_iter() {
let var = arena[child].downcast_ref::<Variable>().unwrap();
let declaration = format!("
/**
* {description}.
*
* @var {var_type}
*/
private ${var_name};\n",
description = var.description.as_ref().unwrap(),
var_type = var.vartype,
var_name = var.name.lower_camel_case()
);
output.push_str(&declaration);
}
outstream.write(unindent(&output).as_bytes());
}
// TODO: indentation
outstream.write(b"\n\n}\n");
outstream.flush();
}
pub fn construct(data: &DataTable) -> Program {
let program = &mut Arena::new();
let mut root = program.new_node(Code { ..Default::default() });
root.append(program, Code::new("<?php>"));
root.append(program, Code::new(r#"namespace \Blah"#));
for s in data.structures(program) {
root.append(program, Code::new("public class");
}
root.append(program, Code
}
|
use std::io::prelude::*;
use std::io;
use std::env;
use rand::Rng;
use std::net::{TcpListener, TcpStream, Shutdown};
use std::thread;
use std::sync::Arc;
use std::str::from_utf8;
fn main() {
let mut adress = String::new();
let mut count = String::new();
// io::stdin().read_line(&mut adress)
// .expect("Не удалось прочитать строку");
if let Some(arg1) = env::args().nth(1) {
adress = arg1;
}
if let Some(arg2) = env::args().nth(2) {
count = arg2;
}
adress = adress.trim().to_string();
match adress.find(':') {
None => {
let mut full_adress = String::from("0.0.0.0");
full_adress.push_str(":");
full_adress.push_str(&adress);
println!("{}", full_adress);
server(full_adress);
},
Some(_) => {
// io::stdin().read_line(&mut count)
// .expect("Не удалось прочитать строку");
let count_int = count.trim().parse::<i32>().unwrap();
//println!("{}", count_int);
let adress = Arc::new(adress);
for i in 1..count_int+1 {
println!("{}", i);
let adress = adress.clone();
thread::spawn(move|| {
client(adress.to_string());
});
}
}
}
let mut just_waiting = String::new();
io::stdin().read_line(&mut just_waiting)
.expect("Не удалось прочитать строку");
}
fn handle_client(mut stream: TcpStream) {
let mut data = [0 as u8; 20];
let mut server_key :String;
let mut server_protector = SessionProtector {hash:String::new()};
match stream.read(&mut data) {
Ok(size) => {
if size == 0
{ panic!("Получен хэш 0 длины");
}else{
let read_hash = from_utf8(&data).unwrap();
let mut read_hash = read_hash.to_string();
read_hash.retain(|c| c != 0 as char);
server_protector.hash = read_hash;
println!("Получен хэш: {}", server_protector.hash);
let msg = b"hash accept";
stream.write(msg).unwrap();
println!("Отправленно hash accept");
}
},
Err(_) => {
println!("Не удалось получить хэш {}", stream.peer_addr().unwrap());
stream.shutdown(Shutdown::Both).unwrap();
}
}
let server_protector = server_protector; // сделал хэш неизменяемым
loop{
match stream.read(&mut data) {
Ok(size) => {
if size == 0 {
println!("Обмен завершен, либо получен ключ длины 0");
println!("");
break;
}
let text = from_utf8(&data).unwrap();
println!("Получен ключ: {}", text);
// удаляем пустые символы
let mut prepare_session_key = text.to_string();
prepare_session_key.retain(|c| c != 0 as char);
server_key = server_protector.next_session_key(&prepare_session_key);
println!("Вычислен новый ключ сервера, {}",server_key);
stream.write(server_key.as_bytes()).unwrap();
println!("Отправлен новый ключ");
},
Err(_) => {
println!("Ошибка в соединении, разрываю его {}", stream.peer_addr().unwrap());
stream.shutdown(Shutdown::Both).unwrap();
break;
}
}
}
}
fn server(adress: String){
let listener = TcpListener::bind(adress).unwrap();
println!("Сервер слушает");
for stream in listener.incoming() {
match stream {
Ok(stream) => {
println!("Новое подключение: {}", stream.peer_addr().unwrap());
thread::spawn(move|| {
handle_client(stream)
});
}
Err(e) => {
println!("Ошибка: {}", e);
}
}
}
drop(listener);
}
fn client(adress: String) {
match TcpStream::connect(adress) {
Ok(mut stream) => {
println!("Подключение установленно");
let inint_hash_string = get_hash_str();
println!("Создан хэш: {}", inint_hash_string);
let mut init_session_key = get_session_key();
println!("Создан ключ: {}", init_session_key);
let client_protector = SessionProtector { hash: inint_hash_string };
let bytes_hash_string = client_protector.hash.as_bytes();
let mut bytes_client_key = init_session_key.as_bytes();
stream.write(bytes_hash_string).unwrap();
println!("Отправлен хэш");
let mut data = [0 as u8; 20];
match stream.read(&mut data) {
Ok(_) => {
let text = from_utf8(&data).unwrap();
println!("Ответ сервера: {}", text);
},
Err(e) => {
panic!("Не удалось убедиться в принятии хэша сервером: {}", e);
}
}
for i in 1..4 {
let mut data = [0 as u8; 20];
stream.write(bytes_client_key).unwrap();
println!("Отправлен ключ {}",i);
match stream.read(&mut data) {
Ok(size) => {
if size == 0 {
panic!("Прочитано 0 байт, ошибка");
}else{
let answer = from_utf8(&data).unwrap();
let mut answer_string = answer.to_string();
answer_string.retain(|c| c != 0 as char);
println!("Получен новый ключ сервера: {}", answer_string);
init_session_key = client_protector.next_session_key(&init_session_key);
println!("Вычислен новый ключ клиента: {}", init_session_key);
if answer_string == init_session_key {
println!("Ключи совпадают");
println!("");
bytes_client_key = init_session_key.as_bytes();
}else{
panic!("Ключи не совпадают,ошибка");
}
}
},
Err(e) => {
println!("Не удалось получить новый ключ: {}", e);
}
}
}
},
Err(e) => {
println!("Подключение не установлено: {}", e);
}
}
}
fn get_session_key() -> String {
let mut rand_string = String::new();
for _ in 1..11 {
let rand_f64 :f64 = rand::thread_rng().gen();
rand_string += &(((9.0*rand_f64+1.0) as i64).to_string());
}
rand_string
}
fn get_hash_str() -> String {
let mut rand_string = String::new();
for _ in 0..5 {
let rand_f64 :f64 = rand::thread_rng().gen();
rand_string += &(((6.0*rand_f64+1.0) as i64).to_string());
}
rand_string
}
struct SessionProtector {
hash: String,
}
impl SessionProtector{
fn next_session_key (&self, session_key : &String) -> String {
if self.hash == String::new(){
panic!("Hash code is empty");
}
let mut result :i64 = 0;
/* let session_key_bytes = session_key.as_bytes();
for i in 0..session_key_bytes.len() {
println!("{}", session_key_bytes[i]);
} */ // побайтовый просмотр строки на отсутствие лишних сиволов в строке
match session_key.trim().parse::<i64>() {
Ok(_) => {
for i in 0..self.hash.len() {
let hash_num_i = self.hash.get(i..i+1).unwrap().parse::<i64>().unwrap();
result += self.calc_hash(session_key, hash_num_i).parse::<i64>().unwrap();
}
}
Err(e) => {
panic!("Hash code contains non-digit letter {}", e);
}
}
let mut finish_string = String::from("0000000000");
let result_string = result.to_string();
let mut lenght = result_string.len();
if lenght > 10 {
lenght = 10;
}
finish_string += result_string.get(0..lenght).unwrap();
finish_string = finish_string.get(finish_string.len()-10..finish_string.len()).unwrap().to_string();
finish_string
}
fn calc_hash( &self, session_key: &String, val:i64) -> String{
match val {
1 => {
let mut return_string = String::from("00");
let op_with_session_key :i64 = session_key.get(0..5).unwrap().parse::<i64>().unwrap() % 97;
return_string += &op_with_session_key.to_string();
return_string = return_string.get(return_string.len()-2..).unwrap().to_string();
return return_string;
}
2 => {
let lenght = session_key.len();
let mut return_string = String::new();
for i in 1..lenght {
return_string += session_key.get(lenght-i..lenght-i+1).unwrap();
}
return_string += session_key.get(0..1).unwrap();
return return_string
}
3 => {
let mut return_string :String = session_key.get(session_key.len()-5..).unwrap().to_string();
return_string += session_key.get(0..5).unwrap();
return return_string;
}
4 => {
let mut num :i64 = 0;
let mut session_key_chars = session_key.chars();
session_key_chars.next();
for _ in 1..9 {
num += session_key_chars.next().unwrap().to_digit(10).unwrap() as i64 + 41;
}
let num_string = num.to_string();
return num_string
}
5 => {
let mut num :i64 = 0;
let mut ch :char;
let session_key_bytes = session_key.as_bytes();
for i in 0..session_key.len() {
ch = (session_key_bytes[i] ^ 43) as char;
if !ch.is_digit(10){
num += ch as i64;
} else {
num += ch.to_digit(10).unwrap() as i64;
}
}
let num_string = num.to_string();
return num_string
}
_ => {
let return_string :String = (session_key.parse::<i64>().unwrap()+val).to_string();
return return_string
}
}
}
}
|
use crate::unused_keywords::model::UnusedKeywordId;
use crate::unused_keywords::schema::unused_keyword_id;
use diesel::result::Error;
use diesel::{MysqlConnection, RunQueryDsl};
pub fn save_unused_keywords_batch<'a>(
conn: &MysqlConnection,
unused_keyword_ids: &Vec<UnusedKeywordId>,
) -> Result<(), Error> {
diesel::insert_or_ignore_into(unused_keyword_id::table)
.values(unused_keyword_ids)
.execute(conn)
.expect("Error saving new unused");
Ok(())
}
|
//////////////////////////////////////////////////
// General notes
//
// - Rust uses snake casing for functions and
// variables (like_this_example)
fn another_function() {
println!("another_function has been called.");
}
fn main() {
another_function();
//////////////////////////////////////////////
// Shadowing
//////////////////////////////////////////////
let x = 5;
let x = x + 1;
let x = x * 2;
println!("x is {}", x);
let x = "outer scope";
println!("x is {}", x);
{
let x = "inner scope";
println!("x is {}", x);
}
println!("x is {}", x);
//////////////////////////////////////////////
// Scalar types
//////////////////////////////////////////////
// Signed Integers
let _a: i8 = 0;
let _a: i16 = 0;
let _a: i32 = 0;
let _a: i64 = 0;
let _a: i128 = 0;
// Unsigned Integers
let _a: u8 = 0;
let _a: u16 = 0;
let _a: u32 = 0;
let _a: u64 = 0;
let _a: u128 = 0;
// Integer Literals
let _a = 98_222; // Decimal
let _a = 0xff; // Hex
let _a = 0o77; // Octal
let _a = 0b1111_0000; // Binary
let _a = b'A'; // Byte (u8 only)
// The default integer is i32.
// Integer Overflow
//
// The compiler will err out if it can find overflow errors
// in code. The default runtime behavior is to generate an
// Unrecoverable Error panic. If compiler with the --release
// flag, Rust will perform two's complement wrapping, eg. 256
// will become 0, 257 will become 1, etc.
//
// let overflow: i8 = 256;
// Floating point types
//
// When not specified, Rust uses f64 as the
// default floating point type.
//
let _a: f64 = 0.0;
let _a: f32 = 0.0;
// Boolean types
let _t = true;
let _f: bool = false;
// Character types
//
// The char type is 4 bytes in size and
// represents a Unicode Scalar Value.
let _c: char = 'z';
let _z = 'Z';
let heart_eyed_cat_emoji = '😻';
println!("heart eyed cat: {}", heart_eyed_cat_emoji);
//////////////////////////////////////////////
// Compound types
//////////////////////////////////////////////
// Tuple types
//
// - Have a fixed length
// - Can be different types
let _tup: (i32, f64, u8) = (500, 6.4, 1);
println!("_tup is ({}, {}, {})", _tup.0, _tup.1, _tup.2);
// Destructuring
let (x, y, z) = _tup;
println!("_tup is ({}, {}, {})", x, y, z);
println!("_tup is {:?}", _tup);
println!("_tup is {:#?}", _tup); // Pretty print
// Array types
//
// - Also fixed length
// - Same type
// - Allocated on the stack, rather than the heap
// - If an out of range index is specified at runtime,
// a panic will occur and terminate the program
let _arr = [1, 2, 3, 4, 5];
let _arr: [i32; 5] = [1, 2, 3, 4, 5]; // Explicit
println!("_arr: {:?}", _arr);
// Create a new array of 5 elements, all initialized
// with the number 3.
let _arr = [3; 5];
println!("_arr: {:?}", _arr);
}
|
#![allow(clippy::missing_safety_doc)]
#[allow(
non_upper_case_globals,
non_snake_case,
improper_ctypes,
non_camel_case_types
)]
#[doc(hidden)]
pub mod sys;
pub mod context;
pub mod device;
pub mod dim3;
pub mod error;
pub mod func;
// pub mod future;
pub mod init;
pub mod kernel_params;
pub mod mem;
pub mod module;
pub mod stream;
pub mod version;
pub struct Cuda;
pub use context::*;
pub use device::*;
pub use dim3::*;
pub(crate) use error::cuda_error;
pub use error::{CudaResult, ErrorCode};
pub use func::*;
// pub use future::*;
pub use kernel_params::*;
pub use mem::*;
pub use module::*;
pub use stream::*;
pub use version::*;
|
pub const COLOR_HEX_BLUE_1: &str = "#0e3569";
pub const COLOR_HEX_BLUE_2: &str = "#1960b2";
pub const COLOR_HEX_BLUE_3: &str = "#3a88e2";
pub const COLOR_HEX_BLUE_4: &str = "#5095e5";
pub const COLOR_HEX_BLUE_5: &str = "#a5c9f2";
pub const COLOR_HEX_GREEN_1: &str = "#0c3300";
pub const COLOR_HEX_GREEN_2: &str = "#00400e";
pub const COLOR_HEX_GREEN_3: &str = "#005813";
pub const COLOR_HEX_GREEN_4: &str = "#117401";
pub const COLOR_HEX_GREEN_5: &str = "#038d05";
/// Color can be used to configure colors of different elements on charts.
pub struct Color {
value: String,
}
impl Color {
/// Create color from hex string.
pub fn new_from_hex(hex: &str) -> Self {
Color {
value: String::from(hex),
}
}
/// Create color from (r, g, b) values.
pub fn new_from_rgb(r: u8, g: u8, b: u8) -> Self {
let value = format!("rgb({},{},{})", r, g, b);
Color { value }
}
}
impl std::fmt::Display for Color {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", self.value)
}
}
impl Default for Color {
fn default() -> Self {
Self::new_from_hex(COLOR_HEX_BLUE_2)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn new_from_hex() {
let color = Color::new_from_hex(COLOR_HEX_GREEN_5);
assert_eq!(color.value, COLOR_HEX_GREEN_5);
}
#[test]
fn new_from_rgb() {
let color = Color::new_from_rgb(253, 185, 200);
assert_eq!(color.value, "rgb(253,185,200)".to_string());
}
}
|
#[derive(Debug, Clone)]
pub struct Module {
pub decls: Vec<Declaration>,
}
#[derive(Debug, Clone)]
pub struct Script {
pub exprs: Vec<ExpressionHandle>,
}
#[derive(Debug, Clone)]
pub enum Declaration {
Struct(Struct),
Require(Require),
Import(Import),
ImportAll(ImportAll),
Function(Function),
}
#[derive(Debug, Clone, Copy)]
pub struct ExpressionHandle(pub hecs::Entity);
#[derive(Debug, Clone)]
pub struct Expression {
pub expr: ExpressionKind,
pub type_: Option<Type>,
}
#[derive(Debug, Clone)]
pub enum ExpressionKind {
IntrinsicCall(IntrinsicCall),
IntrinsicLiteral(IntrinsicLiteral),
Set(Set),
Name(Name),
Struct(Struct),
Make(Make),
Require(Require),
Import(Import),
ImportAll(ImportAll),
Function(Function),
Call(Call),
}
#[derive(Debug, Clone)]
pub enum IntrinsicCall {
Nop,
Clear,
Dump,
Int32WrappingAdd(Name, Name),
}
#[derive(Debug, Clone)]
pub enum IntrinsicLiteral {
Int32(String),
}
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct Name {
pub symbol: string_interner::DefaultSymbol,
}
#[derive(Debug, Clone)]
pub struct Set {
pub name: Name,
pub type_: Type,
pub expr: ExpressionHandle,
}
#[derive(Debug, Clone)]
pub struct Struct {
pub name: Name,
pub fields: Vec<StructField>,
}
#[derive(Debug, Clone)]
pub struct StructField {
pub name: Name,
pub type_: Type,
}
#[derive(Debug, Clone)]
pub enum Type {
Name(TypeName),
Intrinsic(TypeIntrinsic),
}
#[derive(Debug, Clone)]
pub struct TypeName(pub Name);
#[derive(Debug, Clone)]
pub enum TypeIntrinsic {
Nil,
Int32,
}
#[derive(Debug, Clone)]
pub struct Make {
pub name: Name,
pub fields: Vec<StructFieldInitializer>,
}
#[derive(Debug, Clone)]
pub struct StructFieldInitializer {
pub name: Name,
pub value: ExpressionHandle,
}
#[derive(Debug, Clone)]
pub struct Require {
pub module: ModuleId,
}
#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct ModuleId {
pub group: Name,
pub module: Name,
}
#[derive(Debug, Clone)]
pub struct Import {
pub module: ModuleId,
pub item: Name,
}
#[derive(Debug, Clone)]
pub struct ImportAll {
pub module: ModuleId,
}
#[derive(Debug, Clone)]
pub struct Function {
pub name: Name,
pub args: Vec<Argument>,
pub return_type: Type,
pub exprs: Vec<ExpressionHandle>,
}
#[derive(Debug, Clone)]
pub struct Argument {
pub name: Name,
pub type_: Type,
}
#[derive(Debug, Clone)]
pub struct Call {
pub name: Name,
pub args: Vec<ExpressionHandle>,
}
impl From<string_interner::DefaultSymbol> for Name {
fn from(s: string_interner::DefaultSymbol) -> Name {
Name {
symbol: s,
}
}
}
|
pub fn change(amount: i32, coins: Vec<i32>) -> i32 {
use std::collections::HashMap;
let mut cache = HashMap::<(i32, i32), i32>::new();
let mut coins = coins;
coins.sort();
fn core(cache: &mut HashMap<(i32, i32), i32>, amount: i32, coins: &[i32]) -> i32 {
if amount == 0 {
return 1
}
if coins.len() == 0 {
return 0
}
if coins.len() == 1 {
return if amount % coins[0] == 0 {
1
} else {
0
}
}
let key = (amount, coins.len() as i32);
if cache.contains_key(&key) {
return cache.get(&key).unwrap().clone()
}
let nc = coins.len();
let largest = coins[nc-1];
let max = amount / largest;
let mut counter = 0;
for i in 0..=max {
counter += core(cache, amount-i*largest, &coins[0..nc-1]);
}
cache.insert(key, counter);
counter
}
core(&mut cache, amount, &coins)
}
#[test]
fn test_change() {
assert_eq!(change(5, vec![1, 2, 5]), 4);
assert_eq!(change(3, vec![2]), 0);
assert_eq!(change(10, vec![10]), 1);
assert_eq!(change(500, vec![3, 5, 7, 8, 9, 10, 11]), 35502874);
}
|
pub fn fizz_buzz(value: i64) -> String {
if 0 == (value % 15) {
"Fizz Buzz".to_string()
} else if 0 == (value % 3) {
"Fizz".to_string()
} else if 0 == (value % 5) {
"Buzz".to_string()
} else {
value.to_string()
}
}
|
pub use self::ai::{Action, Ai, AiState, StateQuery};
pub use self::bounding_box::BoundingBox;
pub use self::cargo::Cargo;
pub use self::contract::{Contract, ItemType};
pub use self::course::{Course, Patrol};
pub use self::expiration::Expiration;
pub use self::owned_by::OwnedBy;
pub use self::port::Port;
pub use self::selection::{Controllable, Selected};
pub use self::ship::{Affiliation, Pirate, Ship};
pub mod ai;
pub mod bounding_box;
pub mod cargo;
pub mod contract;
pub mod course;
pub mod expiration;
pub mod owned_by;
pub mod port;
pub mod selection;
pub mod ship;
|
use std::net::SocketAddr;
use clap::{Parser, ValueEnum};
use client::run_client;
use hydroflow::tokio;
use hydroflow::util::{bind_udp_bytes, ipv4_resolve};
use server::run_server;
mod client;
mod protocol;
mod server;
#[derive(Clone, ValueEnum, Debug)]
enum Role {
Client,
Server,
}
#[derive(Clone, ValueEnum, Debug)]
enum GraphType {
Mermaid,
Dot,
Json,
}
#[derive(Parser, Debug)]
struct Opts {
#[clap(long)]
name: String,
#[clap(value_enum, long)]
role: Role,
#[clap(long, value_parser = ipv4_resolve)]
addr: Option<SocketAddr>,
#[clap(long, value_parser = ipv4_resolve)]
server_addr: Option<SocketAddr>,
#[clap(value_enum, long)]
graph: Option<GraphType>,
}
#[hydroflow::main]
async fn main() {
let opts = Opts::parse();
// if no addr was provided, we ask the OS to assign a local port by passing in "localhost:0"
let addr = opts
.addr
.unwrap_or_else(|| ipv4_resolve("localhost:0").unwrap());
// allocate `outbound` sink and `inbound` stream
let (outbound, inbound, addr) = bind_udp_bytes(addr).await;
println!("Listening on {:?}", addr);
match opts.role {
Role::Client => {
run_client(outbound, inbound, opts).await;
}
Role::Server => {
run_server(outbound, inbound, opts).await;
}
}
}
#[test]
fn test() {
use std::io::Write;
use hydroflow::util::{run_cargo_example, wait_for_process_output};
let (_server, _, mut server_output) =
run_cargo_example("chat", "--role server --name server --addr 127.0.0.1:11247");
let mut server_output_so_far = String::new();
wait_for_process_output(
&mut server_output_so_far,
&mut server_output,
"Server live!",
);
let (_client1, mut client1_input, mut client1_output) = run_cargo_example(
"chat",
"--role client --name client1 --server-addr 127.0.0.1:11247",
);
let (_client2, _, mut client2_output) = run_cargo_example(
"chat",
"--role client --name client2 --server-addr 127.0.0.1:11247",
);
let mut client1_output_so_far = String::new();
let mut client2_output_so_far = String::new();
wait_for_process_output(
&mut client1_output_so_far,
&mut client1_output,
"Client live!",
);
wait_for_process_output(
&mut client2_output_so_far,
&mut client2_output,
"Client live!",
);
client1_input.write_all(b"Hello\n").unwrap();
wait_for_process_output(
&mut client2_output_so_far,
&mut client2_output,
".*, .* client1: Hello",
);
}
|
struct Solution();
impl Solution {
pub fn can_win_nim(n: i32) -> bool {
// let n = n as usize;
// let mut win_nim_vec=vec![true;n];
// if n==1||n==2||n==3{
// return true;
// }
// let mut first=true;
// let mut second=true;
// let mut third=true;
// let mut fourth=true;
// for _ in 3..n{
// fourth=!(first&second&third);
// first=second;
// second=third;
// third=fourth;
// }
// fourth
// if n==1{
// return true;
// }
// let mod_=((n-1)/3)%2;//如果是5,5/3=1%2=1,如果是7/3=2,2%2=0,也就是mod_取0的时候返回true,否则返回false,如果是3,3/3=1%2=1,这是不对的
// if mod_==0{
// true
// }else{
// false
// }
//打印出来看,发现4的倍数是false,否则就是true
// if n%4==0{
// false
// }else{
// true
// }
//更节省内存
n%4!=0
}
}
fn main(){
// println!("{}",Solution::can_win_nim(201782680));
// println!("{}",Solution::can_win_nim(655678107
// ));
println!("{}",Solution::can_win_nim(30));
} |
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;
use anyhow::Result;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde_json::Value as JsonValue;
use svc_agent::{
error::Error as AgentError,
mqtt::{
OutgoingMessage, OutgoingRequest, OutgoingRequestProperties, ResponseStatus,
ShortTermTimingProperties, SubscriptionTopic,
},
request::Dispatcher,
AccountId, AgentId, Subscription,
};
use uuid::Uuid;
use super::types::*;
use super::{generate_correlation_data, ClientError, EventClient};
use super::{EVENT_LIST_LIMIT, MAX_EVENT_LIST_PAGES};
use crate::db::class::BoundedDateTimeTuple;
use crate::db::recording::Segments;
pub struct MqttEventClient {
me: AgentId,
event_account_id: AccountId,
dispatcher: Arc<Dispatcher>,
timeout: Option<Duration>,
api_version: String,
}
impl MqttEventClient {
#[allow(dead_code)]
pub fn new(
me: AgentId,
event_account_id: AccountId,
dispatcher: Arc<Dispatcher>,
timeout: Option<Duration>,
api_version: &str,
) -> Self {
Self {
me,
event_account_id,
dispatcher,
timeout,
api_version: api_version.to_string(),
}
}
fn response_topic(&self) -> Result<String, ClientError> {
let me = self.me.clone();
Subscription::unicast_responses_from(&self.event_account_id)
.subscription_topic(&me, &self.api_version)
.map_err(|e| AgentError::new(&e.to_string()).into())
}
fn build_reqp(&self, method: &str) -> Result<OutgoingRequestProperties, ClientError> {
let reqp = OutgoingRequestProperties::new(
method,
&self.response_topic()?,
&generate_correlation_data(),
ShortTermTimingProperties::new(Utc::now()),
);
Ok(reqp)
}
}
#[async_trait]
impl EventClient for MqttEventClient {
async fn read_room(&self, id: Uuid) -> Result<EventRoomResponse, ClientError> {
let reqp = self.build_reqp("room.read")?;
let payload = EventRoomReadPayload { id };
let msg = if let OutgoingMessage::Request(msg) =
OutgoingRequest::multicast(payload, reqp, &self.event_account_id, &self.api_version)
{
msg
} else {
unreachable!()
};
let request = self.dispatcher.request::<_, EventRoomResponse>(msg);
let payload_result = request.await;
let payload = payload_result.map_err(|e| ClientError::Payload(e.to_string()))?;
Ok(payload.extract_payload())
}
async fn create_room(
&self,
time: BoundedDateTimeTuple,
audience: String,
preserve_history: Option<bool>,
tags: Option<JsonValue>,
classroom_id: Option<Uuid>,
) -> Result<Uuid, ClientError> {
let reqp = self.build_reqp("room.create")?;
let payload = EventRoomCreatePayload {
audience,
time,
preserve_history,
tags,
classroom_id,
};
let msg = if let OutgoingMessage::Request(msg) =
OutgoingRequest::multicast(payload, reqp, &self.event_account_id, &self.api_version)
{
msg
} else {
unreachable!()
};
let request = self.dispatcher.request::<_, JsonValue>(msg);
let payload_result = if let Some(dur) = self.timeout {
tokio::time::timeout(dur, request)
.await
.map_err(|_e| ClientError::Timeout)?
} else {
request.await
};
let payload = payload_result.map_err(|e| ClientError::Payload(e.to_string()))?;
let data = payload.extract_payload();
let uuid_result = match data.get("id").and_then(|v| v.as_str()) {
Some(id) => Uuid::from_str(id).map_err(|e| ClientError::Payload(e.to_string())),
None => Err(ClientError::Payload(
"Missing id field in room.create response".into(),
)),
};
uuid_result
}
async fn update_room(&self, id: Uuid, update: RoomUpdate) -> Result<(), ClientError> {
let reqp = self.build_reqp("room.update")?;
let payload = EventRoomUpdatePayload {
id,
time: update.time,
classroom_id: update.classroom_id,
};
let msg = if let OutgoingMessage::Request(msg) =
OutgoingRequest::multicast(payload, reqp, &self.event_account_id, &self.api_version)
{
msg
} else {
unreachable!()
};
let request = self.dispatcher.request::<_, JsonValue>(msg);
let payload_result = if let Some(dur) = self.timeout {
tokio::time::timeout(dur, request)
.await
.map_err(|_e| ClientError::Timeout)?
} else {
request.await
};
let payload = payload_result.map_err(|e| ClientError::Payload(e.to_string()))?;
match payload.properties().status() {
ResponseStatus::OK => Ok(()),
_ => Err(ClientError::Payload(
"Event room update returned non 200 status".into(),
)),
}
}
async fn update_locked_types(
&self,
id: Uuid,
locked_types: LockedTypes,
) -> Result<(), ClientError> {
let reqp = self.build_reqp("room.locked_types")?;
let payload = EventRoomLockedTypesPayload { id, locked_types };
let msg = if let OutgoingMessage::Request(msg) =
OutgoingRequest::multicast(payload, reqp, &self.event_account_id, &self.api_version)
{
msg
} else {
unreachable!()
};
let request = self.dispatcher.request::<_, JsonValue>(msg);
let payload_result = if let Some(dur) = self.timeout {
tokio::time::timeout(dur, request)
.await
.map_err(|_e| ClientError::Timeout)?
} else {
request.await
};
let payload = payload_result.map_err(|e| ClientError::Payload(e.to_string()))?;
match payload.properties().status() {
ResponseStatus::OK => Ok(()),
_ => Err(ClientError::Payload(
"Event update_locked_types returned non 200 status".into(),
)),
}
}
async fn adjust_room(
&self,
event_room_id: Uuid,
started_at: DateTime<Utc>,
segments: Segments,
offset: i64,
) -> Result<(), ClientError> {
let reqp = self.build_reqp("room.adjust")?;
let payload = EventAdjustPayload {
id: event_room_id,
started_at,
segments,
offset,
};
let msg = if let OutgoingMessage::Request(msg) =
OutgoingRequest::multicast(payload, reqp, &self.event_account_id, &self.api_version)
{
msg
} else {
unreachable!()
};
let request = self.dispatcher.request::<_, JsonValue>(msg);
let payload_result = if let Some(dur) = self.timeout {
tokio::time::timeout(dur, request)
.await
.map_err(|_e| ClientError::Timeout)?
} else {
request.await
};
let payload = payload_result.map_err(|e| ClientError::Payload(e.to_string()))?;
match payload.properties().status() {
ResponseStatus::ACCEPTED => Ok(()),
status => {
let e = format!("Wrong status, expected 202, got {:?}", status);
Err(ClientError::Payload(e))
}
}
}
async fn commit_edition(&self, edition_id: Uuid, offset: i64) -> Result<(), ClientError> {
let reqp = self.build_reqp("edition.commit")?;
let payload = EventCommitPayload {
id: edition_id,
offset,
};
let msg = if let OutgoingMessage::Request(msg) =
OutgoingRequest::multicast(payload, reqp, &self.event_account_id, &self.api_version)
{
msg
} else {
unreachable!()
};
let request = self.dispatcher.request::<_, JsonValue>(msg);
let payload_result = if let Some(dur) = self.timeout {
tokio::time::timeout(dur, request)
.await
.map_err(|_e| ClientError::Timeout)?
} else {
request.await
};
let payload = payload_result.map_err(|e| ClientError::Payload(e.to_string()))?;
match payload.properties().status() {
ResponseStatus::ACCEPTED => Ok(()),
status => {
let e = format!("Wrong status, expected 202, got {:?}", status);
Err(ClientError::Payload(e))
}
}
}
async fn create_event(&self, payload: JsonValue) -> Result<(), ClientError> {
let reqp = self.build_reqp("event.create")?;
let msg = if let OutgoingMessage::Request(msg) =
OutgoingRequest::multicast(payload, reqp, &self.event_account_id, &self.api_version)
{
msg
} else {
unreachable!()
};
let request = self.dispatcher.request::<_, JsonValue>(msg);
let payload_result = if let Some(dur) = self.timeout {
tokio::time::timeout(dur, request)
.await
.map_err(|_e| ClientError::Timeout)?
} else {
request.await
};
let payload = payload_result.map_err(|e| ClientError::Payload(e.to_string()))?;
match payload.properties().status() {
ResponseStatus::CREATED => Ok(()),
status => {
let e = format!(
"Wrong status, expected 201, got {:?}, payload = {:?}",
status,
payload.payload()
);
Err(ClientError::Payload(e))
}
}
}
async fn list_events(&self, room_id: Uuid, kind: &str) -> Result<Vec<Event>, ClientError> {
let mut events = vec![];
let mut last_occurred_at = None;
for _ in 0..MAX_EVENT_LIST_PAGES {
let reqp = self.build_reqp("event.list")?;
let payload = EventListPayload {
room_id,
kind: kind.to_owned(),
last_occurred_at,
limit: EVENT_LIST_LIMIT,
};
let msg = if let OutgoingMessage::Request(msg) =
OutgoingRequest::multicast(payload, reqp, &self.event_account_id, &self.api_version)
{
msg
} else {
unreachable!()
};
let request = self.dispatcher.request::<_, Vec<Event>>(msg);
let response_result = if let Some(dur) = self.timeout {
tokio::time::timeout(dur, request)
.await
.map_err(|_e| ClientError::Timeout)?
} else {
request.await
};
let response = response_result.map_err(|e| ClientError::Payload(e.to_string()))?;
let status = response.properties().status();
if status != ResponseStatus::OK {
let e = format!("Wrong status, expected 200, got {:?}", status);
return Err(ClientError::Payload(e));
}
if let Some(last_event) = response.payload().last() {
last_occurred_at = Some(last_event.occurred_at());
let mut events_page = response.payload().to_vec();
events.append(&mut events_page);
} else {
break;
}
}
Ok(events)
}
async fn dump_room(&self, room_id: Uuid) -> Result<(), ClientError> {
let reqp = self.build_reqp("room.dump_events")?;
let payload = EventDumpEventsPayload { id: room_id };
let msg = if let OutgoingMessage::Request(msg) =
OutgoingRequest::multicast(payload, reqp, &self.event_account_id, &self.api_version)
{
msg
} else {
unreachable!()
};
let request = self.dispatcher.request::<_, JsonValue>(msg);
let payload_result = if let Some(dur) = self.timeout {
tokio::time::timeout(dur, request)
.await
.map_err(|_| ClientError::Timeout)?
} else {
request.await
};
let payload = payload_result.map_err(|e| ClientError::Payload(e.to_string()))?;
match payload.properties().status() {
ResponseStatus::ACCEPTED => Ok(()),
status => {
let e = format!("Wrong status, expected 202, got {:?}", status);
Err(ClientError::Payload(e))
}
}
}
}
|
//! Led Blinky Roulette example using the DWT peripheral for timing.
//!
//! Requires `cargo install cargo-flash`
//!
//! cargo-flash builds and uploads your code to run standalone. Its a more
//! traditional method of uploading firmware which doesn't maintain any
//! communication link for debug information.
//!
//! `cargo flash --example roulette --release`
#![no_std]
#![no_main]
use panic_halt as _;
use stm32f4xx_hal as hal;
use hal::{dwt::DwtExt, prelude::*, stm32};
#[cortex_m_rt::entry]
fn main() -> ! {
let dp = stm32::Peripherals::take().unwrap();
let cp = cortex_m::peripheral::Peripherals::take().unwrap();
// Set up the system clock.
let rcc = dp.RCC.constrain();
let clocks = rcc
.cfgr
.use_hse(8.mhz()) //discovery board has 8 MHz crystal for HSE
.sysclk(168.mhz())
.freeze();
// Create a delay abstraction based on DWT cycle counter
let dwt = cp.DWT.constrain(cp.DCB, clocks);
let mut delay = dwt.delay();
let gpiod = dp.GPIOD.split();
let mut led1 = gpiod.pd12.into_push_pull_output();
let mut led2 = gpiod.pd13.into_push_pull_output();
let mut led3 = gpiod.pd14.into_push_pull_output();
let mut led4 = gpiod.pd15.into_push_pull_output();
loop {
led1.set_high().unwrap();
led2.set_low().unwrap();
led3.set_low().unwrap();
led4.set_low().unwrap();
delay.delay_ms(333_u32);
led1.set_low().unwrap();
led2.set_high().unwrap();
led3.set_low().unwrap();
led4.set_low().unwrap();
delay.delay_ms(333_u32);
led1.set_low().unwrap();
led2.set_low().unwrap();
led3.set_high().unwrap();
led4.set_low().unwrap();
delay.delay_ms(333_u32);
led1.set_low().unwrap();
led2.set_low().unwrap();
led3.set_low().unwrap();
led4.set_high().unwrap();
delay.delay_ms(333_u32);
}
}
|
use crate::css;
use crate::error::Error;
use crate::sass::Value;
use crate::variablescope::Scope;
use std::default::Default;
/// the actual arguments of a function or mixin call.
///
/// Each argument has a Value. Arguments may be named.
/// If the optional name is None, the argument is positional.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd)]
pub struct CallArgs(Vec<(Option<String>, Value)>);
impl CallArgs {
pub fn new(v: Vec<(Option<String>, Value)>) -> Self {
CallArgs(v)
}
pub fn from_value(v: Value) -> Self {
match v {
Value::List(v, _, false) => {
CallArgs(v.into_iter().map(|v| (None, v)).collect())
}
v => CallArgs(vec![(None, v)]),
}
}
pub fn iter(&self) -> ::std::slice::Iter<(Option<String>, Value)> {
self.0.iter()
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn get(&self, index: usize) -> Option<&(Option<String>, Value)> {
self.0.get(index)
}
pub fn evaluate(
&self,
scope: &dyn Scope,
arithmetic: bool,
) -> Result<css::CallArgs, Error> {
if let [(None, Value::List(list, _, false))] = &self.0[..] {
if let [Value::Map(map), Value::Literal(mark)] = &list[..] {
if mark.is_unquoted() && mark.single_raw() == Some("...") {
return Ok(css::CallArgs(
map.iter()
.map(|(k, v)| {
Ok((
match k.do_evaluate(scope, arithmetic)? {
css::Value::Null => None,
css::Value::Literal(s, _) => Some(s),
x => {
return Err(Error::bad_value(
"string", &x,
))
}
},
v.do_evaluate(scope, arithmetic)?,
))
})
.collect::<Result<Vec<_>, Error>>()?,
));
}
}
}
let args = self.0
.iter()
.map(|&(ref n, ref v)| -> Result<(Option<String>, css::Value), Error> {
Ok((n.clone(), v.do_evaluate(scope, arithmetic)?))
})
.collect::<Result<Vec<_>, Error>>()?;
Ok(css::CallArgs(args))
}
}
impl Default for CallArgs {
fn default() -> Self {
CallArgs(vec![])
}
}
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
use core::cell::UnsafeCell;
use core::marker::PhantomData;
use core::mem;
use core::sync::atomic::AtomicU64;
use core::sync::atomic::Ordering::*;
use heapless::mpmc::Q64;
/// These constants describe the format of the combined queued and guard
/// counter. These counters are coupled to
/// 1. Allow for single atomic writes when creating and dropping signal guards
/// 2. Ensuring consistency between the counters at any given time. This
/// simplifies the logic in proving the correctness of the operations
///
/// The format of the counters is:
///
/// |<---------------------- 64 Bits ---------------------->|
/// |<-= 32 Bits Queued Count ->|<-- 32 Bits Guard Count -->|
///
const GUARD_COUNT_BITS: u8 = 32;
const GUARD_COUNT_UNIT: u64 = 1;
const GUARD_COUNT_MASK: u64 = (1 << GUARD_COUNT_BITS) - 1;
const QUEUED_COUNT_SHIFT: u8 = GUARD_COUNT_BITS;
const QUEUED_COUNT_UNIT: u64 = 1 << QUEUED_COUNT_SHIFT;
const QUEUED_COUNT_MASK: u64 = !GUARD_COUNT_MASK;
type Invocation<T> = (fn(T), T);
pub type SignalHandlerInput = libc::siginfo_t;
pub type SignalGuard = SequencerGuard<'static, SignalHandlerInput>;
pub type SignalAntiGuard = SequencerAntiGuard<'static, SignalHandlerInput>;
thread_local! {
pub(crate) static SIGNAL_HANLDER_SEQUENCER: GuardedSequencer<SignalHandlerInput>
= GuardedSequencer::with_initial_guard_count(1);
}
/// Marker struct that triggers "run-on-drop" behavior for defered invocations.
/// The phantom data here is to make the guard `!Send`
pub struct SequencerGuard<'a, T> {
owner: &'a GuardedSequencer<T>,
_phantom: PhantomData<UnsafeCell<()>>,
}
/// Marker struct that is the like the particle opposite of the signal guard.
/// When it is created, the count of guards decreases by one. If the new guard
/// count is zero, defered execitions will be evaluated and signals will not be
/// blocked. When this struct is dropped, the count of guards will be increased
/// by one guarding against signal interuptions again. The phantom data here is
/// to make the anti guard `!Send`
pub struct SequencerAntiGuard<'a, T> {
owner: &'a GuardedSequencer<T>,
_phantom: PhantomData<UnsafeCell<()>>,
}
impl<'a, T> SequencerGuard<'a, T> {
fn new(owner: &'a GuardedSequencer<T>) -> Self {
SequencerGuard {
owner,
_phantom: Default::default(),
}
}
}
impl<'a, T> SequencerAntiGuard<'a, T> {
fn new(owner: &'a GuardedSequencer<T>) -> Self {
SequencerAntiGuard {
owner,
_phantom: Default::default(),
}
}
}
impl<'a, T> Drop for SequencerGuard<'a, T> {
/// When the guard is dropped, we decrement the counter for guards, and if
/// this was the last one, we run any invocations that were added while the
/// guard(s) were active
fn drop(&mut self) {
self.owner.decrement_guard_count()
}
}
impl<'a, T> Drop for SequencerAntiGuard<'a, T> {
/// When an anti guard is dropped, we increment the guard count to return
/// the thread to a state that cannot be interrupted
fn drop(&mut self) {
self.owner.increment_guard_count()
}
}
pub(crate) struct GuardedSequencer<T> {
queue: Q64<Invocation<T>>,
guard_state: AtomicU64,
}
impl<T> GuardedSequencer<T> {
const fn with_initial_guard_count(guard_count: u32) -> Self {
GuardedSequencer {
queue: Q64::new(),
guard_state: AtomicU64::new(guard_count as u64),
}
}
// Enqueue the given invocation to be run when no guards are active.
fn enqueue_invocation(&self, invocation: Invocation<T>) {
self.queue.enqueue(invocation).ok().expect("Buffer full");
}
/// Drain the invocation. When a invocation is "drained", it is:
/// 1. Removed from the buffer
/// 2. Evaluated
/// 3. Counted as handled in the queued count
fn drain_one_invocation(&self) -> bool {
if let Some((handler, argument)) = self.queue.dequeue() {
handler(argument);
// Decrement the queued count stored with guard count
self.guard_state.fetch_sub(QUEUED_COUNT_UNIT, SeqCst);
true
} else {
false
}
}
/// Execute the invocations that are currently stored in the queue.
fn drain_invocations(&self) {
// While invocations are successfully being drained, keep draining. If
// draining one invocation is not successful, either there are no more
// or drain was interrupted and completed elsewhere. Either way there's
// nothing more to do here.
while self.drain_one_invocation() {}
}
/// Execute the given handler with the given argument when the current
/// thread has no active signal guards. If there are no guards, this
/// invocation will be run synchronously, otherwise, the invocation will be
/// stored and run asynchronously when guard count reaches zero
pub fn invoke(&self, handler: fn(T), argument: T) {
// Increment the guard and queued count in one atomic step
self.guard_state
.fetch_add(QUEUED_COUNT_UNIT + GUARD_COUNT_UNIT, SeqCst);
self.enqueue_invocation((handler, argument));
// decrementing the guard count here will either run the invocation
// that was just added or defer it depending respectively on whether
// this was the only guard or not
self.decrement_guard_count();
}
/// Increment the number of active guards by one
fn increment_guard_count(&self) {
self.guard_state.fetch_add(GUARD_COUNT_UNIT, Acquire);
}
/// Decrement the counter for guards, and if the count goes to zero, we run
/// any invocations that were added while the guard(s) were active
fn decrement_guard_count(&self) {
let prev_guard_state = self.guard_state.fetch_sub(GUARD_COUNT_UNIT, Release);
let prev_guard_count = prev_guard_state & GUARD_COUNT_MASK;
assert!(
prev_guard_count > 0,
"Signal guard count went negative indicating a bug"
);
// If this wasn't the last guard or if there were no invocations added,
// we are done
if prev_guard_count > 1 || prev_guard_state & QUEUED_COUNT_MASK == 0 {
return;
}
// Now it's our responsibility to execute all invocations
self.drain_invocations();
}
/// Create a guard on this sequencer. Invocations performed on this
/// sequencer will be deferred until the returned guard (and any others)
/// are dropped
fn guard<'a>(&'a self) -> SequencerGuard<'a, T> {
self.increment_guard_count();
SequencerGuard::new(self)
}
/// Create a guard on this sequencer without incrementing the guard count.
/// Think of this as taking ownership of a guard that someone else forgot.
/// Invocations performed on this sequencer will be deferred until the
/// returned guard (and any others) are dropped.
fn implicit_guard<'a>(&'a self) -> SequencerGuard<'a, T> {
assert!(
self.guard_state.load(Acquire) > 0,
"No implicit signal guard in place"
);
SequencerGuard::new(self)
}
/// Create a an anti guard on this sequencer. Until it is dropped, the
/// returned anti guard cancels out exactly one guard meaning if a single
/// guard exists and has defered invocations, those invocations will be
/// executed as soon as this anti guard is created, and any subsequent
/// invocations will be run immediately
fn anti_guard<'a>(&'a self) -> SequencerAntiGuard<'a, T> {
self.decrement_guard_count();
SequencerAntiGuard::new(self)
}
}
/// Get a static pointer to the the guarded sequencer for this thread
fn signal_handler_sequencer() -> &'static GuardedSequencer<SignalHandlerInput> {
// We are using some unsafe code here to convert the lifetime provided for
// the thread-local `.with` function into a static lifetime. This is safe
// because we are not passing the returned value to any other thread
SIGNAL_HANLDER_SEQUENCER.with(|sequencer| unsafe { mem::transmute::<_, &'static _>(sequencer) })
}
/// Execute the given handler with the given argument when the current
/// thread has no active signal guards. If there are no guards, this
/// invocation will be run synchronously, otherwise, the invocation will be
/// stored and run asynchronously when guard count reaches zero
pub fn invoke_guarded(handler: fn(SignalHandlerInput), siginfo: SignalHandlerInput) {
signal_handler_sequencer().invoke(handler, siginfo);
}
/// Enter a region where signals cannot interrupt invocation of the current
/// thread. This operation should be thought to have atomic-aquire ordering.
/// The exclusion zone will last until the returned guard is dropped
#[must_use]
pub fn enter_signal_exclusion_zone() -> SignalGuard {
signal_handler_sequencer().guard()
}
/// Enter an already-exiting region where signals cannot interrupt execution of
/// the current thread. The exclusion zone will last until the returned guard is
/// dropped
#[must_use]
pub fn enter_implicit_signal_exclusion_zone() -> SignalGuard {
signal_handler_sequencer().implicit_guard()
}
/// Re-enter an execution phase where signals can interrupt the current thread.
/// When the returned anti guard is dropped, a signal exclusion zone will be
/// resumed
#[must_use]
pub fn reenter_signal_inclusion_zone() -> SignalAntiGuard {
signal_handler_sequencer().anti_guard()
}
#[cfg(test)]
mod tests {
use std::cell::RefCell;
use std::mem;
use std::rc::Rc;
use super::*;
macro_rules! assert_interrupts_eq {
($received:ident, [$($v:ident),*]) => {
{
let to_compare : Vec<&'static str> = vec![$(stringify!($v)),*];
assert_eq!(&*$received.borrow(), &to_compare);
}
}
}
macro_rules! make_handlers {
($($handler:ident),*$(,)?) => {
$(
fn $handler(input: HandlerInput) {
let HandlerInput(_, log) = input;
log.borrow_mut().push(stringify!($handler));
}
macro_rules! $handler {
($sched:ident, $log:ident) => {
$sched.invoke($handler, HandlerInput($sched.clone(), $log.clone()))
}
}
)*
}
}
// Define the handlers we are goning to call
make_handlers! {
h1,
h2,
h3,
h4,
h5,
h6,
}
type InvocationLog = Rc<RefCell<Vec<&'static str>>>;
#[derive(Clone)]
struct HandlerInput(Rc<GuardedSequencer<HandlerInput>>, InvocationLog);
/// Test wrapper to do the cleanup we need and run each test in serial
fn run_guarded_sequencer_test<T>(t: T)
where
T: FnOnce(Rc<GuardedSequencer<HandlerInput>>, InvocationLog),
{
let handler_log = Rc::new(RefCell::new(Vec::new()));
let sequencer = Rc::new(GuardedSequencer::with_initial_guard_count(0));
t(sequencer.clone(), handler_log);
// Make sure if the test exits normally that all handlers were run
// and the guard/handler counts are returned to zero
assert_eq!(0, sequencer.guard_state.load(SeqCst));
assert!(sequencer.queue.dequeue().is_none());
}
#[test]
fn test_basic_handler_defer() {
run_guarded_sequencer_test(|sequencer, log| {
assert_interrupts_eq!(log, []);
// Running ungaurded should work immediately
h1!(sequencer, log);
assert_interrupts_eq!(log, [h1]);
// Running with one guard should defer the handler
{
let _g1 = sequencer.guard();
h2!(sequencer, log);
assert_interrupts_eq!(log, [h1]);
}
// until after the guard goes out of scope
assert_interrupts_eq!(log, [h1, h2]);
});
}
#[test]
fn test_defer_with_multiple_guards() {
run_guarded_sequencer_test(|sequencer, log| {
// Running with one guard should defer the handler
{
let _g1 = sequencer.guard();
h1!(sequencer, log);
assert_interrupts_eq!(log, []);
// Running with another guard should do the same
{
let _g2 = sequencer.guard();
h2!(sequencer, log);
assert_interrupts_eq!(log, []);
}
// Nothing should change when the first guard is dropped
assert_interrupts_eq!(log, []);
}
// When both guards are dropped, the handlers should run in the
// order they were received
assert_interrupts_eq!(log, [h1, h2]);
});
}
#[test]
fn test_defer_with_anti_guard() {
run_guarded_sequencer_test(|sequencer, log| {
// Running with one guard should defer the handler
{
let _g1 = sequencer.guard();
h1!(sequencer, log);
assert_interrupts_eq!(log, []);
// Running with an anti guard allows defered signals to run,
// and allow new new handlers to run immediately
{
let _ag = sequencer.anti_guard();
assert_interrupts_eq!(log, [h1]);
h2!(sequencer, log);
assert_interrupts_eq!(log, [h1, h2]);
}
// When the anti guard is gone, we return to a state where
// handlers are defered
h3!(sequencer, log);
assert_interrupts_eq!(log, [h1, h2]);
}
// When the guard is dropped, the handlers should run in the
// order they were received
assert_interrupts_eq!(log, [h1, h2, h3]);
});
}
#[test]
fn test_defer_with_implicit_guard() {
run_guarded_sequencer_test(|sequencer, log| {
// Create a guard and drop it without calling the destructor;
mem::forget(sequencer.guard());
h1!(sequencer, log);
assert_interrupts_eq!(log, []);
//To release that implicit guard, we enter an implicitly guarded
// zone
{
let _implicit_guard = sequencer.implicit_guard();
// Handlers are still deferred
h2!(sequencer, log);
assert_interrupts_eq!(log, []);
}
// Once the guard is dropped, deferred signals are run
assert_interrupts_eq!(log, [h1, h2]);
//and new handlers are run immediately
h3!(sequencer, log);
assert_interrupts_eq!(log, [h1, h2, h3]);
});
}
#[test]
fn test_nested_handling() {
run_guarded_sequencer_test(|sequencer, log| {
// Nothing prevents guards from being created and dropped within
// handler functions
fn nested_1(input_1: HandlerInput) {
let HandlerInput(sequencer, log) = input_1.clone();
h2!(sequencer, log);
let _g = sequencer.guard();
h3!(sequencer, log);
{
let _ag = sequencer.anti_guard();
h4!(sequencer, log);
}
sequencer.invoke(nested_2, input_1);
h5!(sequencer, log);
assert_interrupts_eq!(log, [h1, h2, h3, h4]);
}
fn nested_2(input_2: HandlerInput) {
let HandlerInput(sequencer, log) = input_2;
h6!(sequencer, log);
}
{
let _g = sequencer.guard();
h1!(sequencer, log);
sequencer.invoke(nested_1, HandlerInput(sequencer.clone(), log.clone()));
}
assert_interrupts_eq!(log, [h1, h2, h3, h4, h5, h6]);
});
}
#[test]
#[should_panic]
fn test_invalid_implicit_guard() {
run_guarded_sequencer_test(|sequencer, _| {
// Entering an implicit guard when one doesn't exist is an error
let _g = sequencer.implicit_guard();
})
}
#[test]
#[should_panic]
fn test_anti_guard_without_guard() {
run_guarded_sequencer_test(|sequencer, _| {
// Creating an anti guard outside of a guard is an error
let _ag = sequencer.anti_guard();
})
}
thread_local! {
static INVOKE_COUNT: AtomicU64 = AtomicU64::new(0);
}
fn test_signal_handler(_: SignalHandlerInput) {
INVOKE_COUNT.with(|counter| counter.fetch_add(1, SeqCst));
}
pub(crate) const DUMMY_SIGINFO: SignalHandlerInput = unsafe {
mem::transmute::<_, SignalHandlerInput>([0u8; mem::size_of::<SignalHandlerInput>()])
};
#[test]
fn test_signal_handling_guard() {
SIGNAL_HANLDER_SEQUENCER.with(|sequencer| {
// Reinitialize the guard state and queue just in case
sequencer.guard_state.store(1, SeqCst);
while sequencer.queue.dequeue().is_some() {}
INVOKE_COUNT.with(|counter| counter.store(0, SeqCst));
// Run through the functions just to check that we have our sanity
invoke_guarded(test_signal_handler, DUMMY_SIGINFO);
// We initialized the sequencer with an implicit guard, so
assert_eq!(0, INVOKE_COUNT.with(|count| count.load(SeqCst)));
{
let _g1 = enter_implicit_signal_exclusion_zone();
invoke_guarded(test_signal_handler, DUMMY_SIGINFO);
assert_eq!(0, INVOKE_COUNT.with(|count| count.load(SeqCst)));
}
assert_eq!(2, INVOKE_COUNT.with(|count| count.load(SeqCst)));
{
let _g2 = enter_signal_exclusion_zone();
invoke_guarded(test_signal_handler, DUMMY_SIGINFO);
assert_eq!(2, INVOKE_COUNT.with(|count| count.load(SeqCst)));
{
let _ag1 = reenter_signal_inclusion_zone();
assert_eq!(3, INVOKE_COUNT.with(|count| count.load(SeqCst)));
invoke_guarded(test_signal_handler, DUMMY_SIGINFO);
assert_eq!(4, INVOKE_COUNT.with(|count| count.load(SeqCst)));
}
invoke_guarded(test_signal_handler, DUMMY_SIGINFO);
assert_eq!(4, INVOKE_COUNT.with(|count| count.load(SeqCst)));
}
assert_eq!(5, INVOKE_COUNT.with(|count| count.load(SeqCst)));
})
}
}
|
//! The module contains a set of methods to merge cells together via [`Span`]s.
//!
//! [`Span`]: crate::settings::span::Span
use crate::{
grid::config::ColoredConfig,
grid::records::{ExactRecords, PeekableRecords, Records},
settings::TableOption,
};
/// Merge to combine duplicates together, using [`Span`].
///
/// [`Span`]: crate::settings::span::Span
#[derive(Debug)]
pub struct Merge;
impl Merge {
/// Vertical merge.
pub fn vertical() -> MergeDuplicatesVertical {
MergeDuplicatesVertical
}
/// Horizontal merge.
pub fn horizontal() -> MergeDuplicatesHorizontal {
MergeDuplicatesHorizontal
}
}
/// A modificator for [`Table`] which looks up for duplicates in columns and
/// in case of duplicate merges the cells together using [`Span`].
///
/// [`Table`]: crate::Table
/// [`Span`]: crate::settings::span::Span
#[derive(Debug)]
pub struct MergeDuplicatesVertical;
impl<R, D> TableOption<R, D, ColoredConfig> for MergeDuplicatesVertical
where
R: Records + PeekableRecords + ExactRecords,
{
fn change(self, records: &mut R, cfg: &mut ColoredConfig, _: &mut D) {
let count_rows = records.count_rows();
let count_cols = records.count_columns();
if count_rows == 0 || count_cols == 0 {
return;
}
for column in 0..count_cols {
let mut repeat_length = 0;
let mut repeat_value = String::new();
let mut repeat_is_set = false;
let mut last_is_row_span = false;
for row in (0..count_rows).rev() {
if last_is_row_span {
last_is_row_span = false;
continue;
}
// we need to mitigate messing existing spans
let is_cell_visible = cfg.is_cell_visible((row, column));
let is_row_span_cell = cfg.get_column_span((row, column)).is_some();
if !repeat_is_set {
if !is_cell_visible {
continue;
}
if is_row_span_cell {
continue;
}
repeat_length = 1;
repeat_value = records.get_text((row, column)).to_owned();
repeat_is_set = true;
continue;
}
if is_row_span_cell {
repeat_is_set = false;
last_is_row_span = true;
continue;
}
if !is_cell_visible {
repeat_is_set = false;
continue;
}
let text = records.get_text((row, column));
let is_duplicate = text == repeat_value;
if is_duplicate {
repeat_length += 1;
continue;
}
if repeat_length > 1 {
cfg.set_row_span((row + 1, column), repeat_length);
}
repeat_length = 1;
repeat_value = records.get_text((row, column)).to_owned();
}
if repeat_length > 1 {
cfg.set_row_span((0, column), repeat_length);
}
}
}
}
/// A modificator for [`Table`] which looks up for duplicates in rows and
/// in case of duplicate merges the cells together using [`Span`].
///
/// [`Table`]: crate::Table
/// [`Span`]: crate::settings::span::Span
#[derive(Debug)]
pub struct MergeDuplicatesHorizontal;
impl<R, D> TableOption<R, D, ColoredConfig> for MergeDuplicatesHorizontal
where
R: Records + PeekableRecords + ExactRecords,
{
fn change(self, records: &mut R, cfg: &mut ColoredConfig, _: &mut D) {
let count_rows = records.count_rows();
let count_cols = records.count_columns();
if count_rows == 0 || count_cols == 0 {
return;
}
for row in 0..count_rows {
let mut repeat_length = 0;
let mut repeat_value = String::new();
let mut repeat_is_set = false;
let mut last_is_col_span = false;
for column in (0..count_cols).rev() {
if last_is_col_span {
last_is_col_span = false;
continue;
}
// we need to mitigate messing existing spans
let is_cell_visible = cfg.is_cell_visible((row, column));
let is_col_span_cell = cfg.get_row_span((row, column)).is_some();
if !repeat_is_set {
if !is_cell_visible {
continue;
}
if is_col_span_cell {
continue;
}
repeat_length = 1;
repeat_value = records.get_text((row, column)).to_owned();
repeat_is_set = true;
continue;
}
if is_col_span_cell {
repeat_is_set = false;
last_is_col_span = true;
continue;
}
if !is_cell_visible {
repeat_is_set = false;
continue;
}
let text = records.get_text((row, column));
let is_duplicate = text == repeat_value;
if is_duplicate {
repeat_length += 1;
continue;
}
if repeat_length > 1 {
cfg.set_column_span((row, column + 1), repeat_length);
}
repeat_length = 1;
repeat_value = records.get_text((row, column)).to_owned();
}
if repeat_length > 1 {
cfg.set_column_span((row, 0), repeat_length);
}
}
}
}
|
#[doc = "Register `ADC_CFGR2` reader"]
pub type R = crate::R<ADC_CFGR2_SPEC>;
#[doc = "Register `ADC_CFGR2` writer"]
pub type W = crate::W<ADC_CFGR2_SPEC>;
#[doc = "Field `ROVSE` reader - ROVSE"]
pub type ROVSE_R = crate::BitReader;
#[doc = "Field `ROVSE` writer - ROVSE"]
pub type ROVSE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `JOVSE` reader - JOVSE"]
pub type JOVSE_R = crate::BitReader;
#[doc = "Field `JOVSE` writer - JOVSE"]
pub type JOVSE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `OVSS` reader - OVSS"]
pub type OVSS_R = crate::FieldReader;
#[doc = "Field `OVSS` writer - OVSS"]
pub type OVSS_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>;
#[doc = "Field `TROVS` reader - TROVS"]
pub type TROVS_R = crate::BitReader;
#[doc = "Field `TROVS` writer - TROVS"]
pub type TROVS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `ROVSM` reader - ROVSM"]
pub type ROVSM_R = crate::BitReader;
#[doc = "Field `ROVSM` writer - ROVSM"]
pub type ROVSM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RSHIFT1` reader - RSHIFT1"]
pub type RSHIFT1_R = crate::BitReader;
#[doc = "Field `RSHIFT1` writer - RSHIFT1"]
pub type RSHIFT1_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RSHIFT2` reader - RSHIFT2"]
pub type RSHIFT2_R = crate::BitReader;
#[doc = "Field `RSHIFT2` writer - RSHIFT2"]
pub type RSHIFT2_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RSHIFT3` reader - RSHIFT3"]
pub type RSHIFT3_R = crate::BitReader;
#[doc = "Field `RSHIFT3` writer - RSHIFT3"]
pub type RSHIFT3_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RSHIFT4` reader - RSHIFT4"]
pub type RSHIFT4_R = crate::BitReader;
#[doc = "Field `RSHIFT4` writer - RSHIFT4"]
pub type RSHIFT4_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `OSVR` reader - OSVR"]
pub type OSVR_R = crate::FieldReader<u16>;
#[doc = "Field `OSVR` writer - OSVR"]
pub type OSVR_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 10, O, u16>;
#[doc = "Field `LSHIFT` reader - LSHIFT"]
pub type LSHIFT_R = crate::FieldReader;
#[doc = "Field `LSHIFT` writer - LSHIFT"]
pub type LSHIFT_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>;
impl R {
#[doc = "Bit 0 - ROVSE"]
#[inline(always)]
pub fn rovse(&self) -> ROVSE_R {
ROVSE_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - JOVSE"]
#[inline(always)]
pub fn jovse(&self) -> JOVSE_R {
JOVSE_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bits 5:8 - OVSS"]
#[inline(always)]
pub fn ovss(&self) -> OVSS_R {
OVSS_R::new(((self.bits >> 5) & 0x0f) as u8)
}
#[doc = "Bit 9 - TROVS"]
#[inline(always)]
pub fn trovs(&self) -> TROVS_R {
TROVS_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - ROVSM"]
#[inline(always)]
pub fn rovsm(&self) -> ROVSM_R {
ROVSM_R::new(((self.bits >> 10) & 1) != 0)
}
#[doc = "Bit 11 - RSHIFT1"]
#[inline(always)]
pub fn rshift1(&self) -> RSHIFT1_R {
RSHIFT1_R::new(((self.bits >> 11) & 1) != 0)
}
#[doc = "Bit 12 - RSHIFT2"]
#[inline(always)]
pub fn rshift2(&self) -> RSHIFT2_R {
RSHIFT2_R::new(((self.bits >> 12) & 1) != 0)
}
#[doc = "Bit 13 - RSHIFT3"]
#[inline(always)]
pub fn rshift3(&self) -> RSHIFT3_R {
RSHIFT3_R::new(((self.bits >> 13) & 1) != 0)
}
#[doc = "Bit 14 - RSHIFT4"]
#[inline(always)]
pub fn rshift4(&self) -> RSHIFT4_R {
RSHIFT4_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bits 16:25 - OSVR"]
#[inline(always)]
pub fn osvr(&self) -> OSVR_R {
OSVR_R::new(((self.bits >> 16) & 0x03ff) as u16)
}
#[doc = "Bits 28:31 - LSHIFT"]
#[inline(always)]
pub fn lshift(&self) -> LSHIFT_R {
LSHIFT_R::new(((self.bits >> 28) & 0x0f) as u8)
}
}
impl W {
#[doc = "Bit 0 - ROVSE"]
#[inline(always)]
#[must_use]
pub fn rovse(&mut self) -> ROVSE_W<ADC_CFGR2_SPEC, 0> {
ROVSE_W::new(self)
}
#[doc = "Bit 1 - JOVSE"]
#[inline(always)]
#[must_use]
pub fn jovse(&mut self) -> JOVSE_W<ADC_CFGR2_SPEC, 1> {
JOVSE_W::new(self)
}
#[doc = "Bits 5:8 - OVSS"]
#[inline(always)]
#[must_use]
pub fn ovss(&mut self) -> OVSS_W<ADC_CFGR2_SPEC, 5> {
OVSS_W::new(self)
}
#[doc = "Bit 9 - TROVS"]
#[inline(always)]
#[must_use]
pub fn trovs(&mut self) -> TROVS_W<ADC_CFGR2_SPEC, 9> {
TROVS_W::new(self)
}
#[doc = "Bit 10 - ROVSM"]
#[inline(always)]
#[must_use]
pub fn rovsm(&mut self) -> ROVSM_W<ADC_CFGR2_SPEC, 10> {
ROVSM_W::new(self)
}
#[doc = "Bit 11 - RSHIFT1"]
#[inline(always)]
#[must_use]
pub fn rshift1(&mut self) -> RSHIFT1_W<ADC_CFGR2_SPEC, 11> {
RSHIFT1_W::new(self)
}
#[doc = "Bit 12 - RSHIFT2"]
#[inline(always)]
#[must_use]
pub fn rshift2(&mut self) -> RSHIFT2_W<ADC_CFGR2_SPEC, 12> {
RSHIFT2_W::new(self)
}
#[doc = "Bit 13 - RSHIFT3"]
#[inline(always)]
#[must_use]
pub fn rshift3(&mut self) -> RSHIFT3_W<ADC_CFGR2_SPEC, 13> {
RSHIFT3_W::new(self)
}
#[doc = "Bit 14 - RSHIFT4"]
#[inline(always)]
#[must_use]
pub fn rshift4(&mut self) -> RSHIFT4_W<ADC_CFGR2_SPEC, 14> {
RSHIFT4_W::new(self)
}
#[doc = "Bits 16:25 - OSVR"]
#[inline(always)]
#[must_use]
pub fn osvr(&mut self) -> OSVR_W<ADC_CFGR2_SPEC, 16> {
OSVR_W::new(self)
}
#[doc = "Bits 28:31 - LSHIFT"]
#[inline(always)]
#[must_use]
pub fn lshift(&mut self) -> LSHIFT_W<ADC_CFGR2_SPEC, 28> {
LSHIFT_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "ADC configuration register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`adc_cfgr2::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 [`adc_cfgr2::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct ADC_CFGR2_SPEC;
impl crate::RegisterSpec for ADC_CFGR2_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`adc_cfgr2::R`](R) reader structure"]
impl crate::Readable for ADC_CFGR2_SPEC {}
#[doc = "`write(|w| ..)` method takes [`adc_cfgr2::W`](W) writer structure"]
impl crate::Writable for ADC_CFGR2_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets ADC_CFGR2 to value 0"]
impl crate::Resettable for ADC_CFGR2_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
// Convert Intcode programs into a human readable assembly-like language.
use std::env;
use std::fs;
use std::process;
use std::collections::HashMap;
const MODE_POS: i64 = 0;
const MODE_IMM: i64 = 1;
const MODE_REL: i64 = 2;
const OP_HALT: i64 = 99;
const OP_ADD: i64 = 1;
const OP_MULTIPLY: i64 = 2;
const OP_INPUT: i64 = 3;
const OP_OUTPUT: i64 = 4;
const OP_JUMP_IF_TRUE: i64 = 5;
const OP_JUMP_IF_FALSE: i64 = 6;
const OP_LESS_THAN: i64 = 7;
const OP_EQUALS: i64 = 8;
const OP_REL_BASE_OFFSET: i64 = 9;
fn print_program(program: &Vec<i64>) {
let mut ip: i64 = 0;
let opcode_names: HashMap<i64, &str> = [
(OP_HALT, "halt"),
(OP_ADD, "add"),
(OP_MULTIPLY, "multiply"),
(OP_INPUT, "input"),
(OP_OUTPUT, "output"),
(OP_JUMP_IF_TRUE, "jump_if_true"),
(OP_JUMP_IF_FALSE, "jump_if_false"),
(OP_LESS_THAN, "less_than"),
(OP_EQUALS, "equals"),
(OP_REL_BASE_OFFSET, "rel_base_offset")
].iter().cloned().collect();
while ip < program.len() as i64 {
let instr = program[ip as usize];
let opcode = read_opcode(instr);
match opcode_names.get(&opcode) {
Some(name) => print!("{:0>4}: {: >16} ", ip, name),
None => print!("{:0>4}: {: >16} ", ip, opcode)
}
ip += 1;
let param_count: i64 = match opcode {
OP_ADD | OP_MULTIPLY | OP_LESS_THAN | OP_EQUALS => 3,
OP_JUMP_IF_TRUE | OP_JUMP_IF_FALSE => 2,
OP_INPUT | OP_OUTPUT | OP_REL_BASE_OFFSET => 1,
_ => 0
};
print_params(program, ip, param_count as usize);
print!("\n");
ip += param_count;
}
fn read_opcode(instr: i64) -> i64 {
instr % 100
}
fn read_param_mode(instr: i64, index: usize) -> i64 {
instr % 10_i64.pow((index + 3) as u32) / 10_i64.pow((index + 2) as u32)
}
fn print_params(program: &Vec<i64>, start: i64, count: usize) {
for i in 0..count {
let mode = read_param_mode(program[(start - 1) as usize], i);
let param = program[start as usize + i];
match mode {
MODE_POS => print!(" [{}]", param),
MODE_IMM => print!(" {}", param),
MODE_REL => print!(" [${}]", param),
_ => {}
}
}
}
}
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
eprintln!("Usage: {} <program_path>", args[0]);
process::exit(1);
}
let program = fs::read_to_string(&args[1])
.unwrap()
.trim()
.split(",")
.map(|x| x.parse::<i64>().unwrap())
.collect::<Vec<i64>>();
print_program(&program);
} |
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
pub const TITLE_KEY: &str = "title";
pub const GRAPH_KEY: &str = "graph";
|
use std::path::PathBuf;
use nu_engine::env::current_dir;
use nu_engine::CallExt;
use nu_path::canonicalize_with;
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{Category, Example, PipelineData, ShellError, Signature, Spanned, SyntaxShape};
use crate::filesystem::util::FileStructure;
const GLOB_PARAMS: nu_glob::MatchOptions = nu_glob::MatchOptions {
case_sensitive: true,
require_literal_separator: false,
require_literal_leading_dot: false,
};
#[derive(Clone)]
pub struct Cp;
#[allow(unused_must_use)]
impl Command for Cp {
fn name(&self) -> &str {
"cp"
}
fn usage(&self) -> &str {
"Copy files."
}
fn signature(&self) -> Signature {
Signature::build("cp")
.required("source", SyntaxShape::GlobPattern, "the place to copy from")
.required("destination", SyntaxShape::Filepath, "the place to copy to")
.switch(
"recursive",
"copy recursively through subdirectories",
Some('r'),
)
// TODO: add back in additional features
// .switch("force", "suppress error when no file", Some('f'))
// .switch("interactive", "ask user to confirm action", Some('i'))
.category(Category::FileSystem)
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let src: Spanned<String> = call.req(engine_state, stack, 0)?;
let dst: Spanned<String> = call.req(engine_state, stack, 1)?;
let recursive = call.has_flag("recursive");
let path = current_dir(engine_state, stack)?;
let source = path.join(src.item.as_str());
let destination = path.join(dst.item.as_str());
let sources: Vec<_> = match nu_glob::glob_with(&source.to_string_lossy(), GLOB_PARAMS) {
Ok(files) => files.collect(),
Err(e) => {
return Err(ShellError::SpannedLabeledError(
e.to_string(),
"invalid pattern".to_string(),
src.span,
))
}
};
if sources.is_empty() {
return Err(ShellError::SpannedLabeledError(
"No matches found".into(),
"no matches found".into(),
src.span,
));
}
if sources.len() > 1 && !destination.is_dir() {
return Err(ShellError::SpannedLabeledError(
"Destination must be a directory when copying multiple files".into(),
"is not a directory".into(),
dst.span,
));
}
let any_source_is_dir = sources.iter().any(|f| matches!(f, Ok(f) if f.is_dir()));
if any_source_is_dir && !recursive {
return Err(ShellError::SpannedLabeledError(
"Directories must be copied using \"--recursive\"".into(),
"resolves to a directory (not copied)".into(),
src.span,
));
}
for entry in sources.into_iter().flatten() {
let mut sources = FileStructure::new();
sources.walk_decorate(&entry, engine_state, stack)?;
if entry.is_file() {
let sources = sources.paths_applying_with(|(source_file, _depth_level)| {
if destination.is_dir() {
let mut dest = canonicalize_with(&dst.item, &path)?;
if let Some(name) = entry.file_name() {
dest.push(name);
}
Ok((source_file, dest))
} else {
Ok((source_file, destination.clone()))
}
})?;
for (src, dst) in sources {
if src.is_file() {
std::fs::copy(src, dst).map_err(|e| {
ShellError::SpannedLabeledError(e.to_string(), e.to_string(), call.head)
})?;
}
}
} else if entry.is_dir() {
let destination = if !destination.exists() {
destination.clone()
} else {
match entry.file_name() {
Some(name) => destination.join(name),
None => {
return Err(ShellError::SpannedLabeledError(
"Copy aborted. Not a valid path".into(),
"not a valid path".into(),
dst.span,
))
}
}
};
std::fs::create_dir_all(&destination).map_err(|e| {
ShellError::SpannedLabeledError(e.to_string(), e.to_string(), dst.span)
})?;
let sources = sources.paths_applying_with(|(source_file, depth_level)| {
let mut dest = destination.clone();
let path = canonicalize_with(&source_file, &path)?;
#[allow(clippy::needless_collect)]
let comps: Vec<_> = path
.components()
.map(|fragment| fragment.as_os_str())
.rev()
.take(1 + depth_level)
.collect();
for fragment in comps.into_iter().rev() {
dest.push(fragment);
}
Ok((PathBuf::from(&source_file), dest))
})?;
for (s, d) in sources {
if s.is_dir() && !d.exists() {
std::fs::create_dir_all(&d).map_err(|e| {
ShellError::SpannedLabeledError(e.to_string(), e.to_string(), dst.span)
})?;
}
if s.is_file() {
std::fs::copy(&s, &d).map_err(|e| {
ShellError::SpannedLabeledError(e.to_string(), e.to_string(), call.head)
})?;
}
}
}
}
Ok(PipelineData::new(call.head))
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Copy myfile to dir_b",
example: "cp myfile dir_b",
result: None,
},
Example {
description: "Recursively copy dir_a to dir_b",
example: "cp -r dir_a dir_b",
result: None,
},
]
}
// let mut sources =
// nu_glob::glob(&source.to_string_lossy()).map_or_else(|_| Vec::new(), Iterator::collect);
// if sources.is_empty() {
// return Err(ShellError::FileNotFound(call.positional[0].span));
// }
// if sources.len() > 1 && !destination.is_dir() {
// return Err(ShellError::MoveNotPossible {
// source_message: "Can't move many files".to_string(),
// source_span: call.positional[0].span,
// destination_message: "into single file".to_string(),
// destination_span: call.positional[1].span,
// });
// }
// let any_source_is_dir = sources.iter().any(|f| matches!(f, Ok(f) if f.is_dir()));
// let recursive: bool = call.has_flag("recursive");
// if any_source_is_dir && !recursive {
// return Err(ShellError::MoveNotPossibleSingle(
// "Directories must be copied using \"--recursive\"".to_string(),
// call.positional[0].span,
// ));
// }
// if interactive && !force {
// let mut remove: Vec<usize> = vec![];
// for (index, file) in sources.iter().enumerate() {
// let prompt = format!(
// "Are you shure that you want to copy {} to {}?",
// file.as_ref()
// .map_err(|err| ShellError::SpannedLabeledError(
// "Reference error".into(),
// err.to_string(),
// call.head
// ))?
// .file_name()
// .ok_or_else(|| ShellError::SpannedLabeledError(
// "File name error".into(),
// "Unable to get file name".into(),
// call.head
// ))?
// .to_str()
// .ok_or_else(|| ShellError::SpannedLabeledError(
// "Unable to get str error".into(),
// "Unable to convert to str file name".into(),
// call.head
// ))?,
// destination
// .file_name()
// .ok_or_else(|| ShellError::SpannedLabeledError(
// "File name error".into(),
// "Unable to get file name".into(),
// call.head
// ))?
// .to_str()
// .ok_or_else(|| ShellError::SpannedLabeledError(
// "Unable to get str error".into(),
// "Unable to convert to str file name".into(),
// call.head
// ))?,
// );
// let input = get_interactive_confirmation(prompt)?;
// if !input {
// remove.push(index);
// }
// }
// remove.reverse();
// for index in remove {
// sources.remove(index);
// }
// if sources.is_empty() {
// return Err(ShellError::NoFileToBeCopied());
// }
// }
// for entry in sources.into_iter().flatten() {
// let mut sources = FileStructure::new();
// sources.walk_decorate(&entry, engine_state, stack)?;
// if entry.is_file() {
// let sources = sources.paths_applying_with(|(source_file, _depth_level)| {
// if destination.is_dir() {
// let mut dest = canonicalize_with(&destination, &path)?;
// if let Some(name) = entry.file_name() {
// dest.push(name);
// }
// Ok((source_file, dest))
// } else {
// Ok((source_file, destination.clone()))
// }
// })?;
// for (src, dst) in sources {
// if src.is_file() {
// std::fs::copy(&src, dst).map_err(|e| {
// ShellError::MoveNotPossibleSingle(
// format!(
// "failed to move containing file \"{}\": {}",
// src.to_string_lossy(),
// e
// ),
// call.positional[0].span,
// )
// })?;
// }
// }
// } else if entry.is_dir() {
// let destination = if !destination.exists() {
// destination.clone()
// } else {
// match entry.file_name() {
// Some(name) => destination.join(name),
// None => {
// return Err(ShellError::FileNotFoundCustom(
// format!("containing \"{:?}\" is not a valid path", entry),
// call.positional[0].span,
// ))
// }
// }
// };
// std::fs::create_dir_all(&destination).map_err(|e| {
// ShellError::MoveNotPossibleSingle(
// format!("failed to recursively fill destination: {}", e),
// call.positional[1].span,
// )
// })?;
// let sources = sources.paths_applying_with(|(source_file, depth_level)| {
// let mut dest = destination.clone();
// let path = canonicalize_with(&source_file, &path)?;
// let components = path
// .components()
// .map(|fragment| fragment.as_os_str())
// .rev()
// .take(1 + depth_level);
// components.for_each(|fragment| dest.push(fragment));
// Ok((PathBuf::from(&source_file), dest))
// })?;
// for (src, dst) in sources {
// if src.is_dir() && !dst.exists() {
// std::fs::create_dir_all(&dst).map_err(|e| {
// ShellError::MoveNotPossibleSingle(
// format!(
// "failed to create containing directory \"{}\": {}",
// dst.to_string_lossy(),
// e
// ),
// call.positional[1].span,
// )
// })?;
// }
// if src.is_file() {
// std::fs::copy(&src, &dst).map_err(|e| {
// ShellError::MoveNotPossibleSingle(
// format!(
// "failed to move containing file \"{}\": {}",
// src.to_string_lossy(),
// e
// ),
// call.positional[0].span,
// )
// })?;
// }
// }
// }
// }
// Ok(PipelineData::new(call.head))
// }
}
|
use log::info;
use std::marker::PhantomData;
use std::path::Path;
use crate::env::{traits, ExtAccount};
use svm_types::{AccountAddr, Address, TemplateAddr};
use traits::{AccountDeserializer, AccountSerializer, AccountStore};
const ACCOUNT_KEY_PREFIX: &'static [u8] = b"acc:";
const ACCOUNT_TEMPLATE_KEY_PREFIX: &'static [u8] = b"acc-temp:";
/// [`AccountStore`] implementation backed-by `rocksdb`
pub struct RocksAccountStore<S, D> {
db: Rocksdb,
phantom: PhantomData<(S, D)>,
}
impl<S, D> AccountStore for RocksAccountStore<S, D>
where
S: AccountSerializer,
D: AccountDeserializer,
{
fn store(&mut self, account: &ExtAccount, addr: &AccountAddr) {
let addr = addr.inner();
info!("Storing an `Account`: \n{:?}", addr);
// 1) `Account Address` -> serialized `Account`
let key = self.account_key(addr);
let bytes = S::serialize(account);
let entry1 = (&key[..], &bytes[..]);
// 2) `Account Address` -> `Template Address`
let key = self.account_template_key(addr);
let addr = self.account_template_addr(account);
let entry2 = (&key[..], addr.as_slice());
self.db.set(&[entry1, entry2]);
}
fn load(&self, addr: &AccountAddr) -> Option<ExtAccount> {
let addr = addr.inner().as_slice();
info!("Loading an `Account` {:?}", addr);
self.db.get(addr).and_then(|hash| {
self.db
.get(&hash)
.and_then(|bytes| D::deserialize(&bytes[..]))
})
}
fn resolve_template_addr(&self, addr: &AccountAddr) -> Option<TemplateAddr> {
let addr = addr.inner().as_slice();
self.db.get(addr).and_then(|hash| {
self.db
.get(&hash)
.and_then(|bytes| D::deserialize_template_addr(&bytes[..]))
})
}
}
impl<S, D> RocksAccountStore<S, D>
where
S: AccountSerializer,
D: AccountDeserializer,
{
/// New instance
pub fn new<P>(path: P) -> Self
where
P: AsRef<Path>,
{
Self {
db: Rocksdb::new(path),
phantom: PhantomData,
}
}
#[inline]
fn account_key(&self, addr: &Address) -> Vec<u8> {
// Keys mapping from an `Account Address` to `Template Address`
// are of the pattern "account:ADDRESS"
let mut key = Vec::with_capacity(Address::len() + ACCOUNT_KEY_PREFIX.len());
key.extend_from_slice(ACCOUNT_KEY_PREFIX);
key.extend_from_slice(addr.as_slice());
key
}
#[inline]
fn account_template_key(&self, addr: &Address) -> Vec<u8> {
// Keys mapping from an `Account Address` to `Template Address`
// are of the pattern "acc-temp:ADDRESS"
let mut key = Vec::with_capacity(Address::len() + ACCOUNT_TEMPLATE_KEY_PREFIX.len());
key.extend_from_slice(ACCOUNT_TEMPLATE_KEY_PREFIX);
key.extend_from_slice(addr.as_slice());
key
}
#[inline]
fn account_template_addr<'a>(&self, account: &'a ExtAccount) -> &'a Address {
let addr = account.template_addr();
addr.inner()
}
}
|
//! Example of auth flow.
//!
//! To use this, set the environment variables `CLIENT_ID` and `CLIENT_SECRET` to their respective values.
//! See <https://dev.twitch.tv/docs/authentication#registration> for more information
//!
//! You'll need to add `http://localhost:10666/twitch/token` to your redirect URIs. (You can also override the url with the first argument passed to the executable)
use std::env;
use twitch_oauth2_auth_flow::auth_flow_surf;
#[tokio::main]
async fn main() {
let _ = dotenv::dotenv();
let client_id = get_var("CLIENT_ID");
let client_secret = get_var("CLIENT_SECRET");
let redirect_url = env::args()
.nth(1)
.unwrap_or_else(|| "http://localhost:10666/twitch/token".to_string());
let scopes = None;
let res = auth_flow_surf(&client_id, &client_secret, scopes, &redirect_url);
println!("got result: {:?}", res);
}
fn get_var(var: &'static str) -> String {
env::var(var).unwrap_or_else(|e| panic!("Could not get env {} - {}", var, e))
}
|
use std::collections::HashMap;
use crate::entity::{Ally, Enemy, Item, Pathway, Room};
pub type AllyMap = HashMap<String, Box<Ally>>;
pub type EnemyMap = HashMap<String, Box<Enemy>>;
pub type ItemMap = HashMap<String, Box<Item>>;
pub type PathMap = HashMap<String, Box<Pathway>>;
pub type RoomMap = HashMap<String, Box<Room>>;
|
use std::collections::HashMap;
static FILENAME: &str = "input/data";
type Ticket = Vec<usize>;
struct Rule {
name: String,
nums: Vec<(usize, usize)>,
}
fn main() {
let data = std::fs::read_to_string(FILENAME).expect("could not read file");
let rules = parse_rules(&data);
let nearby_tickets = parse_nearby(&data);
let ticket = parse_ticket(&data);
println!("{}", part_one(&nearby_tickets, &rules));
println!("{}", part_two(&ticket, &nearby_tickets, &rules));
}
fn part_one(nearby: &Vec<Ticket>, rules: &Vec<Rule>) -> usize {
let mut invalids: Vec<usize> = Vec::new();
for ticket in nearby {
for field in ticket {
if !is_field_valid_for_rules(*field, &rules) {
invalids.push(*field);
}
}
}
invalids.iter().sum()
}
fn part_two(my_ticket: &Vec<usize>, nearby_tickets: &Vec<Ticket>, rules: &Vec<Rule>) -> usize {
let mut nearby = nearby_tickets.clone();
// Wash away invalid tickets
nearby.retain(|ticket| is_ticket_valid(ticket.to_vec(), &rules));
let no_of_fields = nearby[0].len();
let mut mapper: HashMap<usize, &Rule> = HashMap::new();
while mapper.len() < no_of_fields {
for rule in rules {
let mut count = 0;
let mut last_valid_ix = 0;
for x in 0..no_of_fields {
if !mapper.contains_key(&x) && is_ix_valid(x, &nearby, &rule) {
count += 1;
last_valid_ix = x;
}
}
if count == 1 {
mapper.insert(last_valid_ix, rule);
}
}
}
mapper
.iter()
.filter(|(_, v)| v.name.starts_with("departure"))
.map(|(k, _i)| my_ticket[*k])
.product::<usize>()
}
fn is_ix_valid(ix: usize, tickets: &Vec<Vec<usize>>, rule: &Rule) -> bool {
for ticket in tickets {
if !is_field_valid(ticket[ix], rule) {
return false;
}
}
true
}
fn is_ticket_valid(ticket: Ticket, sections: &Vec<Rule>) -> bool {
for field in ticket {
if !is_field_valid_for_rules(field, sections) {
return false;
}
}
true
}
fn is_field_valid_for_rules(field: usize, rules: &Vec<Rule>) -> bool {
for rule in rules {
if is_field_valid(field, rule) {
return true;
}
}
false
}
fn is_field_valid(field: usize, rule: &Rule) -> bool {
return (field >= rule.nums[0].0 && field <= rule.nums[0].1)
|| (field >= rule.nums[1].0 && field <= rule.nums[1].1);
}
fn parse_nearby(data: &str) -> Vec<Ticket> {
let mut ticket_section = 0;
let mut nearby_tickets: Vec<Ticket> = Vec::new();
for line in data.lines() {
if line.is_empty() {
ticket_section += 1;
continue;
}
match ticket_section {
2 => {
if line == "nearby tickets:" {
continue;
}
let num_split: Vec<&str> = line.split(",").collect();
let mut nearby_ticket: Vec<usize> = Vec::new();
for num in num_split {
nearby_ticket.push(num.parse::<usize>().unwrap());
}
nearby_tickets.push(nearby_ticket);
}
_ => {}
}
}
nearby_tickets
}
fn parse_ticket(data: &str) -> Ticket {
let mut ticket_section = 0;
let mut ticket: Vec<usize> = Vec::new();
for line in data.lines() {
if line.is_empty() {
ticket_section += 1;
continue;
}
match ticket_section {
1 => {
if line == "your ticket:" {
continue;
}
let num_split: Vec<&str> = line.split(",").collect();
for num in num_split {
ticket.push(num.parse::<usize>().unwrap());
}
}
_ => {}
}
}
ticket
}
fn parse_rules(data: &str) -> Vec<Rule> {
let mut ticket_section = 0;
let mut rules: Vec<Rule> = Vec::new();
for line in data.lines() {
if line.is_empty() {
ticket_section += 1;
continue;
}
match ticket_section {
0 => {
let name_split: Vec<&str> = line.split(": ").collect();
let name = name_split[0];
let range_split: Vec<&str> = name_split[1].split(" or ").collect();
let num_split_1: Vec<&str> = range_split[0].split("-").collect();
let num_split_2: Vec<&str> = range_split[1].split("-").collect();
let rule = Rule {
name: name.to_string(),
nums: vec![
(
num_split_1[0].parse::<usize>().unwrap(),
num_split_1[1].parse::<usize>().unwrap(),
),
(
num_split_2[0].parse::<usize>().unwrap(),
num_split_2[1].parse::<usize>().unwrap(),
),
],
};
rules.push(rule);
}
_ => {}
}
}
rules
}
mod tests {
#[test]
fn test_part_one() {
let data = std::fs::read_to_string(super::FILENAME).expect("could not read file");
let rules = super::parse_rules(&data);
let nearby = super::parse_nearby(&data);
assert_eq!(32835, super::part_one(&nearby, &rules));
}
#[test]
fn test_part_two() {
let data = std::fs::read_to_string(super::FILENAME).expect("could not read file");
let rules = super::parse_rules(&data);
let nearby = super::parse_nearby(&data);
let ticket = super::parse_ticket(&data);
assert_eq!(514662805187, super::part_two(&ticket, &nearby, &rules));
}
}
|
//! A prelude that exports symbols commonly used in any situation that involves Styx.
pub use arch::Architecture;
pub use binder::Binder;
pub use builder::Builder;
pub use context::Context;
pub use diagnostics::{Diagnostic, DiagnosticBag};
pub use expr::Expr;
pub use lexer::{HasSpan, Token};
pub use typesystem::{Fun, Ty, Typed};
pub use visitor::Visitor;
pub use vm::{Vm, VirtualMachine};
/// A mutable reference to a `DiagnosticBag`.
pub type Diags<'r> = &'r mut DiagnosticBag;
/// A mutable reference to a `Context`.
pub type Ctx<'r, 'cx> = &'r mut Context<'cx>;
/// Parsing-related prelude.
pub mod parse {
pub use binder::Binder;
pub use diagnostics::{Diagnostic, DiagnosticBag, DiagnosticCodes, DiagnosticSeverity};
pub use lexer::*;
pub use parser::*;
pub use symbols::{Sym, Symbol};
}
|
#[doc = "Reader of register INTERP1_CTRL_LANE0"]
pub type R = crate::R<u32, super::INTERP1_CTRL_LANE0>;
#[doc = "Writer for register INTERP1_CTRL_LANE0"]
pub type W = crate::W<u32, super::INTERP1_CTRL_LANE0>;
#[doc = "Register INTERP1_CTRL_LANE0 `reset()`'s with value 0"]
impl crate::ResetValue for super::INTERP1_CTRL_LANE0 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `OVERF`"]
pub type OVERF_R = crate::R<bool, bool>;
#[doc = "Reader of field `OVERF1`"]
pub type OVERF1_R = crate::R<bool, bool>;
#[doc = "Reader of field `OVERF0`"]
pub type OVERF0_R = crate::R<bool, bool>;
#[doc = "Reader of field `CLAMP`"]
pub type CLAMP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `CLAMP`"]
pub struct CLAMP_W<'a> {
w: &'a mut W,
}
impl<'a> CLAMP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 22)) | (((value as u32) & 0x01) << 22);
self.w
}
}
#[doc = "Reader of field `FORCE_MSB`"]
pub type FORCE_MSB_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `FORCE_MSB`"]
pub struct FORCE_MSB_W<'a> {
w: &'a mut W,
}
impl<'a> FORCE_MSB_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 19)) | (((value as u32) & 0x03) << 19);
self.w
}
}
#[doc = "Reader of field `ADD_RAW`"]
pub type ADD_RAW_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `ADD_RAW`"]
pub struct ADD_RAW_W<'a> {
w: &'a mut W,
}
impl<'a> ADD_RAW_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18);
self.w
}
}
#[doc = "Reader of field `CROSS_RESULT`"]
pub type CROSS_RESULT_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `CROSS_RESULT`"]
pub struct CROSS_RESULT_W<'a> {
w: &'a mut W,
}
impl<'a> CROSS_RESULT_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17);
self.w
}
}
#[doc = "Reader of field `CROSS_INPUT`"]
pub type CROSS_INPUT_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `CROSS_INPUT`"]
pub struct CROSS_INPUT_W<'a> {
w: &'a mut W,
}
impl<'a> CROSS_INPUT_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16);
self.w
}
}
#[doc = "Reader of field `SIGNED`"]
pub type SIGNED_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SIGNED`"]
pub struct SIGNED_W<'a> {
w: &'a mut W,
}
impl<'a> SIGNED_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15);
self.w
}
}
#[doc = "Reader of field `MASK_MSB`"]
pub type MASK_MSB_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `MASK_MSB`"]
pub struct MASK_MSB_W<'a> {
w: &'a mut W,
}
impl<'a> MASK_MSB_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x1f << 10)) | (((value as u32) & 0x1f) << 10);
self.w
}
}
#[doc = "Reader of field `MASK_LSB`"]
pub type MASK_LSB_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `MASK_LSB`"]
pub struct MASK_LSB_W<'a> {
w: &'a mut W,
}
impl<'a> MASK_LSB_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x1f << 5)) | (((value as u32) & 0x1f) << 5);
self.w
}
}
#[doc = "Reader of field `SHIFT`"]
pub type SHIFT_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `SHIFT`"]
pub struct SHIFT_W<'a> {
w: &'a mut W,
}
impl<'a> SHIFT_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x1f) | ((value as u32) & 0x1f);
self.w
}
}
impl R {
#[doc = "Bit 25 - Set if either OVERF0 or OVERF1 is set."]
#[inline(always)]
pub fn overf(&self) -> OVERF_R {
OVERF_R::new(((self.bits >> 25) & 0x01) != 0)
}
#[doc = "Bit 24 - Indicates if any masked-off MSBs in ACCUM1 are set."]
#[inline(always)]
pub fn overf1(&self) -> OVERF1_R {
OVERF1_R::new(((self.bits >> 24) & 0x01) != 0)
}
#[doc = "Bit 23 - Indicates if any masked-off MSBs in ACCUM0 are set."]
#[inline(always)]
pub fn overf0(&self) -> OVERF0_R {
OVERF0_R::new(((self.bits >> 23) & 0x01) != 0)
}
#[doc = "Bit 22 - Only present on INTERP1 on each core. If CLAMP mode is enabled:\\n - LANE0 result is shifted and masked ACCUM0, clamped by a lower bound of\\n BASE0 and an upper bound of BASE1.\\n - Signedness of these comparisons is determined by LANE0_CTRL_SIGNED"]
#[inline(always)]
pub fn clamp(&self) -> CLAMP_R {
CLAMP_R::new(((self.bits >> 22) & 0x01) != 0)
}
#[doc = "Bits 19:20 - ORed into bits 29:28 of the lane result presented to the processor on the bus.\\n No effect on the internal 32-bit datapath. Handy for using a lane to generate sequence\\n of pointers into flash or SRAM."]
#[inline(always)]
pub fn force_msb(&self) -> FORCE_MSB_R {
FORCE_MSB_R::new(((self.bits >> 19) & 0x03) as u8)
}
#[doc = "Bit 18 - If 1, mask + shift is bypassed for LANE0 result. This does not affect FULL result."]
#[inline(always)]
pub fn add_raw(&self) -> ADD_RAW_R {
ADD_RAW_R::new(((self.bits >> 18) & 0x01) != 0)
}
#[doc = "Bit 17 - If 1, feed the opposite lane's result into this lane's accumulator on POP."]
#[inline(always)]
pub fn cross_result(&self) -> CROSS_RESULT_R {
CROSS_RESULT_R::new(((self.bits >> 17) & 0x01) != 0)
}
#[doc = "Bit 16 - If 1, feed the opposite lane's accumulator into this lane's shift + mask hardware.\\n Takes effect even if ADD_RAW is set (the CROSS_INPUT mux is before the shift+mask bypass)"]
#[inline(always)]
pub fn cross_input(&self) -> CROSS_INPUT_R {
CROSS_INPUT_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bit 15 - If SIGNED is set, the shifted and masked accumulator value is sign-extended to 32 bits\\n before adding to BASE0, and LANE0 PEEK/POP appear extended to 32 bits when read by processor."]
#[inline(always)]
pub fn signed(&self) -> SIGNED_R {
SIGNED_R::new(((self.bits >> 15) & 0x01) != 0)
}
#[doc = "Bits 10:14 - The most-significant bit allowed to pass by the mask (inclusive)\\n Setting MSB < LSB may cause chip to turn inside-out"]
#[inline(always)]
pub fn mask_msb(&self) -> MASK_MSB_R {
MASK_MSB_R::new(((self.bits >> 10) & 0x1f) as u8)
}
#[doc = "Bits 5:9 - The least-significant bit allowed to pass by the mask (inclusive)"]
#[inline(always)]
pub fn mask_lsb(&self) -> MASK_LSB_R {
MASK_LSB_R::new(((self.bits >> 5) & 0x1f) as u8)
}
#[doc = "Bits 0:4 - Logical right-shift applied to accumulator before masking"]
#[inline(always)]
pub fn shift(&self) -> SHIFT_R {
SHIFT_R::new((self.bits & 0x1f) as u8)
}
}
impl W {
#[doc = "Bit 22 - Only present on INTERP1 on each core. If CLAMP mode is enabled:\\n - LANE0 result is shifted and masked ACCUM0, clamped by a lower bound of\\n BASE0 and an upper bound of BASE1.\\n - Signedness of these comparisons is determined by LANE0_CTRL_SIGNED"]
#[inline(always)]
pub fn clamp(&mut self) -> CLAMP_W {
CLAMP_W { w: self }
}
#[doc = "Bits 19:20 - ORed into bits 29:28 of the lane result presented to the processor on the bus.\\n No effect on the internal 32-bit datapath. Handy for using a lane to generate sequence\\n of pointers into flash or SRAM."]
#[inline(always)]
pub fn force_msb(&mut self) -> FORCE_MSB_W {
FORCE_MSB_W { w: self }
}
#[doc = "Bit 18 - If 1, mask + shift is bypassed for LANE0 result. This does not affect FULL result."]
#[inline(always)]
pub fn add_raw(&mut self) -> ADD_RAW_W {
ADD_RAW_W { w: self }
}
#[doc = "Bit 17 - If 1, feed the opposite lane's result into this lane's accumulator on POP."]
#[inline(always)]
pub fn cross_result(&mut self) -> CROSS_RESULT_W {
CROSS_RESULT_W { w: self }
}
#[doc = "Bit 16 - If 1, feed the opposite lane's accumulator into this lane's shift + mask hardware.\\n Takes effect even if ADD_RAW is set (the CROSS_INPUT mux is before the shift+mask bypass)"]
#[inline(always)]
pub fn cross_input(&mut self) -> CROSS_INPUT_W {
CROSS_INPUT_W { w: self }
}
#[doc = "Bit 15 - If SIGNED is set, the shifted and masked accumulator value is sign-extended to 32 bits\\n before adding to BASE0, and LANE0 PEEK/POP appear extended to 32 bits when read by processor."]
#[inline(always)]
pub fn signed(&mut self) -> SIGNED_W {
SIGNED_W { w: self }
}
#[doc = "Bits 10:14 - The most-significant bit allowed to pass by the mask (inclusive)\\n Setting MSB < LSB may cause chip to turn inside-out"]
#[inline(always)]
pub fn mask_msb(&mut self) -> MASK_MSB_W {
MASK_MSB_W { w: self }
}
#[doc = "Bits 5:9 - The least-significant bit allowed to pass by the mask (inclusive)"]
#[inline(always)]
pub fn mask_lsb(&mut self) -> MASK_LSB_W {
MASK_LSB_W { w: self }
}
#[doc = "Bits 0:4 - Logical right-shift applied to accumulator before masking"]
#[inline(always)]
pub fn shift(&mut self) -> SHIFT_W {
SHIFT_W { w: self }
}
}
|
// xfail-win32
// error-pattern:ran out of stack
// Test that the task fails after hiting the recursion limit, but
// that it doesn't bring down the whole proc
fn main() {
task::spawn {||
task::unsupervise();
fn f() { f() };
f();
};
} |
use crate::shims::Error;
use editor::consts::FILE_SAVE_SUFFIX;
use editor::input::keyboard::Key;
use editor::tool::{SelectAppendMode, ToolType};
use editor::Color as InnerColor;
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn file_save_suffix() -> String {
FILE_SAVE_SUFFIX.into()
}
#[wasm_bindgen]
pub fn i32_max() -> i32 {
i32::MAX
}
#[wasm_bindgen]
pub fn i32_min() -> i32 {
i32::MIN
}
#[wasm_bindgen]
pub struct Color(InnerColor);
#[wasm_bindgen]
impl Color {
#[wasm_bindgen(constructor)]
pub fn new(red: f32, green: f32, blue: f32, alpha: f32) -> Result<Color, JsValue> {
match InnerColor::from_rgbaf32(red, green, blue, alpha) {
Some(v) => Ok(Self(v)),
None => Err(Error::new("invalid color").into()),
}
}
}
impl Color {
pub fn inner(&self) -> InnerColor {
self.0
}
}
macro_rules! match_string_to_enum {
(match ($e:expr) {$($var:ident),* $(,)?}) => {
match $e {
$(
stringify!($var) => Some($var),
)*
_ => None
}
};
}
pub fn translate_tool(name: &str) -> Option<ToolType> {
use ToolType::*;
match_string_to_enum!(match (name) {
Select,
Crop,
Navigate,
Eyedropper,
Text,
Fill,
Gradient,
Brush,
Heal,
Clone,
Patch,
BlurSharpen,
Relight,
Path,
Pen,
Freehand,
Spline,
Line,
Rectangle,
Ellipse,
Shape
})
}
pub fn translate_append_mode(name: &str) -> Option<SelectAppendMode> {
use SelectAppendMode::*;
match_string_to_enum!(match (name) {
New,
Add,
Subtract,
Intersect
})
}
pub fn translate_key(name: &str) -> Key {
log::trace!("pressed key: {}", name);
use Key::*;
match name.to_lowercase().as_str() {
"a" => KeyA,
"b" => KeyB,
"c" => KeyC,
"d" => KeyD,
"e" => KeyE,
"f" => KeyF,
"g" => KeyG,
"h" => KeyH,
"i" => KeyI,
"j" => KeyJ,
"k" => KeyK,
"l" => KeyL,
"m" => KeyM,
"n" => KeyN,
"o" => KeyO,
"p" => KeyP,
"q" => KeyQ,
"r" => KeyR,
"s" => KeyS,
"t" => KeyT,
"u" => KeyU,
"v" => KeyV,
"w" => KeyW,
"x" => KeyX,
"y" => KeyY,
"z" => KeyZ,
"0" => Key0,
"1" => Key1,
"2" => Key2,
"3" => Key3,
"4" => Key4,
"5" => Key5,
"6" => Key6,
"7" => Key7,
"8" => Key8,
"9" => Key9,
"enter" => KeyEnter,
"=" => KeyEquals,
"+" => KeyPlus,
"-" => KeyMinus,
"shift" => KeyShift,
// When using linux + chrome + the neo keyboard layout, the shift key is recognized as caps
"capslock" => KeyShift,
"control" => KeyControl,
"delete" => KeyDelete,
"backspace" => KeyBackspace,
"alt" => KeyAlt,
"escape" => KeyEscape,
"tab" => KeyTab,
"arrowup" => KeyArrowUp,
"arrowdown" => KeyArrowDown,
"arrowleft" => KeyArrowLeft,
"arrowright" => KeyArrowRight,
"[" => KeyLeftBracket,
"]" => KeyRightBracket,
"{" => KeyLeftCurlyBracket,
"}" => KeyRightCurlyBracket,
"pageup" => KeyPageUp,
"pagedown" => KeyPageDown,
_ => UnknownKey,
}
}
|
// Copyright 2019 The Grin Developers
//
// 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.
//! Implementation specific error types
use crate::core::libtx;
use crate::keychain;
use crate::libwallet;
use crate::util::secp;
use failure::{Backtrace, Context, Fail};
use grin_wallet_util::OnionV3AddressError;
use std::env;
use std::error::Error as StdError;
use std::fmt::{self, Display};
/// Error definition
#[derive(Debug)]
pub struct Error {
pub inner: Context<ErrorKind>,
}
/// Wallet errors, mostly wrappers around underlying crypto or I/O errors.
#[derive(Clone, Eq, PartialEq, Debug, Fail)]
pub enum ErrorKind {
/// LibTX Error
#[fail(display = "LibTx Error, {}", _0)]
LibTX(libtx::ErrorKind),
/// LibWallet Error
#[fail(display = "LibWallet Error, {}", _0)]
LibWallet(String),
/// Keychain error
#[fail(display = "Keychain error, {}", _0)]
Keychain(keychain::Error),
/// Onion V3 Address Error
#[fail(display = "Onion V3 Address Error, {}", _0)]
OnionV3Address(OnionV3AddressError),
/// Error when formatting json
#[fail(display = "IO error, {}", _0)]
IO(String),
/// Secp Error
#[fail(display = "Secp error, {}", _0)]
Secp(String),
/// Error when formatting json
#[fail(display = "Serde JSON error, {}", _0)]
Format(String),
/// Wallet seed already exists
#[fail(display = "Wallet seed file exists: {}", _0)]
WalletSeedExists(String),
/// Wallet seed doesn't exist
#[fail(display = "Wallet seed doesn't exist error")]
WalletSeedDoesntExist,
/// Wallet seed doesn't exist
#[fail(display = "Wallet doesn't exist at {}. {}", _0, _1)]
WalletDoesntExist(String, String),
/// Enc/Decryption Error
#[fail(display = "Enc/Decryption error (check password?), {}", _0)]
Encryption(String),
/// BIP 39 word list
#[fail(display = "BIP39 Mnemonic (word list) Error, {}", _0)]
Mnemonic(String),
/// Command line argument error
#[fail(display = "{}", _0)]
ArgumentError(String),
/// Generating ED25519 Public Key
#[fail(display = "Error generating ed25519 secret key: {}", _0)]
ED25519Key(String),
/// Checking for onion address
#[fail(display = "Address is not an Onion v3 Address: {}", _0)]
NotOnion(String),
/// API Error
#[fail(display = "Adapter Callback Error, {}", _0)]
ClientCallback(String),
/// Tor Configuration Error
#[fail(display = "Tor Config Error: {}", _0)]
TorConfig(String),
/// Tor Process error
#[fail(display = "Tor Process Error: {}", _0)]
TorProcess(String),
/// Error contacting wallet API
#[fail(display = "Wallet Communication Error: {}", _0)]
WalletComms(String),
/// Listener is closed issue
#[fail(display = "{} listener is closed! consider using `listen` first.", _0)]
ClosedListener(String),
/// MQS generic error
#[fail(display = "MQS error: {}", _0)]
MqsGenericError(String),
/// Address generic error
#[fail(display = "Address error: {}", _0)]
AddressGenericError(String),
/// Get MQS invalid response
#[fail(display = "{} Sender returned invalid response.", _0)]
MqsInvalidRespose(String),
/// Other
#[fail(display = "Generic error: {}", _0)]
GenericError(String),
#[fail(display = "unkown address!, {}", _0)]
UnknownAddressType(String),
#[fail(display = "could not parse `{}` to a https address!", 0)]
HttpsAddressParsingError(String),
#[fail(display = "Swap message error, {}", _0)]
SwapMessageGenericError(String),
#[fail(display = "Swap deal not found error, {}", _0)]
SwapDealGenericError(String),
#[fail(display = "Error in getting swap nodes info, {}", _0)]
SwapNodesObtainError(String),
#[fail(display = "proof address mismatch {}, {}!", _0, _1)]
ProofAddressMismatch(String, String),
}
impl Fail for Error {
fn cause(&self) -> Option<&dyn Fail> {
self.inner.cause()
}
fn backtrace(&self) -> Option<&Backtrace> {
self.inner.backtrace()
}
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let show_bt = match env::var("RUST_BACKTRACE") {
Ok(r) => r == "1",
Err(_) => false,
};
let backtrace = match self.backtrace() {
Some(b) => format!("{}", b),
None => String::from("Unknown"),
};
let inner_output = format!("{}", self.inner,);
let backtrace_output = format!("\nBacktrace: {}", backtrace);
let mut output = inner_output;
if show_bt {
output.push_str(&backtrace_output);
}
Display::fmt(&output, f)
}
}
impl Error {
/// get kind
pub fn kind(&self) -> ErrorKind {
self.inner.get_context().clone()
}
/// get cause
pub fn cause(&self) -> Option<&dyn Fail> {
self.inner.cause()
}
/// get backtrace
pub fn backtrace(&self) -> Option<&Backtrace> {
self.inner.backtrace()
}
}
impl From<ErrorKind> for Error {
fn from(kind: ErrorKind) -> Error {
Error {
inner: Context::new(kind),
}
}
}
impl From<Context<ErrorKind>> for Error {
fn from(inner: Context<ErrorKind>) -> Error {
Error { inner: inner }
}
}
impl From<keychain::Error> for Error {
fn from(error: keychain::Error) -> Error {
Error {
inner: Context::new(ErrorKind::Keychain(error)),
}
}
}
// we have to use e.description because of the bug at rust-secp256k1-zkp
#[allow(deprecated)]
impl From<secp::Error> for Error {
fn from(error: secp::Error) -> Error {
Error {
// secp::Error to_string is broken, in past biilds.
inner: Context::new(ErrorKind::Secp(format!("{}", error.description()))),
}
}
}
#[warn(deprecated)]
impl From<libwallet::Error> for Error {
fn from(error: libwallet::Error) -> Error {
Error {
inner: Context::new(ErrorKind::LibWallet(format!("{}", error))),
}
}
}
impl From<libtx::Error> for Error {
fn from(error: libtx::Error) -> Error {
Error {
inner: Context::new(ErrorKind::LibTX(error.kind())),
}
}
}
impl From<OnionV3AddressError> for Error {
fn from(error: OnionV3AddressError) -> Error {
Error::from(ErrorKind::OnionV3Address(error))
}
}
|
use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion};
use tabled::{
settings::{object::Segment, Alignment, Modify, Padding, Style},
Table, Tabled,
};
macro_rules! table_bench {
($name:ident, $table:expr, $( $modificator:expr ),*) => {
pub fn $name(c: &mut Criterion) {
let mut group = c.benchmark_group(stringify!($name));
for size in [1, 4, 8, 64, 512, 1024] {
group.bench_with_input(BenchmarkId::from_parameter(size), &size, |b, &size| {
let entry = $table;
let data = vec![entry; size];
#[allow(unused_mut)]
let mut table = Table::new(data);
$(table.with($modificator);)*
b.iter(|| {
let _ = black_box(table.to_string());
});
});
}
group.finish();
}
};
($name:ident, $table:expr) => {
table_bench! { $name, $table, }
};
}
table_bench!(small_table, {
#[derive(Tabled, Clone)]
struct Entry {
field1: String,
field2: usize,
field3: i32,
}
Entry {
field1: "This is a text 0".to_string(),
field2: 0,
field3: 1,
}
});
table_bench!(
small_table_stylish,
[0; 3],
Style::modern(),
Modify::new(Segment::all())
.with(Alignment::left())
.with(Alignment::top())
.with(Padding::new(1, 1, 0, 2))
);
table_bench!(big_table, { [0; 16] });
criterion_group!(benches, small_table, big_table, small_table_stylish);
criterion_main!(benches);
|
use super::atom::text::Text;
use super::molecule::tab_menu::{self, TabMenu};
use crate::arena::{block, ArenaMut, BlockMut};
use crate::libs::random_id::U128Id;
use isaribi::{
style,
styled::{Style, Styled},
};
use kagura::prelude::*;
use nusa::prelude::*;
mod boxblock_list;
use boxblock_list::BoxblockList;
pub struct Props {
pub arena: ArenaMut,
pub world: BlockMut<block::World>,
pub selecting: U128Id,
}
pub enum Msg {}
pub enum On {}
pub struct ComponentList {
arena: ArenaMut,
world: BlockMut<block::World>,
selecting: U128Id,
}
impl Component for ComponentList {
type Props = Props;
type Msg = Msg;
type Event = On;
}
impl HtmlComponent for ComponentList {}
impl Constructor for ComponentList {
fn constructor(props: Self::Props) -> Self {
Self {
arena: props.arena,
world: props.world,
selecting: props.selecting,
}
}
}
impl Update for ComponentList {
fn on_load(mut self: Pin<&mut Self>, props: Props) -> Cmd<Self> {
self.arena = props.arena;
self.world = props.world;
self.selecting = props.selecting;
Cmd::none()
}
}
impl Render<Html> for ComponentList {
type Children = ();
fn render(&self, _children: Self::Children) -> Html {
Self::styled(TabMenu::new(
self,
None,
tab_menu::Props {
selected: 0,
controlled: false,
},
Sub::none(),
(
Attributes::new(),
Events::new(),
vec![(
Text::condense_75("ブロック"),
Html::div(
Attributes::new()
.class(Self::class("padding"))
.class(Self::class("scroll"))
.class(Self::class("list")),
Events::new(),
vec![BoxblockList::empty(
self,
None,
boxblock_list::Props {
arena: ArenaMut::clone(&self.arena),
world: BlockMut::clone(&self.world),
selecting: U128Id::clone(&self.selecting),
},
Sub::none(),
)],
),
)],
),
))
}
}
impl Styled for ComponentList {
fn style() -> Style {
style! {
".padding" {
"padding": ".35rem";
}
".scroll" {
"overflow-y": "scroll";
"height": "100%";
}
".list" {
"display": "grid";
"grid-auto-flow": "row";
"row-gap": ".35rem";
}
}
}
}
|
// TODO: this may no longer needed since regex 1.9.
use std::mem;
use anyhow::Result;
use regex::Regex;
pub(crate) struct RegexVecBuilder {
filled: Vec<String>,
current: String,
first: bool,
num_pats: usize,
leading: &'static str,
trailing: &'static str,
}
impl RegexVecBuilder {
const LIMIT: usize = 4096;
pub(crate) fn new(leading: &'static str, trailing: &'static str) -> Self {
let mut current = String::with_capacity(256);
current.push_str(leading);
Self { filled: Vec::with_capacity(1), current, first: true, num_pats: 0, leading, trailing }
}
pub(crate) fn or(&mut self, pat: &str) {
let len = pat.len() / usize::BITS as usize + 1;
self.num_pats += len;
if self.num_pats > Self::LIMIT && self.num_pats != len {
self.current.push_str(self.trailing);
self.filled.push(mem::replace(&mut self.current, String::with_capacity(256)));
self.current.push_str(self.leading);
self.first = true;
self.num_pats = len;
}
if self.first {
debug_assert_eq!(self.current, self.leading);
self.first = false;
} else {
self.current.push('|');
}
self.current.push_str(pat);
}
pub(crate) fn build(mut self) -> Result<RegexVec> {
debug_assert_ne!(self.current.len(), 0);
if self.current != self.leading {
self.current.push_str(self.trailing);
self.filled.push(mem::take(&mut self.current));
}
let mut v = Vec::with_capacity(self.filled.len());
for re in &self.filled {
v.push(Regex::new(re)?);
}
Ok(RegexVec(v))
}
}
pub(crate) struct RegexVec(Vec<Regex>);
impl RegexVec {
pub(crate) fn is_match(&self, text: &str) -> bool {
for re in &self.0 {
if re.is_match(text) {
return true;
}
}
false
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[cfg_attr(miri, ignore)] // Miri is too slow
fn smoke() {
let mut re = RegexVecBuilder::new("^(", ")$");
re.or(&"a".repeat(64 * 4100));
assert!(re.filled.is_empty());
let re = re.build().unwrap();
assert_eq!(re.0.len(), 1);
let mut re = RegexVecBuilder::new("^(", ")$");
while re.filled.is_empty() {
re.or("a");
}
re.or("b");
re.or("c");
assert_eq!(re.filled.len(), 1);
let re = re.build().unwrap();
assert_eq!(re.0.len(), 2);
assert!(re.is_match("a"));
assert!(!re.is_match("aa"));
assert!(re.is_match("b"));
assert!(!re.is_match("bb"));
assert!(re.is_match("c"));
assert!(!re.is_match("cc"));
assert!(!re.is_match("d"));
}
fn gen_pkg_names(num_pkg: usize, pkg_name_size: usize) -> Vec<String> {
(0..num_pkg)
.map(|n| ('a'..='z').cycle().skip(n).take(pkg_name_size).collect())
.collect::<Vec<_>>()
}
#[test]
#[cfg_attr(miri, ignore)] // Miri is too slow
fn regex_pkg_hash_re_size_limit() {
fn pkg_hash_re(pkg_names: &[String]) -> Result<Regex, regex::Error> {
let mut re = String::from("^(lib)?(");
let mut first = true;
for name in pkg_names {
if first {
first = false;
} else {
re.push('|');
}
re.push_str(&name.replace('-', "(-|_)"));
}
re.push_str(")(-[0-9a-f]{7,})?$");
Regex::new(&re)
}
let names = gen_pkg_names(12000, 64);
pkg_hash_re(&names).unwrap();
let names = gen_pkg_names(6000, 128);
pkg_hash_re(&names).unwrap();
let names = gen_pkg_names(3000, 256);
pkg_hash_re(&names).unwrap();
}
fn pkg_hash_re_builder(pkg_names: &[String]) -> RegexVecBuilder {
let mut re = RegexVecBuilder::new("^(lib)?(", ")(-[0-9a-f]{7,})?$");
for name in pkg_names {
re.or(&name.replace('-', "(-|_)"));
}
re
}
#[test]
#[cfg_attr(miri, ignore)] // Miri is too slow
fn regex_vec_pkg_hash_re_size_limit() {
let names = gen_pkg_names(12000, 64);
pkg_hash_re_builder(&names).build().unwrap();
let names = gen_pkg_names(6000, 128);
pkg_hash_re_builder(&names).build().unwrap();
let names = gen_pkg_names(3000, 256);
pkg_hash_re_builder(&names).build().unwrap();
}
}
|
use super::semihosting::{semihosting_halt, SemihostingExitStatus};
pub fn idle() {
unsafe {
asm!("sti; hlt");
}
}
#[cfg_attr(test, allow(unused))]
pub fn halt() -> ! {
semihosting_halt(SemihostingExitStatus::Success);
loop {
unsafe {
asm!("cli; hlt");
}
}
}
|
use std::io;
use shaderc::{Compiler, ShaderKind};
use shaderc::CompilationArtifact;
use wgpu::{Device, ShaderModule};
#[derive(Debug, Error)]
pub enum ShaderCompilationError {
#[error(display = "could not create shader compiler")]
NullCompiler,
#[error(display = "could not create shader compile options")]
NullOptions,
#[error(display = "shader compilation error")]
CompileFailed(#[error(cause)] shaderc::Error),
#[error(display = "could not read shader source file")]
FileError(#[error(cause)] std::io::Error),
}
impl From<shaderc::Error> for ShaderCompilationError {
fn from(err: shaderc::Error) -> Self {
ShaderCompilationError::CompileFailed(err)
}
}
impl From<io::Error> for ShaderCompilationError {
fn from(err: io::Error) -> Self {
ShaderCompilationError::FileError(err)
}
}
fn glsl_to_spirv(source: &str, shader_kind: ShaderKind) -> Result<CompilationArtifact, ShaderCompilationError> {
use self::ShaderCompilationError::*;
let mut compiler = Compiler::new().ok_or_else(|| NullCompiler)?;
let mut options = shaderc::CompileOptions::new().ok_or_else(|| NullOptions)?;
options.add_macro_definition("EP", Some("main"));
let artifact = compiler.compile_into_spirv(source, shader_kind, "shader.glsl", "main", Some(&options))?;
Ok(artifact)
}
pub fn load_shader(path: &str, shader_kind: ShaderKind) -> Result<Vec<u8>, ShaderCompilationError> {
let shader_source = ::std::fs::read_to_string(path)?;
let artifact = glsl_to_spirv(&shader_source, shader_kind)?;
Ok(artifact.as_binary_u8().to_vec())
}
|
/// Possible types of error.
#[derive(Debug)]
pub enum ErrorKind {
/// Invalid parameter.
InvalidValue,
/// IO error
Io(std::io::Error),
}
/// Error type for the crate.
#[derive(Debug)]
pub struct Error {
kind: ErrorKind,
description: String,
}
impl Error {
pub fn new(kind: ErrorKind, description: &str) -> Error {
Error {
kind,
description: String::from(description),
}
}
}
impl std::error::Error for Error {
fn description(&self) -> &str {
&self.description
}
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
None
}
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", &self.description)
}
}
impl From<std::io::Error> for Error {
fn from(e: std::io::Error) -> Self {
Error::new(ErrorKind::Io(e), "IO error")
}
}
/// Result type used in the crate.
pub type Result<T> = std::result::Result<T, Error>;
|
#[doc = "Register `WRP1R_CUR` reader"]
pub type R = crate::R<WRP1R_CUR_SPEC>;
#[doc = "Field `WRPSG1` reader - Bank 1 sector group protection option status byte Each FLASH_WRP1R_CUR bit reflects the write protection status of the corresponding group of four consecutive sectors in bank 1 (0: the group is write protected; 1: the group is not write protected) Bit 0: Group embedding sectors 0 to 3 Bit 1: Group embedding sectors 4 to 7 Bit N: Group embedding sectors 4 x N to 4 x N + 3 Bit 31: Group embedding sectors 124 to 127"]
pub type WRPSG1_R = crate::FieldReader<u32>;
impl R {
#[doc = "Bits 0:31 - Bank 1 sector group protection option status byte Each FLASH_WRP1R_CUR bit reflects the write protection status of the corresponding group of four consecutive sectors in bank 1 (0: the group is write protected; 1: the group is not write protected) Bit 0: Group embedding sectors 0 to 3 Bit 1: Group embedding sectors 4 to 7 Bit N: Group embedding sectors 4 x N to 4 x N + 3 Bit 31: Group embedding sectors 124 to 127"]
#[inline(always)]
pub fn wrpsg1(&self) -> WRPSG1_R {
WRPSG1_R::new(self.bits)
}
}
#[doc = "FLASH write sector group protection for Bank 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`wrp1r_cur::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct WRP1R_CUR_SPEC;
impl crate::RegisterSpec for WRP1R_CUR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`wrp1r_cur::R`](R) reader structure"]
impl crate::Readable for WRP1R_CUR_SPEC {}
#[doc = "`reset()` method sets WRP1R_CUR to value 0"]
impl crate::Resettable for WRP1R_CUR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
#![doc(html_root_url = "https://docs.rs/shorthand/0.1.1")]
#![forbid(unsafe_code)]
#![doc(test(attr(deny(unused_mut))))]
//! # shorthand
//! [`shorthand`](https://dictionary.cambridge.org/de/worterbuch/englisch/shorthand) is defined as
//! `a system of fast writing`
//! and that is exactly what this library is for; to remove the annoying
//! boilerplate code, that comes with writing your own library.
//!
//! # What does this library do?
//!
//! It makes coding in rust a lot more convenient, by deriving `getters` and
//! `setters` for the fields of a struct.
//!
//! ```
//! use shorthand::ShortHand;
//!
//! #[derive(ShortHand, Default)]
//! pub struct Example {
//! number: usize,
//! data: String,
//! }
//!
//! let mut example = Example::default();
//!
//! assert_eq!(example.number(), 0);
//! example.set_number(1);
//! assert_eq!(example.number(), 1);
//!
//! assert_eq!(example.data(), &"".to_string());
//! example.set_data("hi".to_string());
//! assert_eq!(example.data(), &"hi".to_string());
//! ```
//!
//! Otherwise, you would have to write the this by hand
//!
//! ```
//! # pub struct Example {
//! # number: usize,
//! # data: String,
//! # }
//! #[allow(dead_code)]
//! impl Example {
//! #[inline(always)]
//! pub fn number(&self) -> usize { self.number }
//!
//! #[inline(always)]
//! pub fn set_number(&mut self, value: usize) -> &mut Self {
//! self.number = value;
//! self
//! }
//!
//! #[inline(always)]
//! pub fn data(&self) -> &String { &self.data }
//!
//! #[inline(always)]
//! pub fn set_data(&mut self, value: String) -> &mut Self {
//! self.data = value;
//! self
//! }
//! }
//! ```
//!
//! # How do I get started?
//!
//! Simply add this library under `[dependencies]` to your `Cargo.toml`
//! ```toml
//! [dependencies]
//! shorthand = "0.1.0"
//! ```
//!
//! You can then derive `ShortHand` for any struct
//!
//! ```
//! use shorthand::ShortHand;
//!
//! #[derive(ShortHand)]
//! struct Example {
//! field: usize,
//! }
//! ```
//!
//! # Customization
//!
//! The derive macro can be heavily customized with the `#[shorthand]`
//! attribute. It has the following main attributes:
//! * [`enable`](#enable)
//! * [`disable`](#disable)
//! * [`visibility`](#visibility)
//! * [`rename`](#rename)
//! * [`verify`](#verify)
//!
//! ## `enable`
//!
//! This attribute allows you to enable certain attributes. For example by
//! default the attribute [`into`](#into) is disabled.
//!
//! ```
//! use shorthand::ShortHand;
//!
//! #[derive(ShortHand, Default)]
//! struct Example {
//! #[shorthand(enable(into))]
//! field: String,
//! other: String,
//! }
//!
//! let mut example = Example::default();
//!
//! example.set_field("field"); // accepts any type, that implements Into<String> or From<String>
//! example.set_other("other".to_string());
//!
//! assert_eq!(example.field(), &"field".to_string());
//! assert_eq!(example.other(), &"other".to_string());
//! ```
//!
//! You can find a list with all attributes, that can be enabled
//! [here](#attributes).
//!
//! ## `disable`
//!
//! This attribute allows you to disable certain attributes. For example by
//! default the attribute [`primitive_copy`](#primitive_copy) is enabled
//!
//! ```
//! use shorthand::ShortHand;
//!
//! #[derive(ShortHand, Default)]
//! struct Example {
//! #[shorthand(disable(primitive_copy))]
//! field: usize,
//! other: usize,
//! }
//!
//! let example = Example::default();
//!
//! assert_eq!(example.field(), &0); // returns a reference, instead of copying the value
//! assert_eq!(example.other(), 0);
//! ```
//!
//! You can find a list with all attributes, that can be disabled
//! [here](#attributes).
//!
//! ## `visibility`
//!
//! This attribute allows you to change the visibility of the derived function.
//! Anything from
//! [here](https://doc.rust-lang.org/reference/visibility-and-privacy.html#visibility-and-privacy)
//! is valid. You can also set the visibility to `inherit`, all derived
//! functions will then have the visibility of the struct.
//!
//! You can either apply this as a local or as a global attribute. The default
//! visibility is `pub`.
//!
//! ```
//! use shorthand::ShortHand;
//!
//! #[derive(ShortHand, Default)]
//! #[shorthand(visibility("pub(crate)"))]
//! struct Example {
//! field: usize,
//! #[shorthand(visibility("pub"))]
//! data: String,
//! #[shorthand(visibility(inherit))]
//! xt: String,
//! }
//! ```
//!
//! ## `rename`
//!
//! This attribute allows you to rename the derived function, with a pattern.
//! You can either apply this as a local or as a global attribute.
//!
//! ```
//! use shorthand::ShortHand;
//!
//! #[derive(ShortHand, Default)]
//! #[shorthand(rename("prefix_{}_suffix"))]
//! struct Example {
//! field: usize,
//! #[shorthand(rename(format = "example_{}"))]
//! data: String,
//! }
//!
//! let mut example = Example::default();
//! example.set_prefix_field_suffix(1);
//! example.set_example_data("Hello".to_string());
//!
//! assert_eq!(example.prefix_field_suffix(), 1);
//! assert_eq!(example.example_data(), &"Hello".to_string());
//! ```
//!
//! This attribute also supports changing the getter and setter individually:
//!
//! ```
//! use shorthand::ShortHand;
//!
//! #[derive(ShortHand, Default)]
//! #[shorthand(rename(format = "prefix_{}_suffix"))]
//! struct Example {
//! #[shorthand(rename(get = "get_{}", set = "set_{}_a"))]
//! field: usize,
//! #[shorthand(rename(get = "get_{}"))] // this will not change the setter
//! data: String,
//! }
//!
//! let mut example = Example::default();
//! example.set_field_a(1);
//! example.set_data("Hello".to_string());
//!
//! assert_eq!(example.get_field(), 1);
//! assert_eq!(example.get_data(), &"Hello".to_string());
//! ```
//!
//! In the case, that you have a rename attribute on the entire struct, but you
//! do not want to apply it for one specific field, you can disable it.
//!
//! ```
//! use shorthand::ShortHand;
//!
//! #[derive(ShortHand, Default)]
//! #[shorthand(rename("prefix_{}_suffix"))]
//! struct Example {
//! #[shorthand(disable(rename))]
//! field: usize,
//! data: String,
//! }
//!
//! let mut example = Example::default();
//! example.set_field(1);
//! example.set_prefix_data_suffix("Hello".to_string());
//!
//! assert_eq!(example.field(), 1);
//! assert_eq!(example.prefix_data_suffix(), &"Hello".to_string());
//! ```
//!
//! It is also possible to rename single fields
//!
//! ```
//! use shorthand::ShortHand;
//!
//! #[derive(ShortHand, Default)]
//! struct Example {
//! #[shorthand(rename("is_default"))]
//! default: bool,
//! }
//!
//! assert_eq!(Example::default().is_default(), false);
//! ```
//!
//! ## `verify`
//!
//! This attribute allows you to verify wether or not a value passed to a setter
//! is valid.
//!
//! ```should_panic
//! use shorthand::ShortHand;
//!
//! #[derive(ShortHand)]
//! #[shorthand(verify(fn = "Self::verify_field"))]
//! struct Example {
//! field: bool,
//! }
//!
//! impl Example {
//! fn verify_field(&self) {
//! if self.field {
//! panic!("field must be `false`");
//! }
//! }
//! }
//!
//! let mut example = Example { field: false };
//!
//! example.set_field(true);
//! ```
//!
//! ## List of Attributes
//! - [`option_as_ref`](derive.ShortHand.html#option_as_ref)
//! - [`const_fn`](derive.ShortHand.html#const_fn)
//! - [`primitive_copy`](derive.ShortHand.html#primitive_copy)
//! - [`inline`](derive.ShortHand.html#inline)
//! - [`must_use`](derive.ShortHand.html#must_use)
//! - [`copy`](derive.ShortHand.html#copy)
//! - [`get`](derive.ShortHand.html#get)
//! - [`set`](derive.ShortHand.html#set)
//! - [`into`](derive.ShortHand.html#into)
//! - [`try_into`](derive.ShortHand.html#try_into)
//! - [`get_mut`](derive.ShortHand.html#get_mut)
//! - [`ignore_phantomdata`](derive.ShortHand.html#ignore_phantomdata)
//! - [`skip`](derive.ShortHand.html#skip)
//! - [`rename`](derive.ShortHand.html#rename)
//! - [`forward`](derive.ShortHand.html#forward)
//! - [`ignore_underscore`](derive.ShortHand.html#ignore_underscore)
//! - [`collection_magic`](derive.ShortHand.html#collection_magic)
//! - [`strip_option`](derive.ShortHand.html#strip_option)
//! - [`clone`](derive.ShortHand.html#clone)
//!
//! ### Enabled by default
//!
//! The following attributes are [`enable`]d by default
//! - [`option_as_ref`](#option_as_ref)
//! - [`primitive_copy`](#primitive_copy)
//! - [`inline`](#inline)
//! - [`get`](#get)
//! - [`set`](#set)
//! - [`ignore_phantomdata`](#ignore_phantomdata)
//! - [`forward_attributes`](#forward_attributes)
//!
//! [`enable`]: #enable
//!
//! # Feature Requests and Bug Reports
//!
//! Feel free to ask questions or report bugs [here](https://www.github.com/luro02/shorthand).
//! There are no stupid questions.
//!
//! This library should be as convenient as possible, so please do not hesitate
//! to request a feature.
//!
//! # Reference
//!
//! This library has been inspired by the following crates
//! - [`getset`] (just the issue tracker and which features were requested)
//! - [`thiserror`]
//! - [`derive-builder`]
//! - [`proc-macro-workshop`]
//!
//! [`getset`]: https://github.com/Hoverbear/getset
//! [`thiserror`]: https://github.com/dtolnay/thiserror
//! [`derive-builder`]: https://github.com/colin-kiegel/rust-derive-builder
//! [`proc-macro-workshop`]: https://github.com/dtolnay/proc-macro-workshop
//! [`proc_macro`]: https://doc.rust-lang.org/reference/procedural-macros.html
#![deny(clippy::use_self, unconditional_recursion)]
#![warn(clippy::pedantic, clippy::nursery, clippy::cargo)]
#![warn(
missing_copy_implementations,
missing_debug_implementations,
//missing_docs
)]
#![allow(clippy::default_trait_access)]
extern crate proc_macro;
mod attributes;
mod error;
mod expand;
mod forward;
mod options;
mod parser;
mod rename;
mod utils;
mod verify;
mod visibility;
pub(crate) use error::Error;
pub(crate) type Result<T> = std::result::Result<T, Error>;
use proc_macro::TokenStream;
use syn::{parse_macro_input, DeriveInput};
/// A [`proc_macro`] to derive getter, mutgetter and setter for fields.
///
/// A list of all attributes can be found [here](index.html#attributes).
///
/// # Attributes
/// ## `option_as_ref`
/// This attribute makes the getter return `Option<&T>` instead of `&Option<T>`.
/// This feature is enabled by default and recommended, because most of the
/// functions for [`Option`] consume the type.
///
/// You can find a discussion, about wether or not you should use it
/// [here](https://users.rust-lang.org/t/api-design-option-t-vs-option-t/34139).
///
/// ## `const_fn`
/// There is a new feature coming to rust called constant functions.
/// Functions, that are marked with `const` can be executed by the compiler at
/// compile time, if the value is known.
///
/// ```
/// const fn add(value: usize, other: usize) -> usize { value + other }
///
/// let three = add(1, 2);
/// # assert_eq!(three, 3);
/// ```
///
/// will be optimized to
///
/// ```
/// let three = 3;
/// ```
///
/// Another benefit is, that you can also save the result in a `const` variable.
///
/// ```
/// const fn add(value: usize, other: usize) -> usize { value + other }
///
/// const THREE: usize = add(1, 2);
/// ```
///
/// This feature is currently work in progress see
/// [rust-lang/rust#57563](https://github.com/rust-lang/rust/issues/57563)
///
/// You can read more about it
/// [here](https://doc.rust-lang.org/unstable-book/language-features/const-fn.html)
/// or in the [RFC](https://github.com/rust-lang/rfcs/blob/master/text/0911-const-fn.md).
///
/// By enabling this feature the derived functions will be `const`.
///
/// Please note, that not everything is currently supported and therefore some
/// attributes will ignore this attribute and not add `const` to the function.
///
/// ## `primitive_copy`
///
/// This attribute will cause get functions to return a copy of the type,
/// instead of a reference.
///
/// ```
/// use shorthand::ShortHand;
///
/// #[derive(ShortHand, Default)]
/// #[shorthand(disable(primitive_copy))]
/// struct Example {
/// field: usize,
/// #[shorthand(enable(primitive_copy))]
/// other: usize,
/// }
///
/// let example = Example::default();
///
/// assert_eq!(example.field(), &0);
/// assert_eq!(example.other(), 0);
/// ```
///
/// This attribute is enabled by default.
///
/// Please note, that this does only work with primitive types from the standard
/// library, other types have to be marked with [`copy`](#copy).
///
/// ## `copy`
///
/// There is no way for a [`proc_macro`] to know wether or not a type implements
/// [`Copy`], so fields, where the getter should return a copy, instead of a
/// reference have to be marked with `#[shorthand(copy)]`.
///
/// ```
/// use shorthand::ShortHand;
///
/// #[derive(Default, Copy, Clone, PartialEq, Debug)]
/// struct Number(pub usize);
///
/// #[derive(ShortHand, Default)]
/// struct Example {
/// #[shorthand(enable(copy))]
/// field: Number,
/// other: Number,
/// }
///
/// let example = Example::default();
///
/// assert_eq!(example.field(), Number(0));
/// assert_eq!(example.other(), &Number(0));
/// ```
///
/// ## `inline`
///
/// This attribute adds `#[inline(always)]` to the derived function.
///
/// ```
/// #[inline(always)]
/// fn add(a: usize, b: usize) -> usize { a + b }
///
/// let three = add(1, 2);
/// ```
///
/// will be optimized to
///
/// ```
/// let three = 1 + 2;
/// ```
///
/// You can read more about the inline attribute
/// [here](https://doc.rust-lang.org/reference/attributes/codegen.html#the-inline-attribute).
///
/// A discussion, about wether or not you should use it:
/// <https://internals.rust-lang.org/t/when-should-i-use-inline/598>
///
/// This attribute is enabled by default.
///
/// ## `must_use`
///
/// This attribute will mark functions with `#[must_use]`,
/// which means, that their results have to be used, otherwise you get a warning
///
/// ```
/// #[must_use]
/// fn hello() -> &'static str { "hello" }
///
/// hello();
/// ```
///
/// ```text
/// warning: unused return value of `hello` that must be used
/// --> src/main.rs:6:5
/// |
/// 6 | hello();
/// | ^^^^^^^^
/// |
/// = note: `#[warn(unused_must_use)]` on by default
/// ```
///
/// This is disabled by default and can only be enabled for getter and mutable
/// getter. If you really need this attributes on a setter you can just mark the
/// field with `#[must_use]` and shorthand will automatically forward the
/// attribute (see [here](#forward_attributes)).
///
/// ## `get`
///
/// This attribute derives a function, to get the value of a field
/// (sometimes referred to as `getter`).
///
/// ```
/// use shorthand::ShortHand;
///
/// #[derive(ShortHand, Default)]
/// #[shorthand(disable(get))]
/// struct Example {
/// #[shorthand(enable(get))]
/// field: usize,
/// }
///
/// let example = Example::default();
///
/// assert_eq!(example.field(), 0);
/// ```
///
/// This attribute is enabled by default.
///
/// ## `set`
///
/// This attribute derives a function, to set the value of a field
/// (sometimes referred to as `setter`).
///
/// ```
/// use shorthand::ShortHand;
///
/// #[derive(ShortHand, Default)]
/// #[shorthand(disable(get, set))]
/// struct Example {
/// #[shorthand(enable(get, set))]
/// field: usize,
/// }
///
/// let mut example = Example::default();
///
/// example.set_field(1);
///
/// assert_eq!(example.field(), 1);
/// ```
///
/// This attribute is enabled by default.
///
/// ## `ignore_phantomdata`
///
/// Like the name implies, this will tell the [`proc_macro`], to ignore
/// [`PhantomData`] and to not generate functions for it.
///
/// ```compile_fail
/// use core::marker::PhantomData;
/// use shorthand::ShortHand;
///
/// #[derive(ShortHand, Default)]
/// struct Example {
/// field: PhantomData<usize>,
/// }
///
/// let example = Example::default();
/// example.field(); // this will cause a compiler error, because the function does not exist!
/// ```
///
/// This feature is enabled by default.
///
/// [`PhantomData`]: core::marker::PhantomData
///
/// ## `skip`
///
/// Like the name implies, this will tell the [`proc_macro`] to not generate
/// functions for this field (skipping it).
///
/// ```compile_fail
/// use shorthand::ShortHand;
///
/// #[derive(ShortHand, Default)]
/// struct Example {
/// #[shorthand(enable(skip))]
/// field: usize,
/// }
///
/// let example = Example::default();
/// example.field(); // this will cause a compiler error, because the function does not exist!
/// ```
///
/// ## `into`
///
/// The `into` attribute adds `VALUE: Into<field_type>` as a trait bound for
/// setters ([`Into`]).
///
/// ```
/// use shorthand::ShortHand;
///
/// #[derive(ShortHand, Default)]
/// struct Example {
/// #[shorthand(enable(into))]
/// field: String,
/// other: String,
/// }
///
/// let mut example = Example::default();
///
/// example.set_field("field"); // accepts any type, that implements Into<String> or From<String>
/// example.set_other("other".to_string());
///
/// assert_eq!(example.field(), &"field".to_string());
/// assert_eq!(example.other(), &"other".to_string());
/// ```
///
/// This struct uses `VALUE` as a generic, so you should *NOT* use that on your
/// struct
///
/// ```
/// struct DoNotDoThis<VALUE> {
/// value: VALUE,
/// }
/// ```
///
/// This attribute is not enabled by default.
///
/// ## `forward`
///
/// The `forward` attribute, allows you to control how attributes are
/// forwarded. By default the [`proc_macro`] will forward
/// the following attributes of the field to the generated function:
///
/// - [`doc`](https://doc.rust-lang.org/rustdoc/the-doc-attribute.html)
/// - [`cfg`](https://doc.rust-lang.org/reference/conditional-compilation.html#the-cfg-attribute)
/// - [`cfg_attr`](
/// https://doc.rust-lang.org/reference/conditional-compilation.html#the-cfg_attr-attribute)
/// - [`allow`], [`warn`], [`deny`], [`forbid`]
/// - [`deprecated`]
/// - [`must_use`]
/// - [`inline`]
/// - [`cold`]
/// - [`target_feature`]
///
/// [`allow`]:https://doc.rust-lang.org/reference/attributes/diagnostics.html#lint-check-attributes
/// [`warn`]:https://doc.rust-lang.org/reference/attributes/diagnostics.html#lint-check-attributes
/// [`deny`]:https://doc.rust-lang.org/reference/attributes/diagnostics.html#lint-check-attributes
/// [`forbid`]:https://doc.rust-lang.org/reference/attributes/diagnostics.html#lint-check-attributes
/// [`deprecated`]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-deprecated-attribute
/// [`must_use`]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
/// [`inline`]: https://doc.rust-lang.org/reference/attributes/codegen.html#the-inline-attribute
/// [`cold`]: https://doc.rust-lang.org/reference/attributes/codegen.html#the-cold-attribute
/// [`target_feature`]: https://doc.rust-lang.org/reference/attributes/codegen.html#the-target_feature-attribute
///
/// ```
/// use shorthand::ShortHand;
///
/// #[derive(ShortHand)]
/// #[shorthand(disable(forward))]
/// struct Example {
/// #[shorthand(enable(forward(must_use)))]
/// #[must_use]
/// hello: &'static str,
/// }
/// ```
///
/// The `hello` function would now have a `#[must_use]` attribute:
///
/// ```
/// #[must_use]
/// fn hello() -> &'static str { "hello" }
/// ```
///
/// This attribute can be applied multiple times on the same field, which would
/// allow controlled forwarding. Please note, that this feature does not work,
/// until this issue is fixed <https://github.com/rust-lang/rust/issues/67839>.
///
/// ```
/// use shorthand::ShortHand;
///
/// #[derive(ShortHand)]
/// struct Example {
/// #[shorthand(enable(forward))]
/// #[must_use]
/// #[shorthand(disable(forward))]
/// #[allow(dead_code)]
/// hello: &'static str,
/// }
/// ```
///
/// In this example only `#[must_use]` is forwarded and `#[allow(dead_code)]` is
/// not.
///
/// This attribute can also be used to forward parts of docs.
/// A doc comment `///` will be converted to
/// [`#[doc]`](https://doc.rust-lang.org/rustdoc/the-doc-attribute.html)
/// attribute.
///
/// ```
/// use shorthand::ShortHand;
///
/// #[derive(ShortHand, Default)]
/// struct Example {
/// /// Data has some special restrictions.
/// /// - The String can only exist of uppercase characters
/// /// - Numbers are allowed
/// /// - The String has a maximum size of 5.
/// #[shorthand(disable(forward))]
/// /// This part will not be forwarded.
/// #[shorthand(enable(forward))]
/// ///
/// /// # Example
/// ///
/// /// ```
/// /// println!("nice");
/// /// ```
/// data: String,
/// }
/// ```
///
/// will instruct shorthand to generate the following code
///
/// ```
/// # struct Example {
/// # data: String,
/// # }
/// #
/// impl Example {
/// /// Data has some special restrictions.
/// /// - The String can only exist of uppercase characters
/// /// - Numbers are allowed
/// /// - The String has a maximum size of 5.
/// ///
/// /// # Example
/// ///
/// /// ```
/// /// println!("nice");
/// /// ```
/// #[inline(always)]
/// pub fn data(&self) -> &String { &self.data }
///
/// /// Data has some special restrictions.
/// /// - The String can only exist of uppercase characters
/// /// - Numbers are allowed
/// /// - The String has a maximum size of 5.
/// ///
/// /// # Example
/// ///
/// /// ```
/// /// println!("nice");
/// /// ```
/// #[inline(always)]
/// pub fn set_data(&mut self, value: String) -> &mut Self {
/// self.data = value;
/// self
/// }
/// }
/// ```
///
/// as you can see the line `/// This part will not be forwarded.` did not get
/// forwarded.
///
/// ## `ignore_underscore`
///
/// This attribute instructs the [`proc_macro`] to ignore fields prefixed
/// with an `_`.
///
/// This attribute is not enabled by default.
///
/// ## `collection_magic`
///
/// This attribute instructs the [`proc_macro`] to derive additonal functions
/// for fields, that have a collection.
///
/// The following collections are supported:
/// - [`Vec`](std::vec::Vec)
/// - [`BTreeMap`](std::collections::BTreeMap)
/// - [`BTreeSet`](std::collections::BTreeSet)
/// - [`HashMap`](std::collections::HashMap)
/// - [`HashSet`](std::collections::HashSet)
///
/// It will derive a `push_field` function for [`Vec`]
/// and for all the other collection types an `insert_field` function.
///
/// ```
/// use shorthand::ShortHand;
/// use std::collections::BTreeMap;
///
/// #[derive(ShortHand, Default)]
/// struct Example {
/// #[shorthand(enable(collection_magic))]
/// value: Vec<usize>,
/// #[shorthand(enable(collection_magic))]
/// other: BTreeMap<usize, usize>,
/// }
///
/// let mut example = Example::default();
///
/// example.push_value(1);
/// example.push_value(2);
/// example.push_value(3);
///
/// assert_eq!(example.value(), &vec![1, 2, 3]);
///
/// example.insert_other(1, 1);
/// example.insert_other(2, 2);
/// example.insert_other(3, 3);
///
/// assert_eq!(example.other(), &{
/// let mut result = BTreeMap::new();
/// result.insert(1, 1);
/// result.insert(2, 2);
/// result.insert(3, 3);
/// result
/// });
/// ```
///
/// ## `strip_option`
///
/// This will change the input type for setter of optional fields from
/// `Option<T>` to `T`.
///
/// ```
/// use shorthand::ShortHand;
///
/// #[derive(ShortHand, Default)]
/// struct Example {
/// value: Option<usize>,
/// #[shorthand(enable(strip_option))]
/// other: Option<usize>,
/// }
///
/// Example::default().set_value(Some(0));
/// Example::default().set_other(0);
/// ```
///
/// This attribute is diabled by default.
///
/// ## `clone`
///
/// The getter will [`clone`](Clone::clone) the field instead of returning a
/// reference.
///
/// ```
/// use shorthand::ShortHand;
/// use std::rc::Rc;
///
/// #[derive(ShortHand, Default)]
/// struct Example {
/// #[shorthand(enable(clone))]
/// value: Rc<usize>,
/// }
///
/// assert_eq!(Example::default().value(), Rc::new(0));
/// ```
///
/// This attribute is diabled by default.
#[proc_macro_derive(ShortHand, attributes(shorthand))]
pub fn shorthand(input: TokenStream) -> TokenStream {
// Parse the input tokens into a syntax tree
let input = parse_macro_input!(input as DeriveInput);
expand::derive(&input)
.unwrap_or_else(error::Error::into_token_stream)
.into()
}
|
extern crate regex;
extern crate daemonize;
extern crate notify_rust;
use std::env;
use std::process;
use std::thread;
use std::time;
use regex::Regex;
use daemonize::Daemonize;
use notify_rust::Notification;
use notify_rust::Hint;
fn main() {
let (delay, message) = parse_args();
if delay == "" && message == "" {
print_usage();
process::exit(1);
}
let delay_seconds = match parse_delay(&delay) {
Ok(seconds) => seconds,
Err(error) => {
println!("Error: {}", error);
process::exit(1);
}
};
match Daemonize::new().start() {
Ok(_) => {
thread::sleep(time::Duration::new(delay_seconds, 0));
notify(message);
},
Err(error) => println!("Error: {}", error)
}
}
fn print_usage() {
println!("Usage: {} <DELAY> [MESSAGE]", env::args().nth(0).unwrap());
}
fn notify(message: String) {
Notification::new()
.summary("Reminder")
.body(message.as_str())
.timeout(10000)
.hint(Hint::Resident(true))
.show()
.unwrap();
}
fn parse_args() -> (String, String) {
let mut delay: String = String::new();
let mut message: String = String::new();
for (index, arg) in env::args().enumerate() {
if index == 1 {
delay = arg;
} else if index > 1 {
message = message + " " + &arg;
message = message.trim().to_string();
}
}
(delay, message)
}
fn parse_delay(delay: &str) -> Result<u64, String> {
let re = Regex::new(r"^(\d+)([HhMmSs])$").unwrap();
match re.captures(delay) {
Some(captures) => {
let amount: u64 = captures.get(1).unwrap().as_str().parse().unwrap();
let unit = captures.get(2).unwrap().as_str();
Ok(calc_seconds(amount, unit))
}
None => { Err(format!("Invalid amount of time: {}", delay)) }
}
}
fn calc_seconds(amount: u64, unit: &str) -> u64 {
let multiplier = match unit.to_uppercase().as_str() {
"H" => { 60 * 60 },
"M" => { 60 },
_ => { 1 }
};
amount * multiplier
}
|
use std::collections::{btree_map, BTreeSet, BTreeMap, VecDeque};
use std::fmt::{self, Debug, Display};
use std::cell::{RefCell};
use std::cmp;
pub use Symbol::*;
// "T" = terminal, and "N" = nonterminal.
#[derive(Ord,PartialOrd,Eq,PartialEq,Clone)]
pub enum Symbol<T, N> {
Terminal(T),
Nonterminal(N),
}
impl<T: Display, N: Display> Display for Symbol<T, N> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
Terminal(ref t) => t.fmt(f),
Nonterminal(ref n) => n.fmt(f),
}
}
}
impl<T: Debug, N: Debug> Debug for Symbol<T, N> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
Terminal(ref t) => t.fmt(f),
Nonterminal(ref n) => n.fmt(f),
}
}
}
macro_rules! item {
($x: item) => ($x);
}
// Derive the {Partial,}{Eq,Ord} traits, based on the tuple implementations,
// for the given fields.
macro_rules! comparators {
($t: ident($($p: tt)+) ($($s: ident),+) ($($f: ident),+)) => {
item!(impl<$($p)+> PartialEq for $t<$($p)+> where $($s: PartialEq),+ {
fn eq(&self, other: &Self) -> bool {
($(self.$f),+) == ($(other.$f),+)
}
});
item!(impl<$($p)+> Eq for $t<$($p)+> where $($s: Eq),+ {
});
item!(impl<$($p)+> PartialOrd for $t<$($p)+> where $($s: PartialOrd),+ {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
($(self.$f),+).partial_cmp(&($(other.$f),+))
}
});
item!(impl<$($p)+> Ord for $t<$($p)+> where $($s: Ord),+ {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
($(self.$f),+).cmp(&($(other.$f),+))
}
});
};
}
#[derive(Debug,Clone)]
pub struct Rhs<T, N, A> {
pub syms: Vec<Symbol<T, N>>,
pub act: A,
}
comparators!(Rhs(T, N, A) (T, N) (syms));
#[derive(Debug)]
pub struct Item<'a, T: 'a, N: 'a, A: 'a> {
pub lhs: &'a N,
pub rhs: &'a Rhs<T, N, A>,
pub pos: usize,
}
comparators!(Item('a, T, N, A) (T, N) (lhs, rhs, pos));
impl<'a, T, N, A> Clone for Item<'a, T, N, A> {
fn clone(&self) -> Item<'a, T, N, A> {
Item { lhs: self.lhs, rhs: self.rhs, pos: self.pos }
}
}
#[derive(Debug)]
pub struct ItemSet<'a, T: 'a, N: 'a, A: 'a> {
pub items: BTreeSet<Item<'a, T, N, A>>,
}
comparators!(ItemSet('a, T, N, A) (T, N) (items));
impl<'a, T, N, A> Clone for ItemSet<'a, T, N, A> {
fn clone(&self) -> ItemSet<'a, T, N, A> {
ItemSet { items: self.items.clone() }
}
}
#[derive(Debug)]
pub struct Grammar<T, N, A> {
pub rules: BTreeMap<N, Vec<Rhs<T, N, A>>>,
// `start` must have exactly one rule of the form "`start` -> N", for some nonterminal N,
// and not be referred to elsewhere in the grammar.
pub start: N,
}
#[derive(Debug)]
pub struct LR0StateMachine<'a, T: 'a, N: 'a, A: 'a> {
pub states: Vec<(ItemSet<'a, T, N, A>, BTreeMap<&'a Symbol<T, N>, usize>)>,
pub start: &'a N,
}
#[derive(Debug)]
pub enum LRAction<'a, T: 'a, N: 'a, A: 'a> {
Reduce(&'a N, &'a Rhs<T, N, A>),
Shift(usize),
Accept,
}
#[derive(Debug)]
pub struct LR1State<'a, T: 'a, N: 'a, A: 'a> {
pub eof: Option<LRAction<'a, T, N, A>>,
pub lookahead: BTreeMap<&'a T, LRAction<'a, T, N, A>>,
pub goto: BTreeMap<&'a N, usize>,
}
#[derive(Debug)]
pub struct LR1ParseTable<'a, T: 'a, N: 'a, A: 'a> {
pub states: Vec<LR1State<'a, T, N, A>>,
}
#[derive(Debug)]
pub enum LR1Conflict<'a, T: 'a, N: 'a, A: 'a> {
ReduceReduce {
state: ItemSet<'a, T, N, A>,
token: Option<&'a T>,
r1: (&'a N, &'a Rhs<T, N, A>),
r2: (&'a N, &'a Rhs<T, N, A>),
},
ShiftReduce {
state: ItemSet<'a, T, N, A>,
token: Option<&'a T>,
rule: (&'a N, &'a Rhs<T, N, A>),
},
}
impl<T: Ord, N: Ord, A> Grammar<T, N, A> {
// Creates the LR(0) state machine for a grammar.
pub fn lr0_state_machine<'a>(&'a self) -> LR0StateMachine<'a, T, N, A> {
struct S<'a, T: 'a, N: 'a, A: 'a> {
states: Vec<(ItemSet<'a, T, N, A>, BTreeMap<&'a Symbol<T, N>, usize>)>,
item_sets: BTreeMap<ItemSet<'a, T, N, A>, usize>,
nubs: BTreeMap<ItemSet<'a, T, N, A>, usize>,
}
impl<'a, T: Ord, N: Ord, A> S<'a, T, N, A> {
fn item_set(&mut self, item_set: ItemSet<'a, T, N, A>) -> usize {
if let Some(&ix) = self.item_sets.get(&item_set) {
return ix;
}
let ix = self.states.len();
self.item_sets.insert(item_set.clone(), ix);
self.states.push((item_set, BTreeMap::new()));
ix
}
fn complete_nub(&mut self, grammar: &'a Grammar<T, N, A>, nub: ItemSet<'a, T, N, A>) -> usize {
if let Some(&ix) = self.nubs.get(&nub) {
return ix;
}
let mut completed: BTreeSet<_> = nub.items.clone();
let mut to_add: VecDeque<_> = nub.items.iter().cloned().collect();
while let Some(item) = to_add.pop_front() {
if let Some(&Nonterminal(ref n)) = item.rhs.syms.get(item.pos) {
if let Some(rules) = grammar.rules.get(n) {
for rhs in rules.iter() {
let new_item = Item {
lhs: n,
rhs: rhs,
pos: 0,
};
if !completed.contains(&new_item) {
to_add.push_back(new_item.clone());
completed.insert(new_item);
}
}
}
}
}
let ix = self.item_set(ItemSet { items: completed });
self.nubs.insert(nub, ix);
ix
}
}
fn advance<'a, 'b, T, N, A>(i: &'b Item<'a, T, N, A>) -> Option<(&'a Symbol<T, N>, Item<'a, T, N, A>)> {
i.rhs.syms.get(i.pos).map(|s| {
(s, Item {
lhs: i.lhs,
rhs: i.rhs,
pos: i.pos + 1,
})
})
}
let mut state: S<'a, T, N, A> = S {
states: vec![],
item_sets: BTreeMap::new(),
nubs: BTreeMap::new(),
};
let mut finished = 0;
state.complete_nub(self, ItemSet { items: { let mut r = BTreeSet::new(); r.insert(Item {
lhs: &self.start,
rhs: &self.rules.get(&self.start).unwrap()[0],
pos: 0,
}); r } });
while finished < state.states.len() {
let mut next_nubs = BTreeMap::new();
for item in state.states[finished].0.items.iter() {
if let Some((sym, next)) = advance(item) {
next_nubs.entry(sym).or_insert(BTreeSet::new()).insert(next);
}
}
for (sym, items) in next_nubs.into_iter() {
let ix = state.complete_nub(self, ItemSet { items: items });
state.states[finished].1.insert(sym, ix);
}
finished += 1;
}
LR0StateMachine {
states: state.states,
start: &self.start,
}
}
// returns a map containing:
// nonterminal => (first set, nullable)
pub fn first_sets(&self) -> BTreeMap<&N, (BTreeSet<&T>, bool)> {
let mut r = BTreeMap::new();
for (lhs, _) in self.rules.iter() {
r.insert(lhs, RefCell::new((BTreeSet::new(), false)));
}
loop {
let mut changed = false;
// the `zip` is okay because `self.rules` and `r` have the same order
for ((lhs, rhses), (_, cell)) in self.rules.iter().zip(r.iter()) {
let mut cell = cell.borrow_mut();
'outer: for rhs in rhses.iter() {
for sym in rhs.syms.iter() {
match *sym {
Terminal(ref t) => {
if cell.0.insert(t) {
changed = true;
}
continue 'outer;
}
Nonterminal(ref n) => if n == lhs {
// refers to `lhs`; no need to add own set elements
if !cell.1 {
continue 'outer;
}
} else {
let them = r.get(n).unwrap().borrow();
for &t in them.0.iter() {
if cell.0.insert(t) {
changed = true;
}
}
if !them.1 {
// stop if it's not nullable
continue 'outer;
}
},
}
}
if !cell.1 {
// if we got here, then we must be nullable
cell.1 = true;
changed = true;
}
}
}
if !changed {
break;
}
}
r.into_iter().map(|(k, v)| (k, v.into_inner())).collect()
}
// returns a map containing:
// nonterminal => (follow set, follow set contains EOF)
pub fn follow_sets<'a>(&'a self, first: BTreeMap<&'a N, (BTreeSet<&'a T>, bool)>) -> BTreeMap<&'a N, (BTreeSet<&'a T>, bool)> {
let mut r = BTreeMap::new();
for (lhs, _) in self.rules.iter() {
r.insert(lhs, (BTreeSet::new(), *lhs == self.start));
}
loop {
let mut changed = false;
for (lhs, rhses) in self.rules.iter() {
for rhs in rhses.iter() {
let mut follow = r.get(lhs).unwrap().clone();
for sym in rhs.syms.iter().rev() {
match *sym {
Terminal(ref t) => {
follow.0.clear();
follow.1 = false;
follow.0.insert(t);
}
Nonterminal(ref n) => {
let s = r.get_mut(n).unwrap();
for &t in follow.0.iter() {
if s.0.insert(t) {
changed = true;
}
}
if !s.1 && follow.1 {
s.1 = true;
changed = true;
}
let &(ref f, nullable) = first.get(n).unwrap();
if !nullable {
follow.0.clear();
follow.1 = false;
}
follow.0.extend(f.iter().map(|x| *x));
}
}
}
}
}
if !changed {
break;
}
}
r
}
pub fn lalr1<'a, FR, FO>(&'a self, mut reduce_on: FR, mut priority_of: FO)
-> Result<LR1ParseTable<'a, T, N, A>, LR1Conflict<'a, T, N, A>>
where FR: FnMut(&A, Option<&T>) -> bool,
FO: FnMut(&A, Option<&T>) -> i32 {
let state_machine = self.lr0_state_machine();
let augmented = state_machine.augmented_grammar();
let first_sets = augmented.first_sets();
let follow_sets = augmented.follow_sets(first_sets);
let mut r = LR1ParseTable {
states: state_machine.states.iter().map(|_| LR1State {
eof: None,
lookahead: BTreeMap::new(),
goto: BTreeMap::new(),
}).collect(),
};
// add shifts
for (i, &(_, ref trans)) in state_machine.states.iter().enumerate() {
for (&sym, &target) in trans.iter() {
match *sym {
Terminal(ref t) => {
let z = r.states[i].lookahead.insert(t, LRAction::Shift(target));
// can't have conflicts yet
debug_assert!(z.is_none());
}
Nonterminal(ref n) => {
let z = r.states[i].goto.insert(n, target);
debug_assert!(z.is_none());
}
}
}
}
// add reductions
for ((&(start_state, lhs), rhss),
(&&(s2, l2), &(ref follow, eof)))
in augmented.rules.iter().zip(follow_sets.iter()) {
debug_assert_eq!(start_state, s2);
debug_assert!(lhs == l2);
for &Rhs { syms: _, act: (end_state, rhs) }
in rhss.iter() {
for &&t in follow.iter().filter(|&&&t| reduce_on(&rhs.act, Some(t))) {
match r.states[end_state].lookahead.entry(t) {
btree_map::Entry::Vacant(v) => {
v.insert(LRAction::Reduce(lhs, rhs));
}
btree_map::Entry::Occupied(mut v) => {
match *v.get_mut() {
LRAction::Reduce(l, r) if l == lhs
&& r as *const Rhs<T, N, A>
== rhs as *const Rhs<T, N, A> => {
// The cells match, so there's no conflict.
}
LRAction::Reduce(ref mut l, ref mut r) => match priority_of(&r.act, Some(t)).cmp(&priority_of(&rhs.act, Some(t))) {
cmp::Ordering::Greater => {
// `r` overrides `rhs` - do nothing.
}
cmp::Ordering::Less => {
// `rhs` overrides `r`.
*l = lhs;
*r = rhs;
}
cmp::Ordering::Equal => {
// Otherwise, we have a reduce/reduce conflict.
return Err(LR1Conflict::ReduceReduce {
state: state_machine.states[end_state].0.clone(),
token: Some(t),
r1: (*l, *r),
r2: (lhs, rhs),
});
}
},
LRAction::Shift(_) => {
return Err(LR1Conflict::ShiftReduce {
state: state_machine.states[end_state].0.clone(),
token: Some(t),
rule: (lhs, rhs),
});
}
LRAction::Accept => {
unreachable!();
}
}
}
}
}
if eof && reduce_on(&rhs.act, None) {
let state = &mut r.states[end_state];
if *lhs == self.start {
match state.eof {
Some(_) => unreachable!(),
_ => ()
}
state.eof = Some(LRAction::Accept);
} else {
match state.eof {
Some(LRAction::Reduce(l, r)) if l == lhs
&& r as *const Rhs<T, N, A>
== rhs as *const Rhs<T, N, A> => {
// no problem
}
Some(LRAction::Reduce(ref mut l, ref mut r)) => match priority_of(&r.act, None).cmp(&priority_of(&rhs.act, None)) {
cmp::Ordering::Greater => {
// `r` overrides `rhs` - do nothing.
}
cmp::Ordering::Less => {
// `rhs` overrides `r`.
*l = lhs;
*r = rhs;
}
cmp::Ordering::Equal => {
// We have a reduce/reduce conflict.
return Err(LR1Conflict::ReduceReduce {
state: state_machine.states[end_state].0.clone(),
token: None,
r1: (*l, *r),
r2: (lhs, rhs),
});
}
},
Some(LRAction::Shift(_)) => {
return Err(LR1Conflict::ShiftReduce {
state: state_machine.states[end_state].0.clone(),
token: None,
rule: (lhs, rhs),
});
}
Some(LRAction::Accept) => {
unreachable!();
}
None => {
state.eof = Some(LRAction::Reduce(lhs, rhs));
}
}
}
}
}
}
Ok(r)
}
}
impl<'a, T: Ord, N: Ord, A> LR0StateMachine<'a, T, N, A> {
pub fn augmented_grammar(&self) -> Grammar<&'a T, (usize, &'a N), (usize, &'a Rhs<T, N, A>)> {
let mut r: BTreeMap<(usize, &'a N), Vec<Rhs<&'a T, (usize, &'a N), (usize, &'a Rhs<T, N, A>)>>> = BTreeMap::new();
for (ix, &(ref iset, _)) in self.states.iter().enumerate() {
for item in iset.items.iter() {
if item.pos == 0 {
let new_lhs = (ix, item.lhs);
let mut state = ix;
let new_rhs = Rhs {
syms: item.rhs.syms.iter().map(|sym| {
let old_st = state;
state = *self.states[old_st].1.get(sym).unwrap();
match *sym {
Terminal(ref t) => Terminal(t),
Nonterminal(ref n) => {
let nt = (old_st, n);
if let btree_map::Entry::Vacant(view) = r.entry(nt) {
view.insert(vec![]);
}
Nonterminal(nt)
}
}
}).collect(),
act: (state, item.rhs),
};
r.entry(new_lhs).or_insert(vec![]).push(new_rhs);
}
}
}
Grammar {
rules: r,
start: (0, self.start),
}
}
}
impl<'a, T: Debug, N: Debug, A> LR0StateMachine<'a, T, N, A> {
pub fn print(&self) {
println!(r#"
digraph G {{
node [
shape="box",
style="rounded",
penwidth=1,
width=2.0
];"#);
for (i, &(ref iset, ref trans)) in self.states.iter().enumerate() {
print!("s{}[label=<", i);
for item in iset.items.iter() {
print!("{:?} →", item.lhs);
for j in 0..item.pos {
print!(" {:?}", item.rhs.syms[j]);
}
print!(" •");
for j in item.pos..item.rhs.syms.len() {
print!(" {:?}", item.rhs.syms[j]);
}
print!("<br />\n");
}
println!(">]");
for (sym, &target) in trans.iter() {
println!("s{} -> s{} [label=<{:?}>]", i, target, sym);
}
}
println!("}}");
}
}
|
use criterion::{criterion_group, criterion_main, Criterion};
use but_what_about::{PermuteIter};
const STRING: &'static str = "ABCDEF";
pub fn criterion_benchmark(c: &mut Criterion) {
// Iter permute
let mut iter = PermuteIter::from(STRING);
c.bench_function("iter_permute", |b| b.iter(|| iter.next()));
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches); |
fn main() {
let guess: u32 = 1
} |
use crate::RealValue;
#[derive(Debug, Default, Copy, Clone, PartialEq)]
pub struct Rounding {
pub top_left: RealValue,
pub top_right: RealValue,
pub bottom_left: RealValue,
pub bottom_right: RealValue,
}
impl<T: Into<RealValue>> From<T> for Rounding {
fn from(radius: T) -> Self {
let radius = radius.into();
Self {
top_left: radius,
top_right: radius,
bottom_left: radius,
bottom_right: radius,
}
}
}
|
#[repr(packed)]
pub struct Tss {
pub reserved1: u32,
pub sp0: usize,
pub sp1: usize,
pub sp2: usize,
pub reserved2: u32,
pub reserved3: u32,
pub ist1: usize,
pub ist2: usize,
pub ist3: usize,
pub ist4: usize,
pub ist5: usize,
pub ist6: usize,
pub ist7: usize,
pub reserved4: u32,
pub reserved5: u32,
pub reserved6: u16,
pub iomap_base: u16,
}
|
use std::fs::File;
use std::io::{self, BufRead};
use std::error::Error;
use std::path::Path;
use clap::{App, Arg};
use itertools::Itertools;
fn main() -> Result<(), Box<dyn Error>> {
let matches = App::new("efflux")
.version("v1.0-beta")
.arg(
Arg::with_name("file")
.short("f")
.long("file")
.value_name("FILE")
.help("The input file")
.required(true),
)
.arg(
Arg::with_name("host")
.short("h")
.long("host")
.value_name("host")
.help("The splunk hostname e.g: foo.splunk.com")
.required(true),
)
.arg(
Arg::with_name("token")
.short("t")
.long("token")
.value_name("token")
.help("The splunk token")
.required(true),
)
.arg(
Arg::with_name("source")
.short("s")
.long("source")
.value_name("source")
.help("The splunk source")
.default_value("efflux"),
)
.arg(
Arg::with_name("sourcetype")
.short("y")
.long("sourcetype")
.value_name("sourcetype")
.help("The splunk sourcetype")
.default_value("generic_single_line"),
)
.get_matches();
let client = reqwest::blocking::Client::new();
let host = matches.value_of("host").unwrap();
let source = matches.value_of("source").unwrap();
let sourcetype = matches.value_of("sourcetype").unwrap();
let url = format!(
"https://{}/services/collector/raw?source={}&sourcetype={}",
host, source, sourcetype
);
let token = matches.value_of("token").unwrap();
let auth = format!("Splunk {}", token);
let file = matches.value_of("file").unwrap();
for (n, lines) in lines_from_file(file)?
.batching(|it| batch_lines(it))
.enumerate()
{
let size = lines.len();
let resp = client
.post(&url)
.body(lines)
.header("Authorization", &auth)
.send();
println!(
"request:{:?} size:{:#?} status:{:#?}",
n,
size,
resp.unwrap().status()
);
}
Ok(())
}
fn lines_from_file<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
where
P: AsRef<Path>,
{
let file = File::open(filename)?;
Ok(io::BufReader::new(file).lines())
}
fn batch_lines<I>(it: &mut I) -> Option<String>
where
I: Iterator<Item = std::result::Result<String, io::Error>>,
I: std::fmt::Debug,
{
let max = 1024 * 950;
let mut lines = String::with_capacity(max);
let mut size = 0;
while size < max {
match it.next() {
None => {
break;
}
Some(x) => {
let s = x.unwrap();
size += s.len();
lines.push_str(s.as_str());
lines.push('\n');
}
}
}
if lines.is_empty() {
None
} else {
Some(lines)
}
}
|
mod cards;
mod combinations;
mod game;
pub fn run() {
println!("PIQUET");
let seed: [u8; 16] = rand::random();
let mut game = game::Game::new(seed.clone());
println!("Game for seed {:?}: {:?}", seed, game);
}
|
use vulkano::buffer::{BufferUsage, CpuAccessibleBuffer};
use vulkano::command_buffer::{AutoCommandBufferBuilder, CommandBuffer};
use vulkano::device::{Device, DeviceExtensions, Features};
use vulkano::instance::{Instance, InstanceExtensions, PhysicalDevice};
use vulkano::sync::GpuFuture;
fn main() {
println!("Hello, world!");
let instance =
Instance::new(None, &InstanceExtensions::none(), None).expect("Failed to create instance");
let physical = PhysicalDevice::enumerate(&instance)
.next()
.expect("no device available");
for family in physical.queue_families() {
println!(
"Found a queue family with {:?} queue(s)",
family.queues_count()
);
}
let queue_family = physical
.queue_families()
.find(|&q| q.supports_graphics())
.expect("couldn't find a graphical queue family");
let (device, mut queues) = {
Device::new(
physical,
&Features::none(),
&DeviceExtensions::none(),
[(queue_family, 0.5)].iter().cloned(),
)
.expect("failed to create device")
};
let queue = queues.next().unwrap();
// let data = 12;
// let buffer = CpuAccessibleBuffer::from_data(device.clone(), BufferUsage::all(), data)
// .expect"failed to create buffer");
let source_content = 0..64;
let source = CpuAccessibleBuffer::from_iter(device.clone(), BufferUsage::all(), source_content)
.expect("failed to create buffer");
let dest_content = (0..64).map(|_| 0);
let dest = CpuAccessibleBuffer::from_iter(device.clone(), BufferUsage::all(), dest_content)
.expect("failed to create buffer");
let command_buffer = AutoCommandBufferBuilder::new(device.clone(), queue.family())
.map_err(|_| "dammit cant create this stuff")
.and_then(|x| {
x.copy_buffer(source.clone(), dest.clone())
.map_err(|_| "cant copy to buffer?")
})
.and_then(|x| x.build().map_err(|_| "whuuut"))
.unwrap();
let finished = command_buffer.execute(queue.clone()).unwrap();
finished
.then_signal_fence_and_flush()
.and_then(|x| x.wait(None))
.unwrap();
let source_content = source.read().unwrap();
let dest_content = dest.read().unwrap();
assert_eq!(&*source_content, &*dest_content);
let data_iter = 0..65536;
let data_buffer = CpuAccessibleBuffer::from_iter(device.clone(), BufferUsage::all(), data_iter)
.expect("Failed to create buffer");
}
|
#[allow(unused_imports)]
use log::{debug, info, warn};
use crate::{Color, DepthStencil, RenderTarget};
use js_sys::{Array, Error};
use web_sys::{WebGl2RenderingContext as Context, WebGlFramebuffer, WebGlTexture};
pub trait AsAttachment {
type Target: RenderTarget;
fn as_attachment(&self) -> Option<&WebGlTexture>;
fn attachment_dimensions(&self) -> (usize, usize);
}
#[derive(Debug)]
pub struct Framebuffer {
gl: Context,
handle: Option<WebGlFramebuffer>,
cols: usize,
rows: usize,
}
impl Framebuffer {
pub fn new(gl: Context) -> Self {
Self {
gl,
handle: None,
cols: 0,
rows: 0,
}
}
pub fn handle(&self) -> Option<&WebGlFramebuffer> {
self.handle.as_ref()
}
pub fn invalidate(&mut self) {
self.handle = None;
}
pub fn cols(&self) -> usize {
self.cols
}
pub fn rows(&self) -> usize {
self.rows
}
pub fn rebuild(
&mut self,
attachments: &[&dyn AsAttachment<Target = Color>],
depth_stencil: Option<&dyn AsAttachment<Target = DepthStencil>>,
) -> Result<(), Error> {
if let Err(_) | Ok(None) = self.gl.get_extension("EXT_color_buffer_float") {
return Err(Error::new("extension `EXT_color_buffer_float' missing"));
}
if let Err(_) | Ok(None) = self.gl.get_extension("EXT_float_blend") {
warn!("EXT_float_blend missing, browser may be out of date?");
}
assert!(!attachments.is_empty());
let (cols, rows) = attachments[0].attachment_dimensions();
if let Some(framebuffer_handle) = &self.handle {
self.gl.delete_framebuffer(Some(framebuffer_handle));
}
self.handle = self.gl.create_framebuffer();
self.gl
.bind_framebuffer(Context::DRAW_FRAMEBUFFER, self.handle.as_ref());
let array = Array::new();
for (index, attachment) in attachments.iter().enumerate() {
let (next_cols, next_rows) = attachment.attachment_dimensions();
if (next_cols, next_rows) != (cols, rows) {
panic!("inconsistent framebuffer attachment dimensions");
}
let attachment_index = Context::COLOR_ATTACHMENT0 + index as u32;
self.gl.framebuffer_texture_2d(
Context::DRAW_FRAMEBUFFER,
attachment_index,
Context::TEXTURE_2D,
attachment.as_attachment(),
0,
);
array.push(&attachment_index.into());
}
if let Some(depth_stencil) = depth_stencil {
self.gl.framebuffer_texture_2d(
Context::DRAW_FRAMEBUFFER,
Context::DEPTH_STENCIL_ATTACHMENT,
Context::TEXTURE_2D,
depth_stencil.as_attachment(),
0,
);
}
match self.gl.check_framebuffer_status(Context::DRAW_FRAMEBUFFER) {
Context::FRAMEBUFFER_COMPLETE => { /* rebuild successful */ }
Context::FRAMEBUFFER_UNSUPPORTED => {
return Err(Error::new("framebuffer unsupported by this context"))
}
Context::FRAMEBUFFER_INCOMPLETE_ATTACHMENT => {
panic!("framebuffer incomplete: invalid attachment")
}
Context::FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT => {
panic!("framebuffer incomplete: missing attachment")
}
Context::FRAMEBUFFER_INCOMPLETE_DIMENSIONS => {
panic!("framebuffer incomplete: invalid dimensions")
}
_ => unreachable!("unknown framebuffer status"),
}
self.gl.draw_buffers(&array);
self.cols = cols;
self.rows = rows;
Ok(())
}
pub fn clear(&self, attachment: usize, color: [f32; 4]) {
self.gl
.bind_framebuffer(Context::DRAW_FRAMEBUFFER, self.handle.as_ref());
self.gl
.clear_bufferfv_with_f32_array(Context::COLOR, attachment as i32, &color);
}
pub fn clear_depth_stencil(&self, depth: f32, stencil: u8) {
self.gl
.bind_framebuffer(Context::DRAW_FRAMEBUFFER, self.handle.as_ref());
self.gl
.clear_bufferfi(Context::DEPTH_STENCIL, 0, depth, stencil as i32);
}
}
impl Drop for Framebuffer {
fn drop(&mut self) {
if let Some(framebuffer_handle) = &self.handle {
self.gl.delete_framebuffer(Some(framebuffer_handle));
}
}
}
|
use super::random::Rand;
use crate::parse::Edit;
use std::ops::Range;
use std::str;
#[derive(Debug)]
pub struct ReadRecorder<'a> {
content: &'a Vec<u8>,
indices_read: Vec<usize>,
}
impl<'a> ReadRecorder<'a> {
pub fn new(content: &'a Vec<u8>) -> Self {
Self {
content,
indices_read: Vec::new(),
}
}
pub fn read(&mut self, offset: usize) -> &'a [u8] {
if offset < self.content.len() {
if let Err(i) = self.indices_read.binary_search(&offset) {
self.indices_read.insert(i, offset);
}
&self.content[offset..(offset + 1)]
} else {
&[]
}
}
pub fn strings_read(&self) -> Vec<&'a str> {
let mut result = Vec::new();
let mut last_range: Option<Range<usize>> = None;
for index in self.indices_read.iter() {
if let Some(ref mut range) = &mut last_range {
if range.end == *index {
range.end += 1;
} else {
result.push(str::from_utf8(&self.content[range.clone()]).unwrap());
last_range = None;
}
} else {
last_range = Some(*index..(*index + 1));
}
}
if let Some(range) = last_range {
result.push(str::from_utf8(&self.content[range.clone()]).unwrap());
}
result
}
}
pub fn invert_edit(input: &Vec<u8>, edit: &Edit) -> Edit {
let position = edit.position;
let removed_content = &input[position..(position + edit.deleted_length)];
Edit {
position,
deleted_length: edit.inserted_text.len(),
inserted_text: removed_content.to_vec(),
}
}
pub fn get_random_edit(rand: &mut Rand, input: &Vec<u8>) -> Edit {
let choice = rand.unsigned(10);
if choice < 2 {
// Insert text at end
let inserted_text = rand.words(3);
Edit {
position: input.len(),
deleted_length: 0,
inserted_text,
}
} else if choice < 5 {
// Delete text from the end
let deleted_length = rand.unsigned(30).min(input.len());
Edit {
position: input.len() - deleted_length,
deleted_length,
inserted_text: vec![],
}
} else if choice < 8 {
// Insert at a random position
let position = rand.unsigned(input.len());
let word_count = 1 + rand.unsigned(3);
let inserted_text = rand.words(word_count);
Edit {
position,
deleted_length: 0,
inserted_text,
}
} else {
// Replace at random position
let position = rand.unsigned(input.len());
let deleted_length = rand.unsigned(input.len() - position);
let word_count = 1 + rand.unsigned(3);
let inserted_text = rand.words(word_count);
Edit {
position,
deleted_length,
inserted_text,
}
}
}
|
use serde::{Deserialize, Serialize};
use jsonwebtoken::{decode, DecodingKey, Validation, Algorithm};
use rocket::Outcome;
use rocket::http::Status;
use rocket::request::{self, Request, FromRequest};
use crate::libs::utils::get_env;
#[derive(Debug, Serialize, Deserialize)]
struct Jwt {
id: String,
role: String
}
fn is_valid_and_admin(key: &str) -> bool {
let jwt_secret = get_env("JWT_SECRET", "THIS_IS_THE_REFERENCE");
match String::from(key).get_mut(7..) {
Some(jwt) => {
match decode::<Jwt>(
&jwt,
&DecodingKey::from_secret(jwt_secret.as_ref()),
&Validation::new(Algorithm::HS256)
) {
Ok(jwt_obj) => {
jwt_obj.claims.role == String::from("administrator")
},
Err(_ignore) => false
}
},
None => false
}
}
pub struct AuthorizationGuard(String);
#[derive(Debug)]
pub enum ApiKeyError {
BadCount,
Missing,
Invalid,
}
impl<'a, 'r> FromRequest<'a, 'r> for AuthorizationGuard {
type Error = ApiKeyError;
fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
let keys: Vec<_> = request.headers().get("Authorization").collect();
match keys.len() {
0 => Outcome::Failure((Status::Unauthorized, ApiKeyError::Missing)),
1 if is_valid_and_admin(keys[0]) => Outcome::Success(AuthorizationGuard(keys[0].to_string())),
1 => Outcome::Failure((Status::Unauthorized, ApiKeyError::Invalid)),
_ => Outcome::Failure((Status::BadRequest, ApiKeyError::BadCount)),
}
}
}
|
use std::env;
use std::error::Error;
use std::i32;
use std::result;
type Result<T> = result::Result<T, Box<Error>>;
const WIDTH: usize = 300;
const HEIGHT: usize = 300;
#[derive(Clone, Copy)]
struct PowerCell(i32);
impl PowerCell {
fn generate(x: usize, y: usize, serial_num: i32) -> Self {
let (x, y) = (x as i32, y as i32);
let rack_id = x + 10;
let mut result = rack_id * y;
result += serial_num;
result *= rack_id;
let result = (result / 100) % 10;
Self(result - 5)
}
}
struct Grid {
sums: [[i32; WIDTH + 1]; HEIGHT + 1],
}
impl Grid {
fn from_serial_num(serial_num: i32) -> Self {
let mut power_cells = [[PowerCell(0); WIDTH + 1]; HEIGHT + 1];
for y in 1..=HEIGHT {
for x in 1..=WIDTH {
power_cells[y][x] = PowerCell::generate(x, y, serial_num);
}
}
let mut sums = [[0; WIDTH + 1]; HEIGHT + 1];
for y in 1..=HEIGHT {
for x in 1..=WIDTH {
sums[y][x] =
sums[y][x - 1] + sums[y - 1][x] - sums[y - 1][x - 1] + power_cells[y][x].0;
}
}
Self { sums }
}
fn max(&self, size: usize) -> (i32, usize, usize) {
let mut result = (i32::MIN, 1, 1);
for r in 0..=HEIGHT - size {
for c in 0..=WIDTH - size {
let power = self.sums[r + size][c + size] + self.sums[r][c]
- self.sums[r + size][c]
- self.sums[r][c + size];
if power > result.0 {
result = (power, c + 1, r + 1);
}
}
}
result
}
}
fn main() -> Result<()> {
let mut args = env::args();
args.next();
let serial_num: i32 = args.next().ok_or("missing serial_num")?.parse()?;
if args.next() != None {
return Err("expected 1 argument".into());
}
let grid = Grid::from_serial_num(serial_num);
let (_, x, y) = grid.max(3);
println!("{},{}", x, y);
let ((_, x, y), size) = (1..WIDTH).map(|size| (grid.max(size), size)).max().unwrap();
println!("{},{},{}", x, y, size);
Ok(())
}
|
use amethyst::ecs::{storage::DenseVecStorage, Component};
use std::collections::HashMap;
#[derive(Component)]
#[storage(DenseVecStorage)]
pub struct Ai {
pub states: Vec<AiState>,
pub current_state_index: usize,
pub previous_state_index: usize,
}
impl Ai {
pub fn current_state(&self) -> &AiState {
&self.states[self.current_state_index]
}
pub fn previous_state(&self) -> &AiState {
&self.states[self.previous_state_index]
}
}
pub struct AiState {
pub transitions: HashMap<StateQuery, usize>,
pub action: Action,
}
#[derive(Clone, Hash, PartialEq, Eq)]
pub enum StateQuery {
TargetNearby(u32),
TargetNotNearby(u32),
}
#[derive(Clone, PartialEq, Eq)]
pub enum Action {
Patrol,
Chase,
}
|
// Copyright [2020] [Muhammad Adeel Hussain]
use postgres::{Client, NoTls};
use std::env;
fn main() {
let mut client =
Client::connect("postgresql://todoapp@localhost:26257/todolists", NoTls).unwrap();
let args: Vec<String> = env::args().collect();
if args.is_empty() {
println!("Help \n Use addtask id and todo to add a task \n use taskdone id to remove a task \n use tasklist to display lists of taks");
}
let query = &args[1];
if query == "addtask" {
let id = &args[2];
let task = &args[3];
// Create the "tasks" table.
client
.execute(
"CREATE TABLE IF NOT EXISTS tasks (id STRING PRIMARY KEY, todo STRING)",
&[],
)
.unwrap();
// Insert a new todo.
client
.execute(
"INSERT INTO tasks (id, todo) VALUES ($1, $2)",
&[&id, &task],
)
.unwrap();
} else if query == "taskdone" {
//Remove a todo
let id = &args[2];
client
.execute("DELETE FROM tasks WHERE id = $1", &[&id])
.unwrap();
} else if query == "tasklist" {
// Print out the tasks.
println!("Task List:");
for row in &client.query("SELECT id, todo FROM tasks", &[]).unwrap() {
let id: String = row.get(0);
let task: String = row.get(1);
println!("{}: {}", id, task);
}
} else {
eprint!("Wrong Query");
}
}
|
use std::convert::TryInto;
use serenity::prelude::*;
use serenity::model::channel::Message;
use serenity::framework::standard::{
CommandResult,
Args,
macros::{
command,
group
}
};
use yoloxide::{
environment::Environment,
types::{
Token,
VecWindow,
ast::program::Program,
}
};
use cylon_ast::CylonRoot;
use regex::Regex;
use lazy_static::lazy_static;
mod config;
use config::{
YololConfig,
InputFlag,
YololInput,
OutputFlag
};
group!({
name: "yolol",
options: {},
commands: [yolol],
});
lazy_static! {
static ref CODE_MATCHER: Regex = Regex::new(r"\A(?s:\n*)```(?s:[a-z]*\n)?((?s).*)\n?```\z").expect("Code matching regex failed to compile!");
}
fn extract_input(input: &str) -> Result<&str, &str>
{
// The regex ensures the input was formatted into a code block and has a capture group for the text of the input
let captures = match CODE_MATCHER.captures(input)
{
Some(captures) => captures,
None => {
return Err("Your supplied code isn't properly put into a code block. Be sure to surround it with triple backticks!")
}
};
// Capture 0 is the whole thing. The input capture is the only capture, meaning it's capture 1
match captures.get(1)
{
Some(capture) => Ok(capture.as_str()),
None => Err("Something is wrong with extracting input from code block! Someone might have broken the regex we use...")
}
}
fn output_execution(input: YololInput, env: &mut Environment) -> Result<(), String>
{
let tick_limit = 1000;
let code = match input
{
YololInput::Yolol(code) => code,
YololInput::CylonAst(_) => {
return Err("Execution from Cylon AST not yet supported! Psst, try outputting yolol then using it as input ;)".to_owned())
}
};
let lines: Vec<String> = code.lines().map(String::from).collect();
let line_len: i64 = lines.len().try_into().unwrap();
for _ in 0..tick_limit
{
// This is a stupid line but I can't find a better way to do it for some reason...
let next_line = if env.next_line > line_len || env.next_line <= 0 { 1 } else { env.next_line };
env.next_line = next_line;
let next_line: usize = next_line.try_into().unwrap();
yoloxide::execute_line(env, lines[next_line - 1].clone());
}
Ok(())
}
fn output_yolol(input: YololInput) -> Result<String, String>
{
match parse_yolol(input)
{
Ok(prog) => Ok(format!("{}", prog)),
Err(e) => Err(e)
}
}
fn output_cylon_ast(input: YololInput) -> Result<String, String>
{
let cylon_root = match input
{
YololInput::CylonAst(root) => root,
yolol => match parse_yolol(yolol) {
Ok(prog) => CylonRoot::new(prog.into()),
Err(e) => return Err(e)
}
};
match serde_json::to_string(&cylon_root)
{
Ok(ast) => Ok(ast),
Err(error) => Err(format!("Converting AST to Cylon AST failed with error: ```{}```", error))
}
}
fn output_ast(input: YololInput) -> Result<String, String>
{
match parse_yolol(input)
{
Ok(prog) => Ok(format!("{:?}", prog)),
Err(e) => Err(e)
}
}
fn output_tokens(input: YololInput) -> Result<String, String>
{
match tokenize_yolol(input)
{
Ok(tokens) => Ok(format!("{:?}", tokens)),
Err(e) => Err(e)
}
}
fn parse_yolol(input: YololInput) -> Result<Program, String>
{
if let YololInput::CylonAst(root) = input
{
return Ok(root.program.try_into()?)
}
let tokens = tokenize_yolol(input)?;
let mut window = VecWindow::new(tokens, 0);
match yoloxide::parser::parse_program(&mut window)
{
Ok(prog) => Ok(prog),
Err(error) => Err(format!("Parser failure: ```{}```", error)),
}
}
fn tokenize_yolol(input: YololInput) -> Result<Vec<Token>, String>
{
let code = match input
{
YololInput::Yolol(code) => code,
YololInput::CylonAst(_) => {
return Err("Can't tokenize a Cylon AST!".to_owned())
}
};
match yoloxide::tokenizer::tokenize(code)
{
Ok(tokens) => Ok(tokens),
Err(error) => Err(format!("Tokenizer failure: ```{}```", error)),
}
}
#[command]
fn yolol(context: &mut Context, message: &Message, args: Args) -> CommandResult
{
// Wrap the provided args in a new args struct, so we can control the delimiters used
let mut args = {
use serenity::framework::standard::{Args, Delimiter};
Args::new(args.message(), &[Delimiter::Single('\n'), Delimiter::Single(' ')])
};
// Parse arguments into a YololConfig
let config = match YololConfig::parse_args(&mut args)
{
Ok(config) => config,
Err(error) => {
message.channel_id.say(&context.http, error)?;
return Ok(())
}
};
// Anything after the flags is expected to be the input
let input = match extract_input(args.rest())
{
Ok(input) => input,
Err(error) => {
message.channel_id.say(&context.http, error)?;
return Ok(())
}
};
// Quickly checks to make sure there's no backticks in the code, since they can break output formatting
if input.contains('`')
{
message.channel_id.say(&context.http, "Your supplied code contains some backticks! No trying to break the output code blocks ;)")?;
return Ok(())
}
let input = match config.input
{
InputFlag::Yolol => YololInput::Yolol(input.to_owned()),
InputFlag::CylonAst => match serde_json::from_str(input) {
Ok(root) => YololInput::CylonAst(root),
Err(error) => {
message.channel_id.say(&context.http, format!("Converting Cylon AST json to internal representation failed with error: ```{}```", error))?;
return Ok(())
}
},
};
println!("Output: {:?}, input: {:?}", config.input, config.output);
match config.output
{
OutputFlag::Execution => {
let mut env = Environment::new("Bot");
match output_execution(input, &mut env)
{
Ok(_) => (),
Err(e) => {
message.channel_id.say(&context.http, e)?;
return Ok(())
}
}
let output = env.to_string();
if output.len() > 1900
{
use serenity::http::AttachmentType;
let attachment = vec![AttachmentType::Bytes((output.as_bytes(), "toaster_output.txt"))];
message.channel_id.send_files(&context.http, attachment, |m| m.content("The output was too long! Here's a file instead"))?;
}
else
{
let output = format!("Output environment from execution: ```{}```", output);
message.channel_id.say(&context.http, output)?;
}
},
OutputFlag::Yolol => {
let output = match output_yolol(input)
{
Ok(o) => o,
Err(e) => {
message.channel_id.say(&context.http, e)?;
return Ok(());
}
};
let output = format!("Reconstructed code: ```{}```", output);
message.channel_id.say(&context.http, output)?;
},
OutputFlag::CylonAst => {
let output = match output_cylon_ast(input)
{
Ok(o) => o,
Err(e) => {
message.channel_id.say(&context.http, e)?;
return Ok(());
}
};
use serenity::http::AttachmentType;
if output.len() > 2000
{
let attachment = vec![AttachmentType::Bytes((output.as_bytes(), "cylon_ast.json"))];
message.channel_id.send_files(&context.http, attachment, |m| m.content("The code was too long! Here's a file instead"))?;
}
else
{
let output = format!("Cylon AST of program:\n```json\n{}\n```", output);
message.channel_id.say(&context.http, output)?;
}
},
OutputFlag::Ast => {
let output = match output_ast(input)
{
Ok(o) => o,
Err(e) => {
message.channel_id.say(&context.http, e)?;
return Ok(());
}
};
let output = format!("Parsed program: ```{:?}```", output);
message.channel_id.say(&context.http, output)?;
},
OutputFlag::Tokens => {
let output = match output_tokens(input)
{
Ok(o) => o,
Err(e) => {
message.channel_id.say(&context.http, e)?;
return Ok(());
}
};
let output = format!("Tokenized program: ```{:?}```", output);
message.channel_id.say(&context.http, output)?;
}
}
Ok(())
} |
#![feature(test)]
extern crate test;
extern crate greeks;
use self::test::Bencher;
use greeks::*;
const UNDERLYING: f64 = 64.68;
const STRIKE: f64 = 65.00;
const VOL: f64 = 0.5051;
const INTEREST_RATE: f64 = 0.0150;
const DIV_YIELD: f64 = 0.0210;
const DAYS_PER_YEAR: f64 = 365.0;
const TIME_TO_EXPIRY: f64 = 23.0 / DAYS_PER_YEAR;
#[bench]
fn delta_call_bench(b: &mut Bencher) {
let r = b.iter(|| {
delta_call(UNDERLYING,
STRIKE,
TIME_TO_EXPIRY,
INTEREST_RATE,
DIV_YIELD,
VOL)
});
}
#[bench]
fn delta_put_bench(b: &mut Bencher) {
let r = b.iter(|| {
delta_put(UNDERLYING,
STRIKE,
TIME_TO_EXPIRY,
INTEREST_RATE,
DIV_YIELD,
VOL)
});
}
#[bench]
fn rho_call_bench(b: &mut Bencher) {
let r = b.iter(|| {
rho_call(UNDERLYING,
STRIKE,
TIME_TO_EXPIRY,
INTEREST_RATE,
DIV_YIELD,
VOL)
});
}
#[bench]
fn rho_put_bench(b: &mut Bencher) {
let r = b.iter(|| {
rho_put(UNDERLYING,
STRIKE,
TIME_TO_EXPIRY,
INTEREST_RATE,
DIV_YIELD,
VOL)
});
}
#[bench]
fn theta_call_bench(b: &mut Bencher) {
let r = b.iter(|| {
theta_call(UNDERLYING,
STRIKE,
TIME_TO_EXPIRY,
INTEREST_RATE,
DIV_YIELD,
VOL,
DAYS_PER_YEAR)
});
}
#[bench]
fn theta_put_bench(b: &mut Bencher) {
let r = b.iter(|| {
theta_put(UNDERLYING,
STRIKE,
TIME_TO_EXPIRY,
INTEREST_RATE,
DIV_YIELD,
VOL,
DAYS_PER_YEAR)
});
}
#[bench]
fn vega_bench(b: &mut Bencher) {
let r = b.iter(|| {
vega(UNDERLYING,
STRIKE,
TIME_TO_EXPIRY,
INTEREST_RATE,
DIV_YIELD,
VOL);
});
}
#[bench]
fn gamma_bench(b: &mut Bencher) {
let r = b.iter(|| {
gamma(UNDERLYING,
STRIKE,
TIME_TO_EXPIRY,
INTEREST_RATE,
DIV_YIELD,
VOL)
});
}
|
use crate::List::*;
enum List {
// Box<T> is a smart pointer for an object that is to be allocated on the heap.
Node(u32, Box<Box<List>>),
Nil,
}
// this is how code is attached to an enum
impl List {
fn new() -> List {
Nil
}
fn prepend(self, elem: u32) -> List {
Node(elem, Box::new(Box::new(self)))
}
fn len(&self) -> u32 {
// It is preferred to match a concrete type T and not a reference &T
match self {
Node(_elem, ref tail) => 1 + (*tail).len(),
Nil => 0
}
}
fn is_empty(&self) -> bool {
match self {
Node(_elem, ref _tail) => false,
Nil => true
}
}
fn stringify(&self) -> String {
match *self {
Node(elem, ref tail) => {
// 'format!' returns heap-allocated string
format!("{}, {}", elem, (*tail).stringify())
}
Nil => format!("Nil!")
}
}
}
fn main() {
let mut list = List::new();
list = list.prepend(15);
list = list.prepend(9);
list = list.prepend(4);
list = list.prepend(3);
list = list.prepend(1);
let string_repr = list.stringify();
println!("{}", string_repr);
println!("Length is {}", list.len());
println!("Is empty: {}", list.is_empty());
}
|
pub mod dynamo_db_driver;
pub mod storage_actor;
pub mod storage_driver;
|
//! Telnet contains code specifically to handle network I/O for a telnet connection
//!
use crate::portal::{Message, Rx, Tx};
use anyhow::anyhow;
use futures::prelude::*;
use log::{error, info};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use tokio::net::TcpListener;
use tokio::sync::mpsc;
use tokio_util::codec::{Framed, LinesCodec};
use uuid::Uuid;
/// A player connection
#[derive(Debug)]
pub struct Socket {
uuid: Uuid,
id: usize,
stream: Framed<tokio::net::TcpStream, LinesCodec>,
rx: Rx,
main_tx: Tx,
addr: String,
}
impl Socket {
/// Returns a new Socket
///
/// # Arguments
///
/// * `stream` - A `TcpStream` from Tokio
/// * `id` - A unique incrementing connection identifier
/// * `main_tx` - Transmit channel to communicate with the main task
///
/// # Errors
///
/// * This function will return an error if any send/recv operations fail on any channel or
/// stream, which would signal a connection error and disconnect the client.
pub async fn new(
stream: tokio::net::TcpStream,
id: usize,
main_tx: Tx,
) -> Result<Self, anyhow::Error> {
let addr = match stream.peer_addr() {
Ok(addr) => addr.to_string(),
Err(_) => "Unknown".to_string(),
};
info!("Telnet client connected: ID: {id}, remote_addr: {addr}");
let mut stream = Framed::new(stream, LinesCodec::new());
let (tx, rx) = mpsc::unbounded_channel();
stream.send("Welcome to the Ataxia Portal.").await?;
stream.send("Please enter your username:").await?;
let username = match stream.next().await {
Some(Ok(line)) => line,
Some(Err(_)) | None => {
return Err(anyhow!("Failed to get username from {addr}."));
}
};
stream.send(format!("Welcome, {username}!")).await?;
main_tx.send(Message::NewConnection(id, tx, username))?;
Ok(Self {
uuid: Uuid::new_v4(),
id,
stream,
rx,
main_tx,
addr,
})
}
/// Handle a connection
///
/// # Errors
///
/// * This function will return an error and disconnect the client if any send/recv fails.
///
/// # Panics
///
/// TODO: add possible panics
#[allow(clippy::mut_mut)]
pub async fn handle(mut self) -> Result<(), anyhow::Error> {
loop {
futures::select! {
data = self.rx.recv().fuse() => {
if let Some(message) = data {
match message {
Message::Data(_, message) => self.stream.send(message).await?,
_ => error!("Oops"),
}
} else {
// The main loop closed our channel to signal system shutdown
self.stream.send("The game is shutting down, goodbye!").await?;
break;
}
},
data = self.stream.next().fuse() => {
if let Some(message) = data {
if let Err(e) = self.main_tx.send(Message::Data(self.id, message?)) {
// The main loop channel was closed, most likely this signals a crash
self.stream.send("The game has crashed, sorry! Please try again.").await?;
error!("Connection error due to game crash? {}", e);
break;
}
} else {
// The other end closed the connection. Nothing left to do.
break;
}
},
};
}
self.main_tx.send(Message::CloseConnection(self.id))?;
Ok(())
}
}
/// Server data structure holding all the server state
#[derive(Debug)]
pub struct Server {
listener: TcpListener,
id_counter: Arc<AtomicUsize>,
main_tx: Tx,
}
impl Server {
/// Returns a new Server
///
/// # Arguments
///
/// * `address` - A String containing the listen addr:port
/// * `clients` - A shared binding to the client list
/// * `id_counter` - A shared binding to a global connection counter
///
/// # Errors
///
/// * Returns `tokio::io::Error` if the server can't bind to the listen port
///
pub async fn new(
address: &str,
id_counter: Arc<AtomicUsize>,
tx: Tx,
) -> Result<Self, anyhow::Error> {
let listener = TcpListener::bind(address).await?;
info!("Listening for telnet clients on {:?}", address);
Ok(Self {
listener,
id_counter,
main_tx: tx,
})
}
/// Start the listener loop, which will spawn individual connections into the runtime
#[allow(clippy::needless_return)]
pub async fn run(self) {
loop {
let connection = self.listener.accept().await;
match connection {
Err(e) => error!("Accept failed: {:?}", e),
Ok(stream) => {
let client_id = self.id_counter.fetch_add(1, Ordering::Relaxed);
let main_tx = self.main_tx.clone();
tokio::spawn(async move {
let socket = match Socket::new(stream.0, client_id, main_tx).await {
Ok(socket) => socket,
Err(e) => {
error!("Client disconnected: {}", e);
return;
}
};
if let Err(e) = socket.handle().await {
error!("Client error: {}", e);
return;
};
});
}
}
}
}
}
|
use std::{sync::Arc, time::Duration};
use bson::{doc, Document};
use crate::{
hello::LEGACY_HELLO_COMMAND_NAME,
runtime,
test::{
log_uncaptured,
spec::unified_runner::run_unified_tests,
Event,
EventHandler,
FailCommandOptions,
FailPoint,
FailPointMode,
SdamEvent,
TestClient,
CLIENT_OPTIONS,
},
Client,
};
#[cfg_attr(feature = "tokio-runtime", tokio::test(flavor = "multi_thread"))]
#[cfg_attr(feature = "async-std-runtime", async_std::test)]
async fn run_unified() {
// TODO RUST-1222: Unskip this file
let mut skipped_files = vec!["interruptInUse-pool-clear.json"];
if cfg!(not(feature = "tracing-unstable")) {
skipped_files.extend_from_slice(&[
"logging-standalone.json",
"logging-replicaset.json",
"logging-sharded.json",
"logging-loadbalanced.json",
]);
}
run_unified_tests(&["server-discovery-and-monitoring", "unified"])
.skip_files(&skipped_files)
.skip_tests(&[
// The driver does not support socketTimeoutMS.
"Reset server and pool after network timeout error during authentication",
"Ignore network timeout error on find",
])
.await;
}
/// Streaming protocol prose test 1 from SDAM spec tests.
#[cfg_attr(feature = "tokio-runtime", tokio::test(flavor = "multi_thread"))]
#[cfg_attr(feature = "async-std-runtime", async_std::test)]
async fn streaming_min_heartbeat_frequency() {
let test_client = TestClient::new().await;
if test_client.is_load_balanced() {
log_uncaptured("skipping streaming_min_heartbeat_frequency due to load balanced topology");
return;
}
let handler = Arc::new(EventHandler::new());
let mut options = CLIENT_OPTIONS.get().await.clone();
options.heartbeat_freq = Some(Duration::from_millis(500));
options.sdam_event_handler = Some(handler.clone());
let hosts = options.hosts.clone();
let client = Client::with_options(options).unwrap();
// discover a server
client
.database("admin")
.run_command(doc! { "ping": 1 }, None)
.await
.unwrap();
// For each server in the topology, start a task that ensures heartbeats happen roughly every
// 500ms for 5 heartbeats.
let mut tasks = Vec::new();
for address in hosts {
let h = handler.clone();
tasks.push(runtime::spawn(async move {
let mut subscriber = h.subscribe();
for _ in 0..5 {
let event = subscriber
.wait_for_event(Duration::from_millis(750), |e| {
matches!(e, Event::Sdam(SdamEvent::ServerHeartbeatSucceeded(e)) if e.server_address == address)
})
.await;
if event.is_none() {
return Err(format!("timed out waiting for heartbeat from {}", address));
}
}
Ok(())
}));
}
for task in tasks {
task.await.unwrap();
}
}
/// Variant of the previous prose test that checks for a non-minHeartbeatFrequencyMS value.
#[cfg_attr(feature = "tokio-runtime", tokio::test(flavor = "multi_thread"))]
#[cfg_attr(feature = "async-std-runtime", async_std::test)]
async fn heartbeat_frequency_is_respected() {
let test_client = TestClient::new().await;
if test_client.is_load_balanced() {
log_uncaptured("skipping streaming_min_heartbeat_frequency due to load balanced topology");
return;
}
let handler = Arc::new(EventHandler::new());
let mut options = CLIENT_OPTIONS.get().await.clone();
options.heartbeat_freq = Some(Duration::from_millis(1000));
options.sdam_event_handler = Some(handler.clone());
let hosts = options.hosts.clone();
let client = Client::with_options(options).unwrap();
// discover a server
client
.database("admin")
.run_command(doc! { "ping": 1 }, None)
.await
.unwrap();
// For each server in the topology, start a task that ensures heartbeats happen roughly every
// 1s for 3s.
let mut tasks = Vec::new();
for address in hosts {
let h = handler.clone();
tasks.push(runtime::spawn(async move {
let mut subscriber = h.subscribe();
// collect events for 2 seconds, should see between 2 and 3 heartbeats.
let events = subscriber.collect_events(Duration::from_secs(3), |e| {
matches!(e, Event::Sdam(SdamEvent::ServerHeartbeatSucceeded(e)) if e.server_address == address)
}).await;
if !(2..=3).contains(&events.len()) {
return Err(format!("expected 1 or 2 heartbeats, but got {}", events.len()));
}
Ok(())
}));
}
for task in tasks {
task.await.unwrap();
}
}
/// RTT prose test 1 from SDAM spec tests.
#[cfg_attr(feature = "tokio-runtime", tokio::test(flavor = "multi_thread"))]
#[cfg_attr(feature = "async-std-runtime", async_std::test)]
async fn rtt_is_updated() {
let test_client = TestClient::new().await;
if !test_client.supports_streaming_monitoring_protocol() {
log_uncaptured(
"skipping rtt_is_updated due to not supporting streaming monitoring protocol",
);
return;
}
if test_client.is_load_balanced() {
log_uncaptured("skipping rtt_is_updated due to load balanced topology");
return;
}
if test_client.supports_block_connection() {
log_uncaptured("skipping rtt_is_updated due to not supporting block_connection");
return;
}
let app_name = "streamingRttTest";
let handler = Arc::new(EventHandler::new());
let mut options = CLIENT_OPTIONS.get().await.clone();
options.heartbeat_freq = Some(Duration::from_millis(500));
options.app_name = Some(app_name.to_string());
options.sdam_event_handler = Some(handler.clone());
options.hosts.drain(1..);
options.direct_connection = Some(true);
let host = options.hosts[0].clone();
let client = Client::with_options(options).unwrap();
let mut subscriber = handler.subscribe();
// run a find to wait for the primary to be discovered
client
.database("foo")
.collection::<Document>("bar")
.find(None, None)
.await
.unwrap();
// wait for multiple heartbeats, assert their RTT is > 0
let events = subscriber
.collect_events(Duration::from_secs(2), |e| {
if let Event::Sdam(SdamEvent::ServerDescriptionChanged(e)) = e {
assert!(
e.new_description.average_round_trip_time().unwrap() > Duration::from_millis(0)
);
};
true
})
.await;
assert!(events.len() > 2);
// configure a failpoint that blocks hello commands
let fp = FailPoint::fail_command(
&["hello", LEGACY_HELLO_COMMAND_NAME],
FailPointMode::Times(1000),
FailCommandOptions::builder()
.block_connection(Duration::from_millis(500))
.app_name(app_name.to_string())
.build(),
);
let _gp_guard = fp.enable(&client, None).await.unwrap();
let mut watcher = client.topology().watch();
runtime::timeout(Duration::from_secs(10), async move {
loop {
watcher.wait_for_update(None).await;
let rtt = watcher
.server_description(&host)
.unwrap()
.average_round_trip_time
.unwrap();
if rtt > Duration::from_millis(250) {
break;
}
}
})
.await
.unwrap();
}
|
pub mod company;
pub mod intraday_prices;
|
#![feature(decl_macro)]
#[macro_use]
extern crate rocket;
pub mod connect;
mod payload;
pub mod state;
|
use std::fs::File;
use std::io::{self, prelude::*, BufReader};
use std::vec::Vec;
use std::string::String;
use std::time::{SystemTime};
use std::env;
use std::fs;
use std::path::PathBuf;
#[macro_use] extern crate lazy_static;
extern crate regex;
use regex::Regex;
#[derive(Debug)]
enum LineType {
ActionSeparator,
Section(String),
Mnemonic(String),
Remotable(bool),
Cacheable(bool),
Diff,
Boring,
}
fn parse_line(text: &str) -> LineType {
lazy_static! {
static ref DIFF: Regex = Regex::new("^[^ ]").unwrap();
static ref SECTION: Regex = Regex::new("^ ([^ ]+) \\{").unwrap();
static ref KV: Regex = Regex::new("^ ([^ ]+): (.+)").unwrap();
}
let separator: &str = " ---------------------------------------------------------";
if text == separator {
return LineType::ActionSeparator;
}
if DIFF.is_match(text) {
return LineType::Diff
}
if let Some(cap) = SECTION.captures(text) {
return LineType::Section(cap[1].to_string());
}
if let Some(cap) = KV.captures(text) {
match &cap[1] {
"mnemonic" => return LineType::Mnemonic(cap[2].to_string()),
"remotable" => return LineType::Remotable(cap[2].parse().unwrap()),
"cacheable" => return LineType::Cacheable(cap[2].parse().unwrap()),
&_ => {}
}
}
LineType::Boring
}
fn print_summary(action_count: i64, line_count: usize, started: SystemTime) {
let elapsed = started.elapsed().unwrap().as_secs_f64();
println!("Processed {0:>5} total messages in {1:.1} seconds ({2:>7.0} messages/sec, {3:>10.0} lines/sec)", action_count, elapsed, action_count as f64 / elapsed, line_count as f64 / elapsed);
}
fn main() -> io::Result<()> {
let started = SystemTime::now();
let diff_path = fs::canonicalize(PathBuf::from(env::args().nth(1).unwrap())).unwrap();
let file = File::open(&diff_path).unwrap();
let reader = BufReader::new(file);
let mut curr: Vec<String> = vec!();
let mut action_count: i64 = 0;
let mut line_count: usize = 0;
let mut remotable: bool = false;
let mut cacheable: bool = false;
let mut section: Option<String> = None;
let mut section_diffs: Vec<String> = vec!();
let mut mnemonic: Option<String> = None;
for (index, line) in reader.lines().enumerate() {
line_count += 1;
let line = line.unwrap();
let line_type = parse_line(&line);
match line_type {
LineType::ActionSeparator => {
action_count += 1;
if action_count % 1_000 == 0 {
print_summary(action_count, index, started);
}
if !section_diffs.is_empty() && (remotable || cacheable) {
println!("{}", curr.join("\n"));
}
curr.clear();
remotable = false;
cacheable = false;
section = None;
section_diffs.clear();
mnemonic = None;
},
LineType::Section(n) => section = Some(n),
LineType::Remotable(r) => remotable = r,
LineType::Cacheable(c) => cacheable = c,
LineType::Mnemonic(m) => mnemonic = Some(m),
LineType::Diff => {
if let Some(s) = §ion {
section_diffs.push(s.to_string())
} else if !curr.is_empty() {
panic!("{:?}:{}: Diff outside of a section!", &diff_path, index + 1);
}
},
LineType::Boring => {},
// _ => panic!("Unhandled line {:#?}", line_type)
}
curr.push(line);
}
print_summary(action_count, line_count, started);
Ok(())
}
|
mod registry;
mod block_data;
pub use registry::BlockState;
pub use block_data::*;
|
use totsu::prelude::*;
use totsu::*;
use totsu_f64lapack::F64LAPACK;
use totsu_core::solver::Operator;
use rand::prelude::*;
use rand_distr::StandardNormal;
use rand_xoshiro::Xoshiro256StarStar;
use plotters::prelude::*;
use intel_mkl_src as _;
use anyhow::Result;
type La = F64LAPACK;
type AMatBuild = MatBuild<La>;
type AProbSDP = ProbSDP<La>;
type ASolver = Solver<La>;
const EPS_ACC: f64 = 1e-3;
const EPS_ZERO: f64 = 1e-12;
fn make_adj_matrix(x_num: usize, y_num: usize, seed: u64) -> AMatBuild
{
let l = x_num * y_num; // # of nodes
let mut rng = Xoshiro256StarStar::seed_from_u64(seed);
//----- make adjacent matrix
let mut sym_w = AMatBuild::new(MatType::SymPack(l));
for i in 0..l {
let x = i / y_num;
let y = i % y_num;
if x < x_num - 1 {
sym_w[(i, i + y_num)] = rng.sample(StandardNormal); // positive: dissimilar, negative: similar
}
if y < y_num - 1 {
sym_w[(i, i + 1)] = rng.sample(StandardNormal); // positive: dissimilar, negative: similar
}
}
//println!("{:?}", sym_w);
sym_w
}
fn make_sdp(sym_w: &AMatBuild) -> AProbSDP
{
let l = sym_w.size().0; // # of nodes
let vec_c = sym_w.clone().reshape_colvec();
//println!("{}", vec_c);
let n = vec_c.size().0;
let k = l;
let p = l;
let mut syms_f = vec![AMatBuild::new(MatType::SymPack(k)); n + 1];
let mut kk = 0;
for j in 0..l {
for i in 0..=j {
syms_f[kk][(i, j)] = -1.;
kk += 1;
}
}
let mut mat_a = AMatBuild::new(MatType::General(p, n));
let mut j = 0;
for i in 0..p {
mat_a[(i, j)] = 1.;
j += i + 2;
}
//println!("{}", mat_a);
let vec_b = AMatBuild::new(MatType::General(p, 1))
.by_fn(|_, _| 1.);
//println!("{}", vec_b);
AProbSDP::new(vec_c, syms_f, mat_a, vec_b, EPS_ZERO)
}
fn sample_feasible(rslt_x: &[f64], sym_w: &AMatBuild, seed: u64) -> (f64, AMatBuild)
{
let l = sym_w.size().0; // # of nodes
let mut rng = Xoshiro256StarStar::seed_from_u64(seed);
//----- random sampling to find the best feasible point
let mut sym_x = AMatBuild::new(MatType::SymPack(l));
let mut kk = 0;
for j in 0..l {
for i in 0..=j {
sym_x[(i, j)] = rslt_x[kk];
kk += 1;
}
}
//println!("{:?}", sym_x);
sym_x.set_sqrt(EPS_ZERO);
//println!("{:?}", sym_x);
let mut tmpx = AMatBuild::new(MatType::General(l, 1));
let mut x = AMatBuild::new(MatType::General(l, 1));
let mut o = [0f64; 1];
let mut o_feas = None;
let mut x_feas = AMatBuild::new(MatType::General(l, 1));
for _ in 0..l {
tmpx.set_by_fn(|_, _| rng.sample(StandardNormal));
//println!("{:?}", tmpx);
sym_x.as_op().op(1., tmpx.as_ref(), 0., x.as_mut());
for e in x.as_mut() {
*e = if *e > 0. {1.} else {-1.};
}
//println!("{:?}", x);
sym_w.as_op().op(1., x.as_ref(), 0., tmpx.as_mut());
tmpx.as_op().trans_op(1., x.as_ref(), 0., &mut o);
//println!("{}", o[0]);
if let Some(o_feas_some) = o_feas {
if o_feas_some > o[0] {
o_feas = Some(o[0]);
x_feas.set_iter_colmaj(x.as_ref());
}
}
else {
o_feas = Some(o[0]);
x_feas.set_iter_colmaj(x.as_ref());
}
}
let o_feas = o_feas.unwrap();
//println!("{}", o_feas);
//println!("{:?}", x_feas);
(o_feas, x_feas)
}
/// main
fn main() -> Result<()> {
env_logger::init();
//----- make adjacent matrix
let x_num = 8;
let y_num = 6;
let sym_w = make_adj_matrix(x_num, y_num, 10000);
//----- formulate partitioning problem as SDP
let mut sdp = make_sdp(&sym_w);
//----- solve SDP
let s = ASolver::new().par(|p| {
p.eps_acc = EPS_ACC;
p.eps_zero = EPS_ZERO;
utils::set_par_by_env(p);
});
let rslt = s.solve(sdp.problem())?;
//println!("{:?}", rslt);
//----- random sampling to find the best feasible point
let (_, x_feas) = sample_feasible(&rslt.0, &sym_w, 20000);
//println!("{:?}", x_feas);
//----- visualize
let root = SVGBackend::new("plot.svg", (480, 360)).into_drawing_area();
root.fill(&WHITE)?;
let mut chart = ChartBuilder::on(&root)
.margin(30)
.build_cartesian_2d(
0..x_num,
0..y_num
)?;
let scale = 5.;
for i in 0..sym_w.size().0 {
let x = i / y_num;
let y = i % y_num;
if x < x_num - 1 {
let a = sym_w[(i, i + y_num)];
let style = if a > 0. {RED} else {BLUE}.stroke_width((a.abs() * scale) as u32);
chart.draw_series(LineSeries::new(
[(x, y), (x + 1, y)], style
))?;
}
if y < y_num - 1 {
let a = sym_w[(i, i + 1)];
let style = if a > 0. {RED} else {BLUE}.stroke_width((a.abs() * scale) as u32);
chart.draw_series(LineSeries::new(
[(x, y), (x, y + 1)], style
))?;
}
}
let radius = 10;
for i in 0..sym_w.size().0 {
let x = i / y_num;
let y = i % y_num;
if x_feas[(i, 0)] > 0. {
chart.draw_series(
[Circle::new((x, y), radius, BLACK.filled())]
)?;
} else {
chart.draw_series(
[Circle::new((x, y), radius, WHITE.filled()), Circle::new((x, y), radius, &BLACK)]
)?;
}
}
Ok(())
}
|
mod fixtures;
use fixtures::{server, Error};
use rstest::rstest;
#[rstest(headers,
case(vec!["x-info: 123".to_string()]),
case(vec!["x-info1: 123".to_string(), "x-info2: 345".to_string()])
)]
fn custom_header_set(headers: Vec<String>) -> Result<(), Error> {
let server = server(headers.iter().flat_map(|h| vec!["--header", h]));
let resp = reqwest::blocking::get(server.url())?;
for header in headers {
let mut header_split = header.splitn(2, ':');
let header_name = header_split.next().unwrap();
let header_value = header_split.next().unwrap().trim();
assert_eq!(resp.headers().get(header_name).unwrap(), header_value);
}
Ok(())
}
|
pub mod factoring;
pub mod rational;
pub fn is_prime(number: u64) -> bool {
if number <= 14 {
match number {
1 | 9 => false,
2 => true,
_ => number % 2 == 1,
}
} else if number % 2 == 0 || number % 3 == 0 || number % 5 == 0 {
false
} else {
let start_factor = 7;
let mut factor = start_factor;
while factor <= number / start_factor {
if number % factor == 0 {
return false;
}
factor += 2;
}
true
}
}
pub fn gcd(a: u64, b: u64) -> u64 {
if b == 0 {
a
} else {
gcd(b, a % b)
}
}
pub fn quadratic_formula(a: f32, b: f32, c: f32) -> (f32, f32) {
let radical = (b * b - a * c * 4.0).sqrt();
let bottom = 2.0 * a;
((-b + radical) / bottom, (-b - radical) / bottom)
}
pub fn coprimes(val: u64) -> Vec<u64> {
use factoring::prime_factors;
let input_factors = prime_factors(val);
(2..val)
.map(|val| (val, prime_factors(val)))
.filter(|(_, factors)| {
for factor in &input_factors {
if factors.contains(&factor) {
return false;
}
}
true
})
.map(|(guess, _)| guess)
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn prime_test() {
for num in 1..100 {
let prime = is_prime(num);
// An even number that is not 2 is not prime
if num % 2 == 0 && num != 2 {
assert!(!prime);
}
}
}
#[test]
fn gcd_test() {
assert_eq!(gcd(54, 24), 6);
}
#[test]
fn quadratic_test() {
assert_eq!(quadratic_formula(2.0, -5.0, -3.0), (3.0, -0.5));
}
#[test]
fn coprime_test() {
assert_eq!(coprimes(9), vec![2, 4, 5, 7, 8]);
}
}
|
use crate::part::Part;
use std::fs::File;
use std::io::{BufRead, BufReader};
#[derive(Clone, Copy, Debug)]
enum Direction {
East = 0,
South = 1,
West = 2,
North = 3,
}
#[derive(Debug)]
enum Action {
Move(Direction, i64),
Left(i64),
Right(i64),
Forward(i64),
}
const DELTAS: [(i64, i64); 4] = [(1, 0), (0, -1), (-1, 0), (0, 1)];
fn go((x, y): (i64, i64), dir: usize, dist: i64) -> (i64, i64) {
let (dx, dy) = DELTAS[dir];
(x + dx * dist, y + dy * dist)
}
fn part1(actions: &[Action]) -> usize {
let (_, (x, y)) = actions.iter().fold((0, (0, 0)), |(d, coords), a| match a {
Action::Move(dir, dist) => (d, go(coords, *dir as usize, *dist)),
Action::Left(degrees) => {
let mut x = d - degrees / 90;
if x < 0 {
x += DELTAS.len() as i64;
}
(x, coords)
}
Action::Right(degrees) => ((d + (degrees / 90)) % 4, coords),
Action::Forward(dist) => (d, go(coords, d as usize, *dist)),
});
(x.abs() + y.abs()) as usize
}
fn rotate((x, y): (i64, i64), degrees: i64) -> (i64, i64) {
let (sin90, cos90) = DELTAS[(degrees.abs() / 90 - 1) as usize];
if degrees < 0 {
// counterclockwise
// x' = x * cos(d) - y * sin(d);
// y' = x * sin(d) + y * cos(d);
(x * cos90 - y * sin90, x * sin90 + y * cos90)
} else {
// clockwise
// x' = x * cos(d) + y * sin(d);
// y' = -x * sin(d) + y * cos(d);
(x * cos90 + y * sin90, -x * sin90 + y * cos90)
}
}
fn part2(actions: &[Action]) -> usize {
let (_, (x, y)) = actions
.iter()
.fold(((10, 1), (0, 0)), |(waypoint, coords), a| match a {
Action::Move(dir, dist) => (go(waypoint, *dir as usize, *dist), coords),
Action::Left(degrees) => (rotate(waypoint, -*degrees), coords),
Action::Right(degrees) => (rotate(waypoint, *degrees), coords),
Action::Forward(dist) => (
waypoint,
(coords.0 + waypoint.0 * dist, coords.1 + waypoint.1 * dist),
),
});
(x.abs() + y.abs()) as usize
}
pub fn run(part: Part, input_path: &str) -> i64 {
let f = File::open(input_path).expect("failed to open input file");
let reader = BufReader::new(f);
let actions = reader
.lines()
.map(|l| match l.unwrap().split_at(1) {
("N", v) => Action::Move(Direction::North, v.parse().unwrap()),
("S", v) => Action::Move(Direction::South, v.parse().unwrap()),
("E", v) => Action::Move(Direction::East, v.parse().unwrap()),
("W", v) => Action::Move(Direction::West, v.parse().unwrap()),
("L", v) => Action::Left(v.parse().unwrap()),
("R", v) => Action::Right(v.parse().unwrap()),
("F", v) => Action::Forward(v.parse().unwrap()),
_ => unreachable!(),
})
.collect::<Vec<_>>();
match part {
Part::Part1 => part1(&actions) as i64,
Part::Part2 => part2(&actions) as i64,
}
}
|
/// module, struct, interior mutability
mod mystructs;
// if no "mod mystructs;" here.
// failed to resolve: use of undeclared type or module `mystructs`
// use of undeclared type or module `mystructs`
// use mystructs::tuple_like::PrivateBounds;
// struct `PrivateBounds` is private
// use mystructs::tuple_like::{Bounds, usage_private_bounds};
// use mystructs::named_field::Point;
// use mystructs::unit_like::{*};
use mystructs::{
named_field::Point,
tuple_like::{usage_private_bounds, Bounds},
unit_like::*,
};
fn main() {
let such = Onesuch;
println!("Got Onesuch: {:?}", such);
let image_bounds = Bounds(1024, 768);
assert_eq!(image_bounds.0 * image_bounds.1, 786432);
println!("usage_private_bounds: {}", usage_private_bounds(1, 2));
// let point = Point{x:1024, y:768, z:100};
// field `z` of struct `mystructs::named_field::Point` is private
let point = Point::new(1024, 768);
println!("{}-{}", &point.x, &point.y);
println!("{}", &point);
// cannot assign to `point.x`, as `point` is not declared as mutable
// point.x = 2048;
let mut mut_point = Point::new(100, 200);
println!("{}", &mut_point);
mut_point.x = 200;
mut_point.y = 400;
println!("{}", &mut_point);
mut_point.pluse_z();
println!("{}", &mut_point);
// https://ricardomartins.cc/2016/06/08/interior-mutability
let inmut_point = Point::new(100, 200);
println!("{}", &inmut_point);
inmut_point.pluse_n();
println!("{}", &inmut_point);
}
|
use std::path::{Path, PathBuf};
use std::process::Command;
use anyhow::Result;
use crate::light_command::{set_current_dir, LightCommand};
fn prepare_grep_and_args(cmd_str: &str, cmd_dir: Option<PathBuf>) -> (Command, Vec<&str>) {
let args = cmd_str.split_whitespace().collect::<Vec<&str>>();
let mut cmd = Command::new(args[0]);
set_current_dir(&mut cmd, cmd_dir);
(cmd, args)
}
pub fn run(
grep_cmd: String,
grep_query: &str,
glob: Option<&str>,
cmd_dir: Option<PathBuf>,
number: Option<usize>,
enable_icon: bool,
) -> Result<()> {
let (mut cmd, mut args) = prepare_grep_and_args(&grep_cmd, cmd_dir);
// We split out the grep opts and query in case of the possible escape issue of clap.
args.push(grep_query);
if let Some(g) = glob {
args.push("-g");
args.push(g);
}
// currently vim-clap only supports rg.
// Ref https://github.com/liuchengxu/vim-clap/pull/60
if cfg!(windows) {
args.push(".");
}
cmd.args(&args[1..]);
let mut light_cmd = LightCommand::new_grep(&mut cmd, number, enable_icon);
light_cmd.execute(&args)?;
Ok(())
}
fn is_git_repo(dir: &Path) -> bool {
let mut gitdir = dir.to_owned();
gitdir.push(".git");
gitdir.exists()
}
pub fn run_forerunner(
cmd_dir: Option<PathBuf>,
number: Option<usize>,
enable_icon: bool,
) -> Result<()> {
let mut cmd = Command::new("rg");
let args = [
"--column",
"--line-number",
"--no-heading",
"--color=never",
"--smart-case",
"",
];
// Do not use --vimgrep here.
cmd.args(&args);
// Only spawn the forerunner job for git repo for now.
if let Some(dir) = &cmd_dir {
if !is_git_repo(dir) {
return Ok(());
}
} else if let Ok(dir) = std::env::current_dir() {
if !is_git_repo(&dir) {
return Ok(());
}
}
set_current_dir(&mut cmd, cmd_dir);
let mut light_cmd = LightCommand::new_grep(&mut cmd, number, enable_icon);
light_cmd.execute(&args)?;
Ok(())
}
#[test]
fn test_git_repo() {
let mut cmd_dir: PathBuf = "/Users/xuliucheng/.vim/plugged/vim-clap".into();
cmd_dir.push(".git");
if cmd_dir.exists() {
println!("{:?} exists", cmd_dir);
} else {
println!("{:?} does not exist", cmd_dir);
}
}
|
use crate::SCREEN_WIDTH;
use bevy::prelude::*;
pub struct GroundPlugin;
impl Plugin for GroundPlugin{
fn build(&self, app: &mut AppBuilder){
app.add_startup_system(setup.system());
}
}
fn setup(
mut commands: Commands,
assets: Res<AssetServer>,
mut texture_atlases: ResMut<Assets<TextureAtlas>>,
){
let tile_size = Vec2::splat(8.);
let tile_scale = Vec2::splat(6.);
let texture_handle = assets.load("graphics/tile_set.png");
let texture_atlas = TextureAtlas::from_grid(texture_handle, tile_size, 34, 28);
let texture_atlas_handle = texture_atlases.add(texture_atlas);
commands.spawn_bundle(OrthographicCameraBundle::new_2d());
let start_pos = Vec2::new(-SCREEN_WIDTH, -500. + tile_size.y);
let mut pos = Vec2::new(start_pos.x, start_pos.y);
while pos.y + (tile_size.y * tile_scale.y) <= -200.0{
pos.x = start_pos.x;
while pos.x + (tile_size.x * tile_scale.x) <= SCREEN_WIDTH{
commands.spawn_bundle(SpriteSheetBundle {
texture_atlas: texture_atlas_handle.clone(),
transform: Transform{
translation: Vec3::new(pos.x, pos.y, 0.0),
scale: tile_scale.extend(0.0),
..Default::default()
},
..Default::default()
});
pos.x += tile_size.x * tile_scale.x;
}
pos.y += tile_scale.y * tile_size.y;
}
} |
use crate::options::*;
use crate::rrulestr::build_rrule;
use chrono::prelude::*;
use chrono_tz::Tz;
use std::str::FromStr;
#[derive(Clone, Debug)]
pub struct RRule {
pub options: ParsedOptions,
}
impl RRule {
pub fn new(options: ParsedOptions) -> Self {
Self { options }
}
/// Returns all the recurrences of the rrule
pub fn all(&self) -> Vec<DateTime<Tz>> {
self.into_iter().collect()
}
/// Returns the last recurrence before the given datetime instance.
/// The inc keyword defines what happens if dt is an recurrence.
/// With inc == true, if dt itself is an recurrence, it will be returned.
pub fn before(&self, dt: DateTime<Tz>, inc: bool) -> Option<DateTime<Tz>> {
self.into_iter()
.take_while(|d| if inc { *d <= dt } else { *d < dt })
.last()
}
/// Returns the last recurrence after the given datetime instance.
/// The inc keyword defines what happens if dt is an recurrence.
/// With inc == true, if dt itself is an recurrence, it will be returned.
pub fn after(&self, dt: DateTime<Tz>, inc: bool) -> Option<DateTime<Tz>> {
self.into_iter()
.skip_while(|d| if inc { *d < dt } else { *d <= dt })
.next()
}
/// Returns all the recurrences of the rrule between after and before.
/// The inc keyword defines what happens if after and/or before are
/// themselves recurrences. With inc == true, they will be included in the
/// list, if they are found in the recurrence set.
pub fn between(
&self,
after: DateTime<Tz>,
before: DateTime<Tz>,
inc: bool,
) -> Vec<DateTime<Tz>> {
self.into_iter()
.skip_while(|d| if inc { *d < after } else { *d <= after })
.take_while(|d| if inc { *d <= before } else { *d < before })
.collect()
}
}
impl FromStr for RRule {
type Err = RRuleParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
build_rrule(s)
}
}
|
//! Mouse asynchronous implementation, using the PS2 mouse controller printing
//! the mouse point as a pixel to the screen
use conquer_once::spin::OnceCell;
use core::sync::atomic::{AtomicU8, Ordering};
use core::{
pin::Pin,
task::{Context, Poll},
};
use crossbeam_queue::ArrayQueue;
use futures_util::task::AtomicWaker;
use futures_util::{Stream, StreamExt};
use printer::{print, println, WRITER};
use x86_64::instructions::port::Port;
use x86_64::instructions::port::{PortGeneric, ReadWriteAccess};
static mut PORT_64: PortGeneric<u32, ReadWriteAccess> = Port::new(0x64);
static mut PORT_60: PortGeneric<u32, ReadWriteAccess> = Port::new(0x60);
static mut STATE: AtomicU8 = AtomicU8::new(0);
static WAKER: AtomicWaker = AtomicWaker::new();
static mut MOUSEPACKET: [u8; 3] = [0; 3];
static SCANCODE_QUEUE: OnceCell<ArrayQueue<[u8; 3]>> = OnceCell::uninit();
/// Asynchronously print the mouse onto the screen when the
/// a collection of mouse packets are ready in the scancode queue
pub async fn print_mouse() {
let mut scancodes = ScancodeStream::new();
let mut mouse_point = MousePoint::new();
init_mouse().unwrap();
while let Some(scancode) = scancodes.next().await {
let flags = MousePacketFlags::from_bits_truncate(scancode[0]);
if !flags.contains(MousePacketFlags::XSIGN) {
mouse_point.x += scancode[1] as i16;
if flags.contains(MousePacketFlags::XOVERFLOW) {
mouse_point.x += 255;
}
} else {
mouse_point.x -= 256 - scancode[1] as i16;
if flags.contains(MousePacketFlags::XOVERFLOW) {
mouse_point.x -= 255;
}
}
if !flags.contains(MousePacketFlags::YSIGN) {
mouse_point.y -= scancode[2] as i16;
if flags.contains(MousePacketFlags::YOVERFLOW) {
mouse_point.y -= 255;
}
} else {
mouse_point.y += 256 - scancode[2] as i16;
if flags.contains(MousePacketFlags::YOVERFLOW) {
mouse_point.y += 255;
}
}
if mouse_point.x < 0 {
mouse_point.x = 0
}
if mouse_point.x > WRITER.get().unwrap().lock().info.horizontal_resolution as i16 - 1 {
mouse_point.x = WRITER.get().unwrap().lock().info.horizontal_resolution as i16 - 1
}
if mouse_point.y < 0 {
mouse_point.y = 0
}
if mouse_point.y > WRITER.get().unwrap().lock().info.vertical_resolution as i16 - 1 {
mouse_point.y = WRITER.get().unwrap().lock().info.vertical_resolution as i16 - 1
}
WRITER.get().unwrap().lock().write_pixel(
mouse_point.x as usize,
mouse_point.y as usize,
255,
)
}
}
/// Add a mouse scancode to the mouse packet array, if we have collected 3
/// packets of information from the mouse port then process that information
/// and print the mouse
///
/// # Safety
/// Mutable statics are unsafe and are used here to collect mouse information in
/// a packet array, as well as the mouse state and each port for mouse initilization
pub unsafe fn add_scancode(scancode: u8) {
if let Ok(queue) = SCANCODE_QUEUE.try_get() {
match STATE.fetch_add(1, Ordering::Relaxed) {
0 => {
if scancode & 0b00001000 == 0b00001000 {
MOUSEPACKET[0] = scancode;
} else {
STATE.swap(0, Ordering::Relaxed);
}
}
1 => MOUSEPACKET[1] = scancode,
2 => {
MOUSEPACKET[2] = scancode;
if queue.push(MOUSEPACKET).is_err() {
println!("WARNING: scancode queue full; dropping mouse input");
} else {
WAKER.wake();
}
STATE.swap(0, Ordering::Relaxed);
}
_ => unreachable!("Mouse state should not exceed 2 in current impl"),
}
} else {
println!("WARNING: Mouse scancode queue uninitialized");
}
}
/// Private scancode stream for implementing the stream trait onto the scancode queue
struct ScancodeStream {
_private: (),
}
impl ScancodeStream {
/// Create a new scancode stream with a queue size of 100, can only be
/// initialized once else will panic with respective message
pub fn new() -> Self {
SCANCODE_QUEUE
.try_init_once(|| ArrayQueue::new(100))
.expect("Mouse ScancodeStream::new should only be called once");
ScancodeStream { _private: () }
}
}
impl Default for ScancodeStream {
fn default() -> Self {
Self::new()
}
}
impl Stream for ScancodeStream {
type Item = [u8; 3];
/// Poll for the next scancode in the stream, if the queue isn't empty else
/// register this context with a waker and continue execution once woken.
fn poll_next(self: Pin<&mut Self>, context: &mut Context) -> Poll<Option<[u8; 3]>> {
let queue = SCANCODE_QUEUE.try_get().expect("not initialized");
if let Ok(scancode) = queue.pop() {
return Poll::Ready(Some(scancode));
}
WAKER.register(context.waker());
match queue.pop() {
Ok(scancode) => {
WAKER.take();
Poll::Ready(Some(scancode))
}
Err(crossbeam_queue::PopError) => Poll::Pending,
}
}
}
use bitflags::bitflags;
bitflags! {
/// First mouse byte bitflags
///
/// See [Byte 1](https://wiki.osdev.org/Mouse_Input#Initializing_a_PS2_Mouse)
pub struct MousePacketFlags: u8 {
/// The left mouse button was clicked
const LEFTBUTTON = 1;
/// The right mouse button was clicked
const RIGHTBUTTON = 1 << 1;
/// The middle mouse button was clicked
const MIDDLEBUTTON = 1 << 2;
/// The mouse was moved in the x direction in this packet
const XSIGN = 1 << 4;
/// The mouse was moved in the y direction in this packet
const YSIGN = 1 << 5;
const XOVERFLOW = 1 << 6;
const YOVERFLOW = 1 << 7;
}
}
struct MousePoint {
pub x: i16,
pub y: i16,
}
impl MousePoint {
pub fn new() -> Self {
Self { x: 0, y: 0 }
}
}
fn init_mouse() -> Result<(), &'static str> {
unsafe { PORT_64.write(0xA8) };
mouse_wait();
unsafe { PORT_64.write(0x20) };
mouse_wait_input();
let mut status: u8 = unsafe { PORT_60.read() } as u8;
status |= 0b10;
mouse_wait();
unsafe { PORT_64.write(0x60) };
mouse_wait();
unsafe { PORT_60.write(status as u32) };
mouse_write(0xF6);
mouse_read();
mouse_write(0xF4);
mouse_read();
Ok(())
}
fn mouse_wait() {
let mut timeout = 100000;
while timeout != 0 {
if unsafe { PORT_64.read() } & 0b10 == 0 {
return;
}
timeout -= 1;
}
}
fn mouse_wait_input() {
let mut timeout = 100000;
while timeout != 0 {
if unsafe { PORT_64.read() } & 0b1 == 0b1 {
return;
}
timeout -= 1;
}
}
fn mouse_write(value: u8) {
mouse_wait();
unsafe { PORT_64.write(0xD4) };
mouse_wait();
unsafe { PORT_60.write(value as u32) };
}
fn mouse_read() -> u32 {
mouse_wait_input();
unsafe { PORT_60.read() }
}
|
// Copyright 2016 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Library and runtime for fidl bindings.
#![deny(missing_docs)]
#![deny(warnings)]
extern crate fuchsia_zircon as zircon;
extern crate byteorder;
#[macro_use] extern crate failure;
extern crate fuchsia_async as async;
extern crate futures;
extern crate parking_lot;
extern crate slab;
#[macro_use]
pub mod encoding2;
mod error;
pub mod client2;
pub mod endpoints2;
pub use error::{Error, Result};
use futures::task::{self, AtomicWaker};
use std::sync::atomic::{self, AtomicBool};
/// A type used from the innards of server implementations
pub struct ServeInner {
waker: AtomicWaker,
shutdown: AtomicBool,
channel: async::Channel,
}
impl ServeInner {
/// Create a new set of server innards.
pub fn new(channel: async::Channel) -> Self {
let waker = AtomicWaker::new();
let shutdown = AtomicBool::new(false);
ServeInner { waker, shutdown, channel }
}
/// Get a reference to the inner channel.
pub fn channel(&self) -> &async::Channel {
&self.channel
}
/// Set the server to shutdown.
pub fn shutdown(&self) {
self.shutdown.store(true, atomic::Ordering::Relaxed);
self.waker.wake();
}
/// Check if the server has been set to shutdown.
pub fn poll_shutdown(&self, cx: &mut task::Context) -> bool {
if self.shutdown.load(atomic::Ordering::Relaxed) {
return true;
}
self.waker.register(cx.waker());
self.shutdown.load(atomic::Ordering::Relaxed)
}
}
/// A specialized `Box<Future<...>>` type for FIDL.
/// This is a convenience to avoid writing
/// `Future<Item = I, Error = Error> + Send`.
/// The error type indicates various FIDL protocol errors, as well as general-purpose IO
/// errors such as a closed channel.
pub type BoxFuture<Item> = Box<futures::Future<Item = Item, Error = Error> + Send>;
/// A specialized `Future<...>` type for FIDL.
/// This is a convenience to avoid writing
/// `Future<Item = I, Error = fidl::Error> + Send`.
/// The error type indicates various FIDL protocol errors, as well as general-purpose IO
/// errors such as a closed channel.
pub trait Future<Item>: futures::Future<Item = Item, Error = Error> + Send {}
impl<T, Item> Future<Item> for T
where T: futures::Future<Item = Item, Error = Error> + Send {}
#[macro_export]
macro_rules! fidl_enum {
($typename:ident, [$($name:ident = $value:expr;)*]) => {
#[allow(non_upper_case_globals)]
impl $typename {
$(
pub const $name: $typename = $typename($value);
)*
#[allow(unreachable_patterns)]
fn fidl_enum_name(&self) -> Option<&'static str> {
match self.0 {
$(
$value => Some(stringify!($name)),
)*
_ => None,
}
}
}
impl ::std::fmt::Debug for $typename {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
f.write_str(concat!(stringify!($typename), "("))?;
match self.fidl_enum_name() {
Some(name) => f.write_str(&name)?,
None => ::std::fmt::Debug::fmt(&self.0, f)?,
}
f.write_str(")")
}
}
}
}
|
use crate::prelude::*;
use crate::security::SchedulerSecurityConf;
pub(crate) type SharedSchedulerMetaInfo = ShareData<SchedulerMetaInfo>;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct SchedulerMetaInfo {
name: String,
domain: String,
listening_address: String,
security_conf: SchedulerSecurityConf,
}
impl SchedulerMetaInfo {
pub(crate) fn get_app_host_name(&self) -> &String {
&self.domain
}
#[allow(dead_code)]
pub(crate) fn get_app_security_level(&self) -> SecurityLevel {
self.security_conf.security_level
}
pub(crate) fn get_app_security_key(&self) -> Option<&RSAPrivateKey> {
self.security_conf.rsa_private_key.as_ref().map(|k| &k.0)
}
}
impl Default for SchedulerMetaInfo {
fn default() -> Self {
let domain = env::var_os("SCHEDULER_DOMAIN")
.expect("No environment variable set `SCHEDULER_DOMAIN`.")
.to_str()
.map(|s| s.to_owned())
.expect("Environment variable resolution failure.");
let name = env::var_os("SCHEDULER_NAME")
.expect("No environment variable set `SCHEDULER_NAME`.")
.to_str()
.map(|s| s.to_owned())
.expect("Environment variable resolution failure.");
let listening_address = env::var_os("SCHEDULER_LISTENING_ADDRESS")
.expect("No environment variable set `SCHEDULER_LISTENING_ADDRESS`.")
.to_str()
.map(|s| s.to_owned())
.expect("Environment variable resolution failure.");
let security_conf = SchedulerSecurityConf::default();
SchedulerMetaInfo {
name,
domain,
listening_address,
security_conf,
}
}
}
|
use counter::Counter;
#[derive(Debug, Hash, PartialEq, Eq)]
struct Inty {
i: usize,
}
impl Inty {
pub fn new(i: usize) -> Inty {
Inty { i: i }
}
}
#[test]
fn advanced_usage() {
// <https://en.wikipedia.org/wiki/867-5309/Jenny>
let intys = vec![
Inty::new(8),
Inty::new(0),
Inty::new(0),
Inty::new(8),
Inty::new(6),
Inty::new(7),
Inty::new(5),
Inty::new(3),
Inty::new(0),
Inty::new(9),
];
let inty_counts = intys.iter().collect::<Counter<_>>();
println!("{:?}", inty_counts);
// {Inty { i: 8 }: 2, Inty { i: 0 }: 3, Inty { i: 9 }: 1, Inty { i: 3 }: 1,
// Inty { i: 7 }: 1, Inty { i: 6 }: 1, Inty { i: 5 }: 1}
assert!(inty_counts.get(&Inty { i: 8 }) == Some(&2));
assert!(inty_counts.get(&Inty { i: 0 }) == Some(&3));
assert!(inty_counts.get(&Inty { i: 6 }) == Some(&1));
}
|
use crate::level;
use crate::models::player;
use crate::models::points::Points;
use crate::ui;
use bevy::prelude::*;
pub fn setup(
commands: &mut Commands,
mut materials: ResMut<Assets<ColorMaterial>>,
asset_server: Res<AssetServer>,
) {
commands.spawn(OrthographicCameraBundle::new_2d());
commands.insert_resource(Points(0));
player::init(commands, &mut materials, asset_server.clone());
level::init(commands, asset_server.clone(), &mut materials);
ui::init(commands, asset_server.clone());
}
|
use components::*;
use pages::*;
use prelude::*;
use router::{RouterAgent, RouterInput, RouterOutput};
use scatter::*;
use stdweb::traits::IEvent;
use views::svg;
pub struct App {
route: Option<Result<Route, RouteError>>,
router: Box<Bridge<RouterAgent>>,
scatter: Box<Bridge<ScatterAgent>>,
context: Context,
scatter_connected: Option<Result<(), ScatterError>>,
scatter_identity: Option<Result<ScatterIdentity, ScatterError>>,
}
pub enum Msg {
Ignore,
Router(RouterOutput),
Scatter(ScatterOutput),
NavigateTo(Route),
Login,
Logout,
SelectChain(Chain),
}
impl Component for App {
type Message = Msg;
type Properties = ();
fn create(_: Self::Properties, mut link: ComponentLink<Self>) -> Self {
let callback = link.send_back(Msg::Router);
let mut router = RouterAgent::bridge(callback);
router.send(RouterInput::GetCurrentRoute);
let scatter = ScatterAgent::new("eosstrawpoll".into(), 10000, link.send_back(Msg::Scatter));
App {
route: None,
router,
scatter,
context: Context::default(),
scatter_connected: None,
scatter_identity: None,
}
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::NavigateTo(route) => {
let url = route.to_string();
self.router.send(RouterInput::ChangeRoute(url));
false
}
Msg::Router(output) => {
self.route = Some(output.pathname.parse());
true
}
Msg::Scatter(output) => match output {
ScatterOutput::GotIdentity(result) => {
self.scatter_identity = Some(result);
true
}
ScatterOutput::ForgotIdentity(_result) => {
self.scatter_identity = None;
true
}
ScatterOutput::Connected(result) => {
self.scatter_connected = Some(result);
true
}
ScatterOutput::PushedTransaction(_result) => false,
},
Msg::Login => {
let required_fields = self.context.selected_chain.to_scatter_required_fields();
let scatter_msg = ScatterInput::GetIdentity(required_fields);
self.scatter.send(scatter_msg);
false
}
Msg::Logout => {
self.scatter.send(ScatterInput::ForgetIdentity);
false
}
Msg::SelectChain(chain) => {
if chain != self.context.selected_chain {
let chain_id_prefix = chain.to_chain_id_prefix();
let route = Route::Home(Some(chain_id_prefix));
self.scatter.send(ScatterInput::ForgetIdentity);
self.context.selected_chain = chain;
self.router
.send(RouterInput::ChangeRoute(route.to_string()));
true
} else {
false
}
}
Msg::Ignore => false,
}
}
}
impl Renderable<App> for App {
fn view(&self) -> Html<Self> {
html! {
<div class="app", >
{ self.view_header() }
{ self.view_content() }
{ self.view_footer() }
</div>
}
}
}
fn app_logo() -> Html<App> {
html! {
<a class="app_logo",
href="/",
onclick=|e| {
e.prevent_default();
Msg::NavigateTo(Route::default())
},
>
{ "EOS Straw Poll" }
<span class="app_version", >
{ "PRE-ALPHA" }
</span>
</a>
}
}
impl App {
fn view_header(&self) -> Html<Self> {
html! {
<header class="app_header", >
<div class="app_container", >
{ app_logo() }
{ self.view_nav() }
{ self.view_chains_dropdown() }
{ self.view_user() }
</div>
</header>
}
}
fn view_nav(&self) -> Html<Self> {
html! {
<nav class="app_nav", >
<a class="app_link app_link_roadmap",
href="https://github.com/sagan-software/eosstrawpoll/projects",
target="_blank",
>
{ svg::roadmap() }
{ "Roadmap" }
</a>
<a class="app_link app_link_feedback",
href="https://eos-forum.org/#/e/eosstrawpoll",
target="_blank",
>
{ svg::megaphone() }
{ "Feedback" }
</a>
</nav>
}
}
fn view_chains_dropdown(&self) -> Html<Self> {
html! {
<div class="chain_dropdown", >
<div class="available_chains", >
{ for self.context.available_chains.iter().map(|chain| {
self.view_chain_dropdown(chain.clone())
})}
</div>
<div class="selected_chain", >
{ &self.context.selected_chain.long_name }
{ svg::chevron_down() }
</div>
</div>
}
}
fn view_chain_dropdown(&self, chain: Chain) -> Html<Self> {
let c = chain.clone();
let is_selected = chain == self.context.selected_chain;
let selected_class = if is_selected { "-selected" } else { "" };
html! {
<div class=format!("available_chain {}", selected_class),
onclick=|e| {
e.prevent_default();
Msg::SelectChain(chain.clone())
},
>
{ &c.long_name }
</div>
}
}
fn view_user(&self) -> Html<Self> {
let view = match (&self.scatter_connected, &self.scatter_identity) {
(None, _) => self.view_user_loading(),
(Some(Err(_)), _) => self.view_user_install_scatter(),
(_, None) => self.view_user_none(),
(_, Some(Ok(identity))) => self.view_user_ok(identity),
(_, Some(Err(error))) => self.view_user_err(error),
};
html! {
<nav class="app_user", >
{ view }
</nav>
}
}
fn view_user_loading(&self) -> Html<Self> {
html! {
<span
class="app_login btn btn-primary btn-lg -loading",
>
{ "Loading..." }
</span>
}
}
fn view_user_install_scatter(&self) -> Html<Self> {
html! {
<a
class="app_login btn btn-primary btn-lg -install",
href="https://get-scatter.com",
>
{ "Install " }
{ svg::scatter_large() }
</a>
}
}
fn view_user_none(&self) -> Html<Self> {
html! {
<button
class="app_login btn btn-primary btn-lg",
onclick=|_| Msg::Login,
>
{ "Login with " }
{ svg::scatter_large() }
</button>
}
}
fn view_user_ok(&self, identity: &ScatterIdentity) -> Html<Self> {
let account_name = identity
.account_name()
.unwrap_or_else(|| "Anon".to_string());
let profile_route = Route::Profile(
self.context.selected_chain.to_chain_id_prefix(),
account_name.clone(),
);
html! {
<div class="app_user_actions", >
<a
class="app_user_account",
href=profile_route.to_string(),
onclick=|e| {
e.prevent_default();
Msg::NavigateTo(profile_route.clone())
},
>
{ svg::head() }
{ account_name }
</a>
<button class="app_user_logout",
onclick=|_| Msg::Logout,
>
{ svg::logout() }
</button>
</div>
}
}
fn view_user_err(&self, _error: &ScatterError) -> Html<Self> {
html! {
<button
class="app_login btn btn-danger btn-lg",
onclick=|_| Msg::Login,
>
{ "Login with " }
{ svg::scatter_large() }
</button>
}
}
fn view_content(&self) -> Html<Self> {
html!{
<div class="app_content", >
{ self.view_page() }
</div>
}
}
fn view_footer(&self) -> Html<Self> {
html!{
<footer class="app_footer", >
<div class="app_container", >
<p class="app_footer_text", >
{ "Created by " }
<a href="//www.sagan.software", >{ "sagan.software" }</a>
{ " © 2018" }
</p>
<p class="app_footer_links", >
<a href="//www.github.com/sagan-software", >
{ svg::github() }
{ "Github" }
</a>
<a href="//www.twitter.com/SaganSoftware", >
{ svg::twitter() }
{ "Twitter" }
</a>
<a href="https://t.me/SaganSoftware", >
{ svg::telegram() }
{ "Telegram" }
</a>
</p>
</div>
</footer>
}
}
fn view_unknown_chain(&self, chain_id_prefix: &ChainIdPrefix) -> Html<Self> {
html! {
<div class="page error_page", >
<header class="page_header", >
<div class="app_container", >
<h1 class="page_title", >
{ "Unknown Chain"}
</h1>
</div>
</header>
<main class="page_content", >
<div class="app_container", >
{ svg::link_cross() }
<p>{ format!("Couldn't find an EOS blockchain with chain ID prefix '{}'", chain_id_prefix.to_string())}</p>
</div>
</main>
</div>
}
}
fn view_page(&self) -> Html<App> {
match &self.route {
Some(result) => match result {
Ok(route) => match route {
Route::Home(chain_id_prefix) => match chain_id_prefix {
Some(chain_id_prefix) => match self.context.find_chain(chain_id_prefix) {
Some(chain) => html! {
<HomePage:
context=&self.context,
chain=Some(chain),
/>
},
None => self.view_unknown_chain(chain_id_prefix),
},
None => html! {
<HomePage:
context=&self.context,
chain=None,
/>
},
},
Route::Profile(chain_id_prefix, ref account) => {
match self.context.find_chain(chain_id_prefix) {
Some(chain) => html! {
<ProfilePage:
context=&self.context,
chain=chain,
account=account,
/>
},
None => self.view_unknown_chain(chain_id_prefix),
}
}
Route::PollVoting(chain_id_prefix, ref poll_id) => {
match self.context.find_chain(chain_id_prefix) {
Some(chain) => html! {
<PollVotingPage:
context=&self.context,
chain=chain,
poll_id=poll_id,
/>
},
None => self.view_unknown_chain(chain_id_prefix),
}
}
Route::PollResults(chain_id_prefix, ref poll_id) => {
match self.context.find_chain(chain_id_prefix) {
Some(chain) => html! {
<PollResultsPage:
context=&self.context,
chain=chain,
poll_id=poll_id,
/>
},
None => self.view_unknown_chain(chain_id_prefix),
}
}
},
Err(error) => match error {
RouteError::NotFound(url) => html! {
<>
{ format!("404 not found: {}", url)}
</>
},
RouteError::SecurityError(_error) => html! {
<>
{ "something bad happened"}
</>
},
},
},
None => html! {
<>
{ "loading..."}
</>
},
}
}
}
|
const INPUT: &str = include_str!("../input");
type Result<T> = ::std::result::Result<T, Box<dyn ::std::error::Error>>;
fn main() -> Result<()> {
let parsed_input = parse_input(INPUT)?;
println!("{}", parsed_input.sum_metadata());
println!("{}", parsed_input.find_value());
Ok(())
}
#[derive(Debug, PartialEq)]
struct Node {
children: Vec<Node>,
metadata: Vec<u32>,
}
impl Node {
fn from_data(data: &[u32]) -> Self {
fn build_node(data: &[u32]) -> (Node, usize) {
let child_count = data[0];
let metadata_count = data[1];
let mut children = vec![];
let mut index = 2;
for _ in 0..child_count {
let (child, len) = build_node(&data[index..]);
children.push(child);
index += len;
}
let metadata = data[index..(index + metadata_count as usize)].to_vec();
index += metadata_count as usize;
(Node { children, metadata }, index)
}
build_node(data).0
}
fn sum_metadata(&self) -> u32 {
self.metadata.iter().sum::<u32>()
+ self.children.iter().map(|c| c.sum_metadata()).sum::<u32>()
}
fn find_value(&self) -> u32 {
if self.children.is_empty() {
return self.metadata.iter().sum();
}
self.metadata
.iter()
.map(|&m| {
self.children
.get(m as usize - 1)
.map(|c| c.find_value())
.unwrap_or(0)
})
.sum()
}
}
fn parse_input(input: &str) -> Result<Node> {
let data = input
.trim()
.split_whitespace()
.map(|d| d.parse().map_err(Box::from))
.collect::<Result<Vec<_>>>()?;
Ok(Node::from_data(&data))
}
#[cfg(test)]
mod test {
use super::*;
const SAMPLE_INPUT: &str = "2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2\n";
const REAL_INPUT: &str = include_str!("../input");
#[test]
fn it_parses_input_correctly() {
assert_eq!(parse_input(SAMPLE_INPUT).unwrap(), get_sample_input());
}
#[test]
fn it_solves_part_one_correctly() {
assert_eq!(get_sample_input().sum_metadata(), 138);
assert_eq!(parse_input(REAL_INPUT).unwrap().sum_metadata(), 49426);
}
#[test]
fn it_solves_part_two_correctly() {
assert_eq!(get_sample_input().find_value(), 66);
assert_eq!(parse_input(REAL_INPUT).unwrap().find_value(), 40688);
}
fn get_sample_input() -> Node {
Node {
metadata: vec![1, 1, 2],
children: vec![
Node {
metadata: vec![10, 11, 12],
children: vec![],
},
Node {
metadata: vec![2],
children: vec![Node {
metadata: vec![99],
children: vec![],
}],
},
],
}
}
}
|
pub mod html_client;
pub mod json_client;
|
use comet::api::Collectable;
use comet::api::Finalize;
use comet::api::Trace;
use comet::immix::Immix;
use derive_more::AsRef;
use crate::prelude::*;
pub trait Garbage: Collectable + Trace + Finalize {}
impl<T> Garbage for T where T: Collectable + Trace + Finalize {}
#[derive(AsRef, Deref, DerefMut, From, Debug)]
#[deref(forward)]
#[deref_mut(forward)]
#[as_ref(forward)]
pub struct Gc<T: Garbage>(comet::api::Gc<T, Immix>);
impl<T: PartialEq + Garbage> PartialEq for Gc<T> {
fn eq(&self, other: &Self) -> bool {
self.0 == other.0
}
}
impl<T: Garbage> Clone for Gc<T> {
fn clone(&self) -> Self {
self.0.into()
}
}
impl<T: Sharable> Gc<T> {
pub fn inner(self) -> T {
(*self.0).clone()
}
}
pub trait Alloc<T> {
fn alloc(self, ctx: Context) -> T;
}
macro_rules! alloc_identity {
{ $ty:ty } => {
impl Alloc<$ty> for $ty {
#[inline(always)]
fn alloc(self, ctx: Context) -> $ty {
self
}
}
}
}
pub(crate) use alloc_identity;
|
use serde::{Serialize, Serializer};
use uuid::Uuid;
use std::fmt;
#[derive(Debug, PartialEq)]
pub struct AppTopic {
pub room_id: Uuid,
pub resource: ResourceKind,
}
impl fmt::Display for AppTopic {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"apps/signals.netology-group.services/api/v1/rooms/{}/{}",
self.room_id, self.resource
)
}
}
impl Serialize for AppTopic {
fn serialize<S>(&self, serializer: S) -> ::std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&self.to_string())
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ResourceKind {
Agents,
Tracks,
}
impl fmt::Display for ResourceKind {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let value = format!("{:?}", self).to_lowercase();
f.write_str(&value)
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json;
use topic::Topic;
#[test]
fn display_topic() {
let topic = Topic::App(AppTopic {
room_id: Uuid::parse_str("058df470-73ea-43a4-b36c-e4615cad468e").unwrap(),
resource: ResourceKind::Agents,
});
let expected = "apps/signals.netology-group.services/api/v1/rooms/058df470-73ea-43a4-b36c-e4615cad468e/agents";
assert_eq!(topic.to_string(), expected);
}
#[test]
fn serialize_resource_kind() {
assert_eq!(
serde_json::to_string(&ResourceKind::Agents).unwrap(),
r#""agents""#
);
}
#[test]
fn serialize_topic() {
let topic = AppTopic {
room_id: Uuid::parse_str("050b7c6f-795c-4cb4-aeea-5ee3f9083de2").unwrap(),
resource: ResourceKind::Agents,
};
let expected = r#""apps/signals.netology-group.services/api/v1/rooms/050b7c6f-795c-4cb4-aeea-5ee3f9083de2/agents""#;
assert_eq!(serde_json::to_string(&topic).unwrap(), expected);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.