text stringlengths 8 4.13M |
|---|
pub fn is_valid_isbn(isbn: &str) -> bool {
let isbn_digits: Vec<char> = isbn.chars().enumerate()
.filter(|(index, ch)| {
ch.is_numeric() || (ch.is_alphabetic() && *ch == 'X' && *index == isbn.len() - 1 as usize)
})
.map(|(_, ch)| ch)
.collect();
let mut result: bool = isbn_digits.len() == 10;
if result == true {
let isbn_value = isbn_digits.iter().enumerate()
.fold(0, |sum, (index, value)| {
let val = match value {
'X' => 10,
rest => rest.to_digit(10).unwrap()
};
sum + ((10 - index as u32) * val)
});
result = isbn_value % 11 == 0;
}
result
}
|
fn main() {
let v = vec![10,20,30,40,50] ;
// 全ての要素を繰り返す
print!("v is ");
for i in &v {
print!("{} ", i );
}
println!("");
// イテレータを使う
print!("v is ");
for i in v.iter() {
print!("{} ", i );
}
println!("");
// インデックス付きで繰り返す
print!("v is ");
for (i, x) in v.iter().enumerate() {
print!("{}:{} ", i, x );
}
println!("");
// 繰り返し数を指定する
print!("FOR is ");
for i in 0..10 {
print!("{} ", i );
}
println!("");
// 途中で繰り返しを止める
print!("FOR is ");
for i in 0..10 {
if i == 5 {
break;
}
print!("{} ", i );
}
println!("");
// 途中で先頭に戻る
print!("FOR is ");
for i in 0..10 {
if i % 2 == 0 {
continue ;
}
print!("{} ", i );
}
println!("");
// while を使う
print!("WHILE is ");
let mut i = 0;
while i < 10 {
print!("{} ", i );
i += 2 ;
}
println!("");
// loop を使う
print!("LOOP is ");
let mut i = 0;
loop {
if i >= 10 {
break ;
}
print!("{} ", i );
i += 1 ;
}
println!("");
}
|
use ir_derive::{
Instruction,
ReadInstruction,
WriteInstruction,
};
use ir_traits::{
Instruction,
ReadInstruction,
WriteInstruction,
};
use super::Chunk;
use num_derive::FromPrimitive;
use num_traits::FromPrimitive;
use serde::{Serialize, Deserialize};
#[derive(FromPrimitive, Instruction, ReadInstruction, WriteInstruction, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[repr(u8)]
pub enum MIRInstructions{
///Module start
Module,
///End module
EndModule,
///Function start.
///At the beginning is where local variable preallocation will occur.
Fun,
///End function.
///This is where all drops to local variables and any references or values passed as arguments will occur.
EndFun,
//Function param.
//The call to the containing function will handle the pass-by.
FunParam,
//Literals
///Integer literal
Integer,
///Float literal
Float,
///String literal
String,
///Boolean literal
Bool,
///Unit type
Unit,
///Initialize object `name` with `mutability`.
///An allocation instruction must precede this with the size of the object.
///Following this will be a call to the initializer and its mutability.
ObjInit,
///Drop `name`. This can either be a value or a reference.
///The drop mechanism is smart. If what is being dropped is a reference,
///the reference counter will decrement the count for object `name`.
Drop,
//Memory management instructions
///Create reference for `refee`.
///High level references to properties will result in this instruction.
Ref,
///Move `name`.
///A single reference to a local variables will result in this instruction.
Move,
///Copy `name`.
///Where n is the number of references to a local variable, all references until n-1 will result in this instruction,
/// whereas the final reference to a local variable will result in a Move instruction.
Copy,
///Heap allocation of `size` for object `name`
HeapAlloc,
///Stack allocation of `size` for object `name`.
///Either an object contruction or a lateinit instruction must proceed this.
StackAlloc,
///Uninitialized/late initializer.
///This is used for leaving an resource empty until further notice.
///For immutable objects, this grants one free initial mutation for initialization, to which all subsequent mutations will become invalid.
///`None` is the placehold value, so instead of an unsafe empty place in memory, None will fill the emptyness.
///`None` is an object that can be stretched to fit any place whatsoever, and will simply just be garbage data.
///The syntax for this is:
/// let something: A = None
Lateinit,
///Mutate object `name`.
///An expression must proceed this instruction.
ObjMut,
///Halt compiler
Halt
} |
fn main() {
by_moving();
by_cloning();
by_mutating();
println!("concat!");
}
fn by_moving() {
let hello = "hello".to_string();
let world = "world";
let hello_world = hello + world;
println!("{}", hello_world);
}
fn by_cloning() {
let hello = "hello".to_string();
let world = "world";
let hello_world = hello.clone() + world;
println!("{} ", hello_world);
}
fn by_mutating() {
let mut hello = "hello".to_string();
let world = "world";
hello.push_str(world);
println!("{} ", hello);
}
|
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
pub use crate::syscall::raw::arch::abi::{
syscall0, syscall1, syscall2, syscall3, syscall4, syscall5, syscall6, SCT,
};
use crate::syscall::raw::{common};
pub use crate::syscall::raw::common::{
accept, accept4, acct, add_key, adjtimex, bind, bpf, brk, capget,
capset, chdir, chroot, clock_adjtime, clock_getres, clock_gettime,
clock_nanosleep, clock_settime, close, connect, delete_module, dup, dup3,
epoll_create1, epoll_ctl, epoll_pwait, eventfd2,
execve, execveat, exit, exit_group, faccessat, fallocate, fanotify_init,
fanotify_mark, fchdir, fchmod, fchmodat, fchown, fchownat, fcntl, fdatasync,
fgetxattr, finit_module, flistxattr, flock, fremovexattr, fsetxattr, fstatfs,
fsync, ftruncate, futex, getcpu, getcwd, getegid, geteuid, getgid,
getgroups, getitimer, get_mempolicy, getpeername, getpgid, getpid, getppid,
getpriority, getrandom, getresgid, getresuid, getrlimit, get_robust_list, getrusage,
getsid, getsockname, getsockopt, gettid, gettimeofday, getuid, getxattr, init_module,
inotify_add_watch, inotify_init1, inotify_rm_watch, io_cancel, ioctl,
io_destroy, io_getevents, ioprio_get, ioprio_set, io_setup, io_submit, kcmp,
kexec_load, keyctl, kill, lgetxattr, linkat, listen,
listxattr, llistxattr, lookup_dcookie, lremovexattr, lseek, lsetxattr, madvise, mbind,
memfd_create, mincore, mkdirat, mknodat, mlock, mlockall,
mount, move_pages, mprotect, mq_getsetattr, mq_open, mq_timedreceive, mq_timedsend,
mq_unlink, mremap, msgctl, msgget, msgrcv, msgsnd, msync, munlock, munlockall, munmap,
name_to_handle_at, nanosleep, openat, open_by_handle_at, perf_event_open,
personality, pipe2, pivot_root, ppoll, prctl, preadv, process_vm_readv,
process_vm_writev, pselect6, ptrace, pwritev, quotactl, read, readahead,
readlinkat, readv, reboot, recvfrom, recvmmsg, recvmsg, remap_file_pages, removexattr,
renameat, renameat2, request_key, restart_syscall, rt_sigaction,
rt_sigpending, rt_sigprocmask, rt_sigqueueinfo, rt_sigsuspend, rt_sigreturn,
rt_sigtimedwait, rt_tgsigqueueinfo, sched_getaffinity, sched_getattr, sched_getparam,
sched_get_priority_max, sched_get_priority_min, sched_getscheduler,
sched_rr_get_interval, sched_setaffinity, sched_setattr, sched_setparam,
sched_setscheduler, sched_yield, seccomp, semget, semop, semtimedop, sendmmsg,
sendmsg, sendto, setdomainname, setfsgid, setfsuid, setgid, setgroups, sethostname,
setitimer, set_mempolicy, setns, setpgid, setpriority, setregid, setresgid, setresuid,
setreuid, setrlimit, set_robust_list, setsid, setsockopt, set_tid_address,
settimeofday, setuid, setxattr, shmat, shmctl, shmdt, shmget, shutdown, sigaltstack,
signalfd4, socket, socketpair, splice, statfs, swapoff, swapon,
symlinkat, sync, sync_file_range, syncfs, sysinfo, syslog, tee, tgkill,
timer_delete, timerfd_create, timerfd_gettime, timerfd_settime, timer_getoverrun,
timer_gettime, timer_settime, times, tkill, truncate, umask, umount, unlinkat,
unshare, utimensat, vhangup, vmsplice, waitid,
write, writev,
};
use crate::kty::{
self,
c_uint, k_int, k_long, k_ulong, c_char, k_uint, linux_dirent64, loff_t,
new_utsname, pid_t, rlimit64, size_t, ssize_t, stat, c_int,
__NR_iopl, __NR_mmap, __NR_arch_prctl, __NR_clone,
};
#[cfg(target_pointer_width = "64")]
#[path = "x86_64/x64.rs"]
mod abi;
mod asm {
use crate::syscall::raw::arch::abi::{SCT};
#[inline(always)]
pub unsafe fn syscall0(n: SCT) -> SCT {
let ret: SCT;
asm!("syscall" : "={rax}"(ret)
: "{rax}"(n)
: "rcx", "r11", "memory"
: "volatile");
ret
}
#[inline(always)]
pub unsafe fn syscall1(n: SCT, a1: SCT) -> SCT {
let ret: SCT;
asm!("syscall" : "={rax}"(ret)
: "{rax}"(n), "{rdi}"(a1)
: "rcx", "r11", "memory"
: "volatile");
ret
}
#[inline(always)]
pub unsafe fn syscall2(n: SCT, a1: SCT, a2: SCT) -> SCT {
let ret: SCT;
asm!("syscall" : "={rax}"(ret)
: "{rax}"(n), "{rdi}"(a1), "{rsi}"(a2)
: "rcx", "r11", "memory"
: "volatile");
ret
}
#[inline(always)]
pub unsafe fn syscall3(n: SCT, a1: SCT, a2: SCT, a3: SCT) -> SCT {
let ret: SCT;
asm!("syscall" : "={rax}"(ret)
: "{rax}"(n), "{rdi}"(a1), "{rsi}"(a2), "{rdx}"(a3)
: "rcx", "r11", "memory"
: "volatile");
ret
}
#[inline(always)]
pub unsafe fn syscall4(n: SCT, a1: SCT, a2: SCT, a3: SCT, a4: SCT) -> SCT {
let ret: SCT;
asm!("syscall" : "={rax}"(ret)
: "{rax}"(n), "{rdi}"(a1), "{rsi}"(a2), "{rdx}"(a3),
"{r10}"(a4)
: "rcx", "r11", "memory"
: "volatile");
ret
}
#[inline(always)]
pub unsafe fn syscall5(n: SCT, a1: SCT, a2: SCT, a3: SCT, a4: SCT, a5: SCT) -> SCT {
let ret: SCT;
asm!("syscall" : "={rax}"(ret)
: "{rax}"(n), "{rdi}"(a1), "{rsi}"(a2), "{rdx}"(a3),
"{r10}"(a4), "{r8}"(a5)
: "rcx", "r11", "memory"
: "volatile");
ret
}
#[inline(always)]
pub unsafe fn syscall6(n: SCT, a1: SCT, a2: SCT, a3: SCT, a4: SCT, a5: SCT,
a6: SCT) -> SCT {
let ret: SCT;
asm!("syscall" : "={rax}"(ret)
: "{rax}"(n), "{rdi}"(a1), "{rsi}"(a2), "{rdx}"(a3),
"{r10}"(a4), "{r8}"(a5), "{r9}"(a6)
: "rcx", "r11", "memory"
: "volatile");
ret
}
}
// cross platform unification:
pub type StatType = stat;
pub type StatfsType = kty::statfs;
pub unsafe fn pread(fd: k_uint, buf: *mut c_char, count: size_t, pos: loff_t) -> ssize_t {
common::pread64(fd, buf, count, pos)
}
pub unsafe fn pwrite(fd: k_uint, buf: *const c_char, count: size_t,
pos: loff_t) -> ssize_t {
common::pwrite64(fd, buf, count, pos)
}
pub unsafe fn sendfile(out_fd: k_int, in_fd: k_int, offset: *mut loff_t,
count: size_t) -> ssize_t {
common::sendfile64(out_fd, in_fd, offset, count)
}
pub unsafe fn uname(name: *mut new_utsname) -> k_int {
common::newuname(name)
}
pub unsafe fn getdents(fd: k_uint, dirent: *mut linux_dirent64, count: k_uint) -> k_int {
common::getdents64(fd, dirent, count)
}
pub unsafe fn fadvise(fd: k_int, offset: loff_t, len: loff_t, advice: k_int) -> k_int {
common::fadvise64(fd, offset, len as size_t, advice)
}
pub unsafe fn fstatat(dfd: k_int, filename: *const c_char, statbuf: *mut stat,
flag: k_int) -> k_int {
common::newfstatat(dfd, filename, statbuf, flag)
}
pub unsafe fn prlimit(pid: pid_t, resource: k_uint, new_rlim: *const rlimit64,
old_rlim: *mut rlimit64) -> k_int {
common::prlimit64(pid, resource, new_rlim, old_rlim)
}
// x86_64 specific
pub unsafe fn iopl(level: c_uint) -> k_int {
call!(__NR_iopl, level) as k_int
}
pub unsafe fn mmap(addr: k_ulong, len: k_ulong, prot: k_ulong, flags: k_ulong,
fd: k_ulong, off: k_ulong) -> k_long {
call!(__NR_mmap, addr, len, prot, flags, fd, off) as k_long
}
pub unsafe fn clone(flags: k_ulong, newsp: *mut u8, parent_tidptr: *mut c_int,
child_tidptr: *mut c_int, tls: *mut u8) -> k_long {
call!(__NR_clone, flags, newsp, parent_tidptr, child_tidptr, tls) as k_long
}
pub unsafe fn arch_prctl(code: c_int, addr: k_ulong) -> c_int {
call!(__NR_arch_prctl, code, addr) as c_int
}
|
fn main() {
println!("cargo:rerun-if-changed=.git/HEAD");
if let Some(rev) = rev_parse() {
println!("cargo:rustc-env=RUSTBOT_REV={}", rev);
}
}
/// Retrieves SHA-1 git revision. Returns `None` if any step of the way fails,
/// since this is only nice to have for the ?revision command and shouldn't fail builds.
fn rev_parse() -> Option<String> {
let output = std::process::Command::new("git")
.args(&["rev-parse", "--short=9", "HEAD"])
.output()
.ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout).ok()
}
|
//! # homectl
//!
//! homectl is a library for controlling various smart home devices.
#![recursion_limit="128"]
#![feature(custom_attribute)]
#![feature(clamp)]
pub mod prot {
//! This module contains traits defining capabilities smart home devices can
//! possess as well as concrete smart home device implementations.
use std::net::IpAddr;
use std::io::Result;
use color_processing::Color;
/// A smart home device.
///
/// All smart home devices must implement this trait.
pub trait SmartDevice {
/// Attempts to construct a smart home device from IP address.
fn from_address(addr: &IpAddr) -> Result<Option<Self>>
where Self: std::marker::Sized;
/// Attempts to find devices on LAN.
fn discover() -> Result<Option<Vec<Self>>>
where Self: std::marker::Sized;
/// Attempts to update internal state.
///
/// All `_set_` methods should call `refresh()` before returning. Those
/// relying on device's state should first call it as well.
fn refresh(&mut self) -> Result<()>;
/// Attempts to turn the device on.
fn set_on(&mut self, on: bool) -> Result<()>;
/// Checks whether the device is on or not.
fn is_on(&self) -> bool;
/// Returns the address of the device.
fn address(&self) -> IpAddr;
/// Returns port used to communicate with the device.
fn port(&self) -> u16;
/// Returns name of the device.
///
/// This can be any string, but should be unique enough.
fn name(&self) -> String;
}
/// Smart home device that has RGB capability.
pub trait Rgb: SmartDevice {
/// Attempts to set color and brightness.
///
/// `brightness` is clamped to [0, 1] and corresponds to value in HSV
/// representation.
fn rgb_set(&mut self, color: &Color, brightness: f32) -> Result<()>;
/// Attempts to set color to the exact value of `color`.
fn rgb_set_exact(&mut self, color: &Color) -> Result<()>;
/// Attempts to set color, first dimming it to the previously set
/// brightness.
fn rgb_set_color(&mut self, color: &Color) -> Result<()>;
/// Attempts to set brightness.
fn rgb_set_brightness(&mut self, brightness: f32) -> Result<()>;
/// Gets color.
///
/// This method simply returns internally stored state. `refresh()`
/// should first be called to assure the values returned by getters are
/// accurate.
fn rgb_color(&self) -> Color;
/// Gets color.
///
/// This method simply returns internally stored state. `refresh()`
/// should first be called to assure the values returned by getters are
/// accurate.
fn rgb_brightness(&self) -> f32;
/// Gets color.
///
/// This method simply returns internally stored state. `refresh()`
/// should first be called to assure the values returned by getters are
/// accurate.
fn rgb_exact(&self) -> Color;
}
/// Smart home device that has brightness adjust capability.
pub trait Mono: SmartDevice {
/// Attempts to set brightness.
///
/// `brightness` is clamped to [0, 1].
fn mono_set(&mut self, brightness: f32) -> Result<()>;
/// Gets brightness.
///
/// This method simply returns internally stored state. `refresh()`
/// should first be called to assure the values returned by getters are
/// accurate.
fn mono(&self) -> f32;
}
/// Smart home Device that has Correlated Color Temperature adjust
/// capability.
pub trait Cct: SmartDevice {
/// Attempts to set color temperature and brightness.
fn cct_set(&mut self, kelvin: u16, brightness: f32) -> Result<()>;
/// Attempts to set color temperature keeping previously set brightness.
fn cct_set_temperature(&mut self, kelvin: u16) -> Result<()>;
/// Attempts to set brightness keeping previously set color temperature.
fn cct_set_brightness(&mut self, brightness: f32) -> Result<()>;
/// Gets temperature.
///
/// This method simply returns internally stored state. `refresh()`
/// should first be called to assure the values returned by getters are
/// accurate.
fn cct_temperature(&self) -> u16;
/// Gets brightness.
///
/// This method simply returns internally stored state. `refresh()`
/// should first be called to assure the values returned by getters are
/// accurate.
fn cct_brightness(&self) -> f32;
}
pub mod led_net {
//! Implementation of the LEDNET protocol
//!
//! # Note
//! The protocol was reverse-engineered from and tested only on
//! HF-LPB100-ZJ200 RGBWW model
use super::SmartDevice;
use super::Rgb;
use super::Cct;
use std::net::{TcpStream, UdpSocket, Ipv4Addr, IpAddr, SocketAddr};
use std::io::Write;
use std::io::Read;
use std::time::Duration;
use color_processing::Color;
use std::io::Error;
use std::io::ErrorKind;
use std::io::Result;
// TODO: move into impl LedNet?
// TODO: enum for models
const SUPPORTED: [&str; 1] = ["HF-LPB100-ZJ200",];
const DISCO_PORT: u16 = 48899;
const DISCO_MSG: &[u8] = b"HF-A11ASSISTHREAD";
const PORT: u16 = 5577;
/// Takes a comma separated list of values and returns it with its
/// checksum appended.
macro_rules! fin_cmd {
( $( $value:expr ),* ) => {
[ $( $value ),* , 0u8 $( .wrapping_add($value) )* ]
}
}
#[derive(Debug)]
pub struct LedNet {
addr: SocketAddr,
model: &'static str,
is_on: bool,
rgb_color_bytes: (u8, u8, u8),
cct_bytes: (u8, u8),
rgb_brightness: f32,
cct_temperature: u16,
cct_brightness: f32,
}
mod op {
pub const SET_POWER: u8 = 0x71;
pub const SET_COLOR: u8 = 0x31;
pub const GET_STATE: u8 = 0x81;
}
mod word {
pub const TERMINATOR: u8 = 0x0f;
pub const ON: u8 = 0x23;
pub const OFF: u8 = 0x24;
pub const WRITE_COLORS: u8 = 0xf0;
pub const WRITE_WHITES: u8 = 0x0f;
pub const WRITE_BOTH: u8 = WRITE_COLORS & WRITE_WHITES;
}
mod temp {
const MIN_TEMP: u16 = 2800;
const MAX_TEMP: u16 = 6500;
const TEMP_RANGE: u16 = MAX_TEMP - MIN_TEMP;
/// Converts device internal reprsentation of color temperature to
/// Kelvin.
pub fn to_kelvin(warm: u8, cold: u8) -> u16 {
if warm != 0 || cold != 0 {
let warm = warm as f32;
let cold = cold as f32;
let wc = warm + cold;
let leftover = 0xff as f32 - wc;
let warm = warm + (leftover * (warm / wc));
let k = (0xff as f32 - warm)
* (TEMP_RANGE as f32 / 0xff as f32)
+ MIN_TEMP as f32;
k as u16
} else {
0
}
}
/// Converts color temperature in Kelvin to the two-byte device
/// internal representation.
pub fn to_warm_cold(kelvin: u16) -> (u8, u8) {
let temp = (kelvin.clamp(MIN_TEMP, MAX_TEMP) - MIN_TEMP) as f32;
let warm = 0xff as f32 * (1.0 - temp / TEMP_RANGE as f32);
let cold = 0xff as f32 * (temp / TEMP_RANGE as f32);
(warm.ceil() as u8, cold.ceil() as u8)
}
}
impl std::fmt::Display for LedNet {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(
f,
"{name} -- Address: {addr} Power: {power} \
RGB: [{rgb} @ {rgb_b}%] CCT: [{white_t}K @ {white_b}%]",
name = self.name(),
addr = self.addr,
power = if self.is_on { "ON" } else { "OFF" },
rgb = self.rgb_color().to_rgb_string(),
rgb_b = (100.0 * self.rgb_brightness) as u8,
white_t = self.cct_temperature,
white_b = (100.0 * self.cct_brightness) as u8
)
}
}
impl SmartDevice for LedNet {
fn from_address(addr: &IpAddr) -> Result<Option<Self>> {
let socket = UdpSocket::bind(
SocketAddr::from((Ipv4Addr::UNSPECIFIED, DISCO_PORT))
)?;
LedNet::disco_send(
&socket,
&SocketAddr::new(*addr, DISCO_PORT)
)?;
let timeout = Some(Duration::from_millis(2500));
if let Some(dev) = LedNet::disco_recv(&socket, &timeout)? {
Ok(Some(dev))
} else {
Ok(None)
}
}
fn discover() -> Result<Option<Vec<LedNet>>> {
let socket = UdpSocket::bind(
SocketAddr::from((Ipv4Addr::UNSPECIFIED, DISCO_PORT))
)?;
socket.set_broadcast(true)?;
// Get a broadcast address for each interface
let mut bcast_addrs = Vec::new();
for iface in pnet_datalink::interfaces() {
if iface.is_up() && iface.is_broadcast() {
for ip in iface.ips {
if ip.is_ipv4() {
bcast_addrs.push(SocketAddr::from(
(ip.broadcast(), DISCO_PORT)
));
}
}
}
}
// Send the discovery message to each
for bcast_addr in bcast_addrs {
LedNet::disco_send(&socket, &bcast_addr)?;
}
let mut devs = Vec::new();
// If we block for more than two seconds assume no more
// responses will come
let timeout = Some(Duration::from_millis(2000));
while let Ok(maybe_dev) = LedNet::disco_recv(&socket, &timeout){
if let Some(dev) = maybe_dev {
devs.push(dev);
}
}
if !devs.is_empty() {
Ok(Some(devs))
} else {
Ok(None)
}
}
// TODO: get timers, etc
fn refresh(&mut self) -> Result<()> {
const STATE_RESP_LEN: usize = 14;
// TODO: What are the last two bytes?
const GET_STATE_MSG: &[u8] = &fin_cmd![
op::GET_STATE, 0x8a, 0x8b
];
// Tell the device we want its state
let mut stream = TcpStream::connect(self.addr)?;
stream.write_all(GET_STATE_MSG)?;
// Try to read it in
let timeout = Some(Duration::from_millis(2000));
let state = LedNet::read_response(
&mut stream,
STATE_RESP_LEN,
&timeout
)?;
// Make sure the checksum is okay
let checksum = state[..STATE_RESP_LEN - 1].iter()
.fold(0u8, |acc, b| acc.wrapping_add(*b));
if state[STATE_RESP_LEN - 1] != checksum {
return Err(Error::new(
ErrorKind::Other,
"Invalid checksum of state query response".to_owned()
));
}
// Compute brightnesses
let (_, _, rgb_b, _) = Color::new_rgb(
state[6],
state[7],
state[8]
).get_hsva();
let cct_b = 1.0 -
(0xff as i32 - (state[9] as i32 + state[11] as i32)
) as f32 / 0xff as f32;
// Update internal state
self.is_on = state[2] == word::ON;
self.rgb_color_bytes = (state[6], state[7], state[8]);
self.cct_bytes = (state[9], state[11]);
self.rgb_brightness = rgb_b as f32;
self.cct_temperature = temp::to_kelvin(state[9], state[11]);
self.cct_brightness = cct_b;
Ok(())
}
fn set_on(&mut self, on: bool) -> Result<()> {
const ON_COMMAND: &[u8] = &fin_cmd![
op::SET_POWER, word::ON, word::TERMINATOR
];
const ON_RESPONSE: &[u8] = &fin_cmd![
word::TERMINATOR, op::SET_POWER, word::ON
];
const OFF_COMMAND: &[u8] = &fin_cmd![
op::SET_POWER, word::OFF, word::TERMINATOR
];
const OFF_RESPONSE: &[u8] = &fin_cmd![
word::TERMINATOR, op::SET_POWER, word::OFF
];
if on {
self.write_command(ON_COMMAND, ON_RESPONSE)?;
} else {
self.write_command(OFF_COMMAND, OFF_RESPONSE)?;
}
self.refresh()?;
Ok(())
}
fn is_on(&self) -> bool {
self.is_on
}
fn address(&self) -> IpAddr {
self.addr.ip()
}
fn port(&self) -> u16 {
self.addr.port()
}
fn name(&self) -> String {
"LEDNET:".to_owned() + self.model
}
}
impl Rgb for LedNet {
fn rgb_set_exact(&mut self, color: &Color) -> Result<()> {
let command = fin_cmd![
op::SET_COLOR,
color.red,
color.green,
color.blue,
0u8,
0u8,
word::WRITE_COLORS,
word::TERMINATOR
];
self.write_command(&command, &[])?;
self.refresh()?;
Ok(())
}
fn rgb_set(
&mut self,
color: &Color,
brightness: f32
) -> Result<()> {
let (hue, sat, _, _) = color.get_hsva();
self.rgb_set_exact(&Color::new_hsv(hue, sat, brightness.into()))
}
fn rgb_set_color(&mut self, color: &Color) -> Result<()> {
self.refresh()?;
self.rgb_set(color, self.rgb_brightness)
}
fn rgb_set_brightness(&mut self, brightness: f32) -> Result<()> {
self.refresh()?;
self.rgb_set(&self.rgb_color(), brightness)
}
fn rgb_color(&self) -> Color {
let (hue, sat, _, _) = self.rgb_exact().get_hsva();
Color::new_hsv(hue, sat, 1.0)
}
fn rgb_brightness(&self) -> f32 {
self.rgb_brightness
}
fn rgb_exact(&self) -> Color {
Color::new_rgb(
self.rgb_color_bytes.0,
self.rgb_color_bytes.1,
self.rgb_color_bytes.2
)
}
}
impl Cct for LedNet {
fn cct_set(&mut self, kelvin: u16, brightness: f32) -> Result<()> {
let (warm, cold) = temp::to_warm_cold(kelvin);
let command = fin_cmd![
op::SET_COLOR,
0u8,
0u8,
0u8,
(warm as f32 * brightness.clamp(0.0, 1.0)) as u8,
(cold as f32 * brightness.clamp(0.0, 1.0)) as u8,
word::WRITE_WHITES,
word::TERMINATOR
];
self.write_command(&command, &[])?;
self.refresh()?;
Ok(())
}
fn cct_set_temperature(&mut self, kelvin: u16) -> Result<()> {
self.refresh()?;
self.cct_set(kelvin, self.cct_brightness)
}
fn cct_set_brightness(&mut self, brightness: f32) -> Result<()> {
self.refresh()?;
self.cct_set(self.cct_temperature, brightness)
}
fn cct_temperature(&self) -> u16 {
self.cct_temperature
}
fn cct_brightness(&self) -> f32 {
self.cct_brightness
}
}
impl LedNet {
//! LEDNET specific functionality.
/// Attempts to set WW and CW channels directly.
pub fn set_ww_cw(&mut self, ww: u8, cw: u8) -> Result<()> {
let command = fin_cmd![
op::SET_COLOR,
0u8,
0u8,
0u8,
ww,
cw,
word::WRITE_WHITES,
word::TERMINATOR
];
self.write_command(&command, &[])?;
self.refresh()?;
Ok(())
}
/// Attempts to set RGB and CCT outputs simultaneously.
pub fn set_rgb_cct(
&mut self,
color: Color,
kelvin: u16
) -> Result<()> {
let (warm, cold) = temp::to_warm_cold(kelvin);
let command = fin_cmd![
op::SET_COLOR,
color.red,
color.green,
color.blue,
warm,
cold,
word::WRITE_BOTH,
word::TERMINATOR
];
self.write_command(&command, &[])?;
self.refresh()?;
Ok(())
}
fn write_command(
&self,
command: &[u8],
expected: &[u8]
) -> Result<()> {
let mut stream = TcpStream::connect(self.addr)?;
stream.write_all(&command)?;
let timeout = Some(Duration::from_millis(2000));
let response = LedNet::read_response(
&mut stream,
expected.len(),
&timeout
)?;
if response != expected {
Err(Error::new(ErrorKind::Other, "Incorrect response"))
} else {
Ok(())
}
}
fn read_response(
mut stream: &TcpStream,
len: usize,
timeout: &Option<Duration>
) -> Result<Vec<u8>> {
let old_timeout = stream.read_timeout();
stream.set_read_timeout(*timeout)?;
let mut response = vec![0u8; len];
let ret = stream.read_exact(&mut response).map(|_| response);
stream.set_read_timeout(old_timeout.unwrap_or(None))?;
ret
}
fn disco_send(socket: &UdpSocket, addr: &SocketAddr) -> Result<()> {
let sent = socket.send_to(DISCO_MSG, addr)?;
if sent != DISCO_MSG.len() {
Err(Error::new(
ErrorKind::Other,
"Could not write full discovery message"
))
} else {
Ok(())
}
}
fn disco_recv(
socket: &UdpSocket,
timeout: &Option<Duration>
) -> Result<Option<LedNet>> {
// Save the old timeout so we can reset it when we are done
let old_timeout = socket.read_timeout();
socket.set_read_timeout(*timeout)?;
let mut buf = [0u8; 128];
let (len, mut addr) = socket.recv_from(&mut buf)?;
let mut maybe_dev: Option<LedNet> = None;
// Expected format:
// "192.168.1.212,F0FE6B5A6D68,HF-LPB100-ZJ200"
// \___________/ \__________/ \_____________/
// IP MAC Model ID
if let Ok(response) = std::str::from_utf8(&buf[..len]) {
let mut fields = response.split(',');
if let Some(m_id) = fields.nth(2) {
let m_id = SUPPORTED.iter().find(|&&e| e == m_id);
if let Some(model) = m_id {
addr.set_port(PORT);
// There really should be better syntax to
// partially default initialize...
let mut dev = LedNet {
// TODO: Should we read the address from the
// reply instead?
addr,
model,
is_on: Default::default(),
rgb_color_bytes: Default::default(),
cct_bytes: Default::default(),
rgb_brightness: Default::default(),
cct_temperature: Default::default(),
cct_brightness: Default::default(),
};
dev.refresh()?;
maybe_dev = Some(dev);
}
}
}
socket.set_read_timeout(old_timeout.unwrap_or(None))?;
Ok(maybe_dev)
}
}
}
}
pub mod mult {
//! This module is an assortment of traits and enums that provide a unified
//! interface to control various smart home devices without the need to
//! explicitly handle each one.
//!
//! # Example
//!
//! ```
//! use mult::{Command, Device};
//!
//! if let Ok(Some(mut devs)) = Device::discover() {
//! for dev in devs {
//! dev.exec(&Command::On)?;
//! }
//! }
//! ```
use crate::prot::{SmartDevice, Rgb, Cct, Mono};
use crate::prot::led_net::LedNet;
use std::io;
use std::error;
use std::fmt;
use std::net::IpAddr;
use color_processing::Color;
use homectl_macros::Commandable;
type ExecResult = std::result::Result<Option<Response>, Error>;
type Brightness = f32;
type Kelvin = u16;
/// Trait allowing multiple devices to be controlled via commands.
///
/// Should only be implemented using `#[derive(Commandable)]`
pub trait Commandable {
/// Attempts to find devices on LAN.
fn discover() -> Result<Option<Vec<Self>>, io::Error>
where Self: std::marker::Sized;
/// Attempts to construct a variant from IP address.
fn from_address(addr: &IpAddr) -> Result<Option<Self>, io::Error>
where Self: std::marker::Sized;
/// Attempts to execute a command. If the variant does not support a
/// given command `CommandNotSupported` is returned.
fn exec(&mut self, command: &Command) -> ExecResult;
/// Returns a brief description of the device.
fn description(&self) -> String;
}
/// Represents a smart home device.
#[derive(Debug, Commandable)]
pub enum Device {
#[homectl(cmd = "RgbCommands", cmd = "CctCommands")]
LedNet(LedNet),
}
#[derive(Debug)]
pub enum Error {
CommandNotSupported,
Io(io::Error),
}
impl error::Error for Error {}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use Error::*;
match self {
CommandNotSupported => write!(f, "Command not supported"),
Io(e) => write!(f, "I/O error: {}", e.to_string())
}
}
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Error {
Error::Io(err)
}
}
/// Possible responses from various getters.
pub enum Response {
Color(Color),
Brightness(Brightness),
Temperature(Kelvin),
IsOn(bool),
Address(IpAddr),
Port(u16),
}
impl fmt::Display for Response {
fn fmt(&self, f: &mut std::fmt::Formatter) -> fmt::Result {
match self {
Response::Color(c) => write!(f, "{}", c.to_rgb_string()),
Response::Brightness(b) => write!(f, "{}", (100.0 * b) as u8),
Response::Temperature(t) => write!(f, "{}", t),
Response::IsOn(o) => write!(f, "{}", o),
Response::Address(a) => write!(f, "{}", a),
Response::Port(p) => write!(f, "{}", p),
}
}
}
/// Supported commands.
pub enum Command {
On,
Off,
GetAddress,
GetPort,
IsOn,
RgbSet(Color, Brightness),
RgbSetExact(Color),
RgbSetColor(Color),
RgbSetBrightness(Brightness),
RgbGetColor,
RgbGetBrightness,
RgbGetExact,
CctSet(Kelvin, Brightness),
CctSetTemperature(Kelvin),
CctSetBrightness(Brightness),
CctGetTemperature,
CctGetBrightness,
MonoSet(Brightness),
MonoGet
}
trait SmartDeviceCommands {
fn exec(&mut self, command: &Command) -> ExecResult;
}
trait RgbCommands {
fn exec(&mut self, command: &Command) -> ExecResult;
}
trait CctCommands {
fn exec(&mut self, command: &Command) -> ExecResult;
}
trait MonoCommands {
fn exec(&mut self, command: &Command) -> ExecResult;
}
impl<T> SmartDeviceCommands for T where T: SmartDevice {
fn exec(&mut self, command: &Command) -> ExecResult {
match command {
Command::On => {
self.set_on(true)?;
Ok(None)
},
Command::Off => {
self.set_on(false)?;
Ok(None)
},
Command::GetAddress => {
Ok(Some(Response::Address(self.address())))
},
Command::GetPort => {
Ok(Some(Response::Port(self.port())))
},
Command::IsOn => {
Ok(Some(Response::IsOn(self.is_on())))
},
_ => Err(Error::CommandNotSupported)
}
}
}
impl<T> RgbCommands for T where T: Rgb {
fn exec(&mut self, command: &Command) -> ExecResult {
match command {
Command::RgbSet(c, b) => {
self.rgb_set(c, *b)?;
Ok(None)
},
Command::RgbSetExact(c) => {
self.rgb_set_exact(c)?;
Ok(None)
},
Command::RgbSetColor(c) => {
self.rgb_set_color(c)?;
Ok(None)
},
Command::RgbSetBrightness(b) => {
self.rgb_set_brightness(*b)?;
Ok(None)
},
Command::RgbGetColor => {
Ok(Some(Response::Color(self.rgb_color())))
},
Command::RgbGetBrightness => {
Ok(Some(Response::Brightness(self.rgb_brightness())))
},
Command::RgbGetExact => {
Ok(Some(Response::Color(self.rgb_exact())))
},
_ => Err(Error::CommandNotSupported)
}
}
}
impl<T> CctCommands for T where T: Cct {
fn exec(&mut self, command: &Command) -> ExecResult {
match command {
Command::CctSet(k, b) => {
self.cct_set(*k, *b)?;
Ok(None)
},
Command::CctSetTemperature(k) => {
self.cct_set_temperature(*k)?;
Ok(None)
},
Command::CctSetBrightness(b) => {
self.cct_set_brightness(*b)?;
Ok(None)
},
Command::CctGetTemperature => {
Ok(Some(Response::Temperature(self.cct_temperature())))
},
Command::CctGetBrightness => {
Ok(Some(Response::Brightness(self.cct_brightness())))
},
_ => Err(Error::CommandNotSupported)
}
}
}
impl<T> MonoCommands for T where T: Mono {
fn exec(&mut self, command: &Command) -> ExecResult {
match command {
Command::MonoSet(b) => {
self.mono_set(*b)?;
Ok(None)
},
Command::MonoGet => {
Ok(Some(Response::Brightness(self.mono())))
},
_ => Err(Error::CommandNotSupported)
}
}
}
}
|
use super::*;
use std::sync::RwLock;
pub struct RandomSearch<'a> {
handler: SearchHandler<'a>,
enable_dict: bool,
//dictionary: Dict,
}
impl<'a> RandomSearch<'a> {
pub fn new(handler: SearchHandler<'a>, enable_dict: bool) -> Self {
Self { handler, enable_dict }
}
pub fn run(&mut self) {
let mut input = self.handler.get_f_input();
let orig_input_val = input.get_value();
/*{
let cmpid = self.handler.cond.base.cmpid;
let offsets = self.handler.cond.offsets.clone();
let offsets_opt = self.handler.cond.offsets_opt.clone();
let mut d = match self.handler.executor.dictionary.read() {
Ok(guard) => guard,
Err(poisoned) => {
warn!("Lock poisoned. Results can be incorrect! Continuing...");
poisoned.into_inner()
}
};
match d.0.contains_key(&cmpid) {
true => {
info!("{:?} cmpid: {}, offsets: {:?}, offsets_opt: {:?}", d.0.get(&cmpid).unwrap(), cmpid, offsets, offsets_opt);
}
false => {
info!("not exists {}", cmpid);
}
}
}*/
loop {
if self.handler.is_stopped_or_skip() {
break;
}
input.assign(&orig_input_val);
input.randomize_all(self.enable_dict, self.handler.executor.dictionary.clone());
let ret = self.handler.execute_cond(&input).1;
if self.enable_dict && ret.len() > 0 {
let mut d = match self.handler.executor.dictionary.write() {
Ok(guard) => guard,
Err(poisoned) => {
warn!("Lock poisoned. Results can be incorrect! Continuing...");
poisoned.into_inner()
}
};
d.filter(ret, self.handler.buf.clone());
}
}
}
}
|
const ARRAY_MAX: usize = 25_000;
const LUDIC_MAX: usize = 2100;
/// Calculates and returns the first `LUDIC_MAX` Ludic numbers.
///
/// Needs a sufficiently large `ARRAY_MAX`.
fn ludic_numbers() -> Vec<usize> {
// The first two Ludic numbers
let mut numbers = vec![1, 2];
// We start the array with an immediate first removal to reduce memory usage by
// collecting only odd numbers.
numbers.extend((3..ARRAY_MAX).step_by(2));
// We keep the correct Ludic numbers in place, removing the incorrect ones.
for ludic_idx in 2..LUDIC_MAX {
let next_ludic = numbers[ludic_idx];
// We remove incorrect numbers by counting the indices after the correct numbers.
// We start from zero and keep until we reach the potentially incorrect numbers.
// Then we keep only those not divisible by the `next_ludic`.
let mut idx = 0;
numbers.retain(|_| {
let keep = idx <= ludic_idx || (idx - ludic_idx) % next_ludic != 0;
idx += 1;
keep
});
}
numbers
}
fn main() {
let ludic_numbers = ludic_numbers();
print!("First 25: ");
print_n_ludics(&ludic_numbers, 25);
println!();
print!("Number of Ludics below 1000: ");
print_num_ludics_upto(&ludic_numbers, 1000);
println!();
print!("Ludics from 2000 to 2005: ");
print_ludics_from_to(&ludic_numbers, 2000, 2005);
println!();
println!("Triplets below 250: ");
print_triplets_until(&ludic_numbers, 250);
}
/// Prints the first `n` Ludic numbers.
fn print_n_ludics(x: &[usize], n: usize) {
println!("{:?}", &x[..n]);
}
/// Calculates how many Ludic numbers are below `max_num`.
fn print_num_ludics_upto(x: &[usize], max_num: usize) {
let num = x.iter().take_while(|&&i| i < max_num).count();
println!("{}", num);
}
/// Prints Ludic numbers between two numbers.
fn print_ludics_from_to(x: &[usize], from: usize, to: usize) {
println!("{:?}", &x[from - 1..to - 1]);
}
/// Calculates triplets until a certain Ludic number.
fn triplets_below(ludics: &[usize], limit: usize) -> Vec<(usize, usize, usize)> {
ludics
.iter()
.enumerate()
.take_while(|&(_, &num)| num < limit)
.filter_map(|(idx, &number)| {
let triplet_2 = number + 2;
let triplet_3 = number + 6;
// Search for the other two triplet numbers. We know they are larger than
// `number` so we can give the searches lower bounds of `idx + 1` and
// `idx + 2`. We also know that the `n + 2` number can only ever be two
// numbers away from the previous and the `n + 6` number can only be four
// away (because we removed some in between). Short circuiting and doing
// the check more likely to fail first are also useful.
let is_triplet = ludics[idx + 1..idx + 3].binary_search(&triplet_2).is_ok()
&& ludics[idx + 2..idx + 5].binary_search(&triplet_3).is_ok();
if is_triplet {
Some((number, triplet_2, triplet_3))
} else {
None
}
})
.collect()
}
/// Prints triplets until a certain Ludic number.
fn print_triplets_until(ludics: &[usize], limit: usize) {
for (number, triplet_2, triplet_3) in triplets_below(ludics, limit) {
println!("{} {} {}", number, triplet_2, triplet_3);
}
} |
use std::time::Instant;
pub fn count_time_qps(tag: &str, total: u128, start: Instant) {
print_qps(tag, total, start);
print_each_time(tag, total, start);
}
///count qps
pub fn print_qps(tag: &str, total: u128, start: Instant) {
let time = start.elapsed().as_nanos();
println!(
"[count_qps] {} use qps: {} QPS/s",
tag,
(total * 1000000000 as u128 / time)
);
}
///计算每个操作耗时ns纳秒
pub fn print_each_time(tag: &str, total: u128, start: Instant) {
let time = start.elapsed();
println!(
"[count_each_time] {} use Time: {:?},each:{} ns/op",
tag,
time,
time.as_nanos() / total as u128
);
}
|
use std::fmt;
#[cfg(target_arch = "wasm32")]
use serde::Serialize;
#[cfg(not(feature = "std"))]
use alloc::string::String;
#[cfg_attr(target_arch = "wasm32", derive(Serialize))]
#[derive(Debug, Clone)]
pub struct ErrorMsg {
pub short: String,
pub extended: Option<String>,
}
impl fmt::Display for ErrorMsg {
fn fmt(&self, f: &mut std::fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.short)
}
}
#[derive(Debug, Copy, Clone)]
pub enum MsgType {
// Parser
DuplicateRuleIdentifier,
InvalidRuleIdentifier,
MissingAssignmentToken,
InvalidGenericSyntax,
MissingGenericClosingDelimiter,
InvalidGenericIdentifier,
InvalidUnwrapSyntax,
InvalidGroupToChoiceEnumSyntax,
InvalidTagSyntax,
MissingGroupEntryMemberKey,
MissingGroupEntry,
InvalidGroupEntrySyntax,
MissingClosingDelimiter,
MissingClosingParend,
InvalidMemberKeyArrowMapSyntax,
InvalidMemberKeySyntax,
InvalidOccurrenceSyntax,
NoRulesDefined,
IncompleteRuleEntry,
TypeSocketNamesMustBeTypeAugmentations,
GroupSocketNamesMustBeGroupAugmentations,
// Lexer
UnableToAdvanceToken,
InvalidControlOperator,
InvalidCharacter,
InvalidEscapeCharacter,
InvalidTextStringLiteralCharacter,
EmptyTextStringLiteral,
InvalidByteStringLiteralCharacter,
EmptyByteStringLiteral,
InvalidHexFloat,
InvalidExponent,
}
impl From<MsgType> for ErrorMsg {
fn from(mt: MsgType) -> ErrorMsg {
match mt {
MsgType::DuplicateRuleIdentifier => ErrorMsg {
short: "rule with the same identifier is already defined".into(),
extended: None,
},
MsgType::InvalidRuleIdentifier => ErrorMsg {
short: "expected rule identifier followed by an assignment token '=', '/=' or '//='".into(),
extended: None,
},
MsgType::MissingAssignmentToken => ErrorMsg {
short: "expected assignment token '=', '/=' or '//=' after rule identifier".into(),
extended: None,
},
MsgType::InvalidGenericSyntax => ErrorMsg {
short: "generic parameters should be between angle brackets '<' and '>' and separated by a comma ','".into(),
extended: None,
},
MsgType::MissingGenericClosingDelimiter => ErrorMsg {
short: "missing closing '>'".into(),
extended: None,
},
MsgType::InvalidGenericIdentifier => ErrorMsg {
short: "generic parameters must be named identifiers".into(),
extended: None,
},
MsgType::InvalidUnwrapSyntax => ErrorMsg {
short: "invalid unwrap syntax".into(),
extended: None,
},
MsgType::InvalidGroupToChoiceEnumSyntax => ErrorMsg {
short: "invalid group to choice enumeration syntax".into(),
extended: None,
},
MsgType::InvalidTagSyntax => ErrorMsg {
short: "invalid tag syntax".into(),
extended: None,
},
MsgType::MissingGroupEntryMemberKey => ErrorMsg {
short: "missing group entry member key".into(),
extended: None,
},
MsgType::MissingGroupEntry => ErrorMsg {
short: "missing group entry".into(),
extended: None,
},
MsgType::InvalidGroupEntrySyntax => ErrorMsg {
short: "invalid group entry syntax".into(),
extended: None,
},
MsgType::MissingClosingDelimiter => ErrorMsg {
short: "missing closing delimiter".into(),
extended: None,
},
MsgType::MissingClosingParend => ErrorMsg {
short: "missing closing parend ')'".into(),
extended: None,
},
MsgType::InvalidMemberKeyArrowMapSyntax => ErrorMsg {
short: "invalid memberkey. missing '=>'".into(),
extended: None,
},
MsgType::InvalidMemberKeySyntax => ErrorMsg {
short: "invalid memberkey. missing '=>' or ':'".into(),
extended: None,
},
MsgType::InvalidOccurrenceSyntax => ErrorMsg {
short: "invalid occurrence indicator syntax".into(),
extended: None,
},
MsgType::UnableToAdvanceToken => ErrorMsg {
short: "unable to advance to the next token".into(),
extended: None,
},
MsgType::InvalidControlOperator => ErrorMsg {
short: "invalid control operator".into(),
extended: None,
},
MsgType::InvalidCharacter => ErrorMsg {
short: "invalid character".into(),
extended: None,
},
MsgType::InvalidEscapeCharacter => ErrorMsg {
short: "invalid escape character".into(),
extended: None,
},
MsgType::InvalidTextStringLiteralCharacter => ErrorMsg {
short: "invalid character in text string literal. expected closing \"".into(),
extended: None,
},
MsgType::EmptyTextStringLiteral => ErrorMsg {
short: "empty text string literal".into(),
extended: None,
},
MsgType::InvalidByteStringLiteralCharacter => ErrorMsg {
short: "invalid character in byte string literal. expected closing '".into(),
extended: None,
},
MsgType::EmptyByteStringLiteral => ErrorMsg {
short: "empty byte string literal".into(),
extended: None,
},
MsgType::NoRulesDefined => ErrorMsg {
short: "you must have at least one rule defined".into(),
extended: None,
},
MsgType::IncompleteRuleEntry => ErrorMsg {
short: "missing rule entry after assignment".into(),
extended: None,
},
MsgType::TypeSocketNamesMustBeTypeAugmentations => ErrorMsg {
short: "all plugs for type socket names must be augmentations using '/=' (alternatively change the definition to be a group socket)".into(),
extended: None,
},
MsgType::GroupSocketNamesMustBeGroupAugmentations => ErrorMsg {
short: "all plugs for group socket names must be augmentations using '//=' (alternatively change the definition to be a type socket)".into(),
extended: None,
},
MsgType::InvalidHexFloat => ErrorMsg {
short: "invalid hexfloat".into(),
extended: None,
},
MsgType::InvalidExponent => ErrorMsg {
short: "invalid exponent".into(),
extended: None,
}
}
}
}
|
/// Solver errors.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum SolverError
{
/// Found an unbounded certificate.
Unbounded,
/// Found an infeasibile certificate.
Infeasible,
/// Exceed max iterations.
ExcessIter,
/// Invalid [`crate::solver::Operator`].
InvalidOp,
/// Shortage of work slice length.
WorkShortage,
/// Failure caused by [`crate::solver::Cone`].
ConeFailure,
}
impl core::fmt::Display for SolverError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{}", match &self {
SolverError::Unbounded => "Unbounded: found an unbounded certificate",
SolverError::Infeasible => "Infeasible: found an infeasibile certificate",
SolverError::ExcessIter => "ExcessIter: exceed max iterations",
SolverError::InvalidOp => "InvalidOp: invalid Operator",
SolverError::WorkShortage => "WorkShortage: shortage of work slice length",
SolverError::ConeFailure => "ConeFailure: failure caused by Cone",
})
}
}
//
#[cfg(feature = "std")]
extern crate std;
#[cfg(feature = "std")]
impl std::error::Error for SolverError {}
|
use {
http::{
header::{
CONNECTION, //
CONTENT_LENGTH,
HOST,
SEC_WEBSOCKET_ACCEPT,
SEC_WEBSOCKET_KEY,
SEC_WEBSOCKET_VERSION,
TRANSFER_ENCODING,
UPGRADE,
},
Request, StatusCode,
},
tsukuyomi::{
endpoint,
test::{self, loc, TestServer},
App,
},
tsukuyomi_tungstenite::Ws,
};
#[test]
fn test_version_sync() {
version_sync::assert_html_root_url_updated!("src/lib.rs");
}
#[test]
fn test_handshake() -> test::Result {
let app = App::build(|mut s| {
s.at("/ws")?
.get()
.extract(tsukuyomi_tungstenite::ws())
.to(endpoint::call(|ws: Ws| {
ws.finish(|_| Ok::<(), std::io::Error>(()))
}))
})?;
let mut server = TestServer::new(app)?;
let mut client = server.connect();
client
.request(
Request::get("/ws")
.header(HOST, "localhost:4000")
.header(CONNECTION, "upgrade")
.header(UPGRADE, "websocket")
.header(SEC_WEBSOCKET_VERSION, "13")
.header(SEC_WEBSOCKET_KEY, "dGhlIHNhbXBsZSBub25jZQ==")
.body("")?,
)
.assert(loc!(), StatusCode::SWITCHING_PROTOCOLS)?
.assert(loc!(), test::header::not_exists(CONTENT_LENGTH))?
.assert(loc!(), test::header::not_exists(TRANSFER_ENCODING))?
.assert(loc!(), test::header::eq(CONNECTION, "upgrade"))?
.assert(loc!(), test::header::eq(UPGRADE, "websocket"))?
.assert(
loc!(),
test::header::eq(SEC_WEBSOCKET_ACCEPT, "s3pPLMBiTxaQ9kYGzzhZRbK+xOo="),
)?;
Ok(())
}
// TODO: add check whether the task to handle upgraded connection is spawned
|
/*
* A sample API conforming to the draft standard OGC API - Features - Part 1: Core
*
* This is a sample OpenAPI definition that conforms to the conformance classes \"Core\", \"GeoJSON\", \"HTML\" and \"OpenAPI 3.0\" of the draft standard \"OGC API - Features - Part 1: Core\". This example is a generic OGC API Features definition that uses path parameters to describe all feature collections and all features. The generic OpenAPI definition does not provide any details on the collections or the feature content. This information is only available from accessing the feature collection resources. There is [another example](ogcapi-features-1-example2.yaml) that specifies each collection explicitly.
*
* The version of the OpenAPI document: 1.0.0
* Contact: info@example.org
* Generated by: https://openapi-generator.tech
*/
use std::rc::Rc;
use std::borrow::Borrow;
#[allow(unused_imports)]
use std::option::Option;
use hyper;
use serde_json;
use futures::Future;
use super::{Error, configuration};
use super::request as __internal_request;
pub struct DataApiClient<C: hyper::client::Connect> {
configuration: Rc<configuration::Configuration<C>>,
}
impl<C: hyper::client::Connect> DataApiClient<C> {
pub fn new(configuration: Rc<configuration::Configuration<C>>) -> DataApiClient<C> {
DataApiClient {
configuration,
}
}
}
pub trait DataApi {
fn get_feature(&self, collection_id: &str, feature_id: &str) -> Box<dyn Future<Item = crate::models::FeatureGeoJson, Error = Error<serde_json::Value>>>;
fn get_features(&self, collection_id: &str, limit: Option<i32>, bbox: Option<Vec<f32>>, datetime: Option<&str>) -> Box<dyn Future<Item = crate::models::FeatureCollectionGeoJson, Error = Error<serde_json::Value>>>;
}
impl<C: hyper::client::Connect>DataApi for DataApiClient<C> {
fn get_feature(&self, collection_id: &str, feature_id: &str) -> Box<dyn Future<Item = crate::models::FeatureGeoJson, Error = Error<serde_json::Value>>> {
let mut req = __internal_request::Request::new(hyper::Method::Get, "/collections/{collectionId}/items/{featureId}".to_string())
;
req = req.with_path_param("collectionId".to_string(), collection_id.to_string());
req = req.with_path_param("featureId".to_string(), feature_id.to_string());
req.execute(self.configuration.borrow())
}
fn get_features(&self, collection_id: &str, limit: Option<i32>, bbox: Option<Vec<f32>>, datetime: Option<&str>) -> Box<dyn Future<Item = crate::models::FeatureCollectionGeoJson, Error = Error<serde_json::Value>>> {
let mut req = __internal_request::Request::new(hyper::Method::Get, "/collections/{collectionId}/items".to_string())
;
if let Some(ref s) = limit {
req = req.with_query_param("limit".to_string(), s.to_string());
}
if let Some(ref s) = bbox {
req = req.with_query_param("bbox".to_string(), s.join(",").to_string());
}
if let Some(ref s) = datetime {
req = req.with_query_param("datetime".to_string(), s.to_string());
}
req = req.with_path_param("collectionId".to_string(), collection_id.to_string());
req.execute(self.configuration.borrow())
}
}
|
use crate::draw;
use glam::Vec2;
#[derive(serde::Serialize, serde::Deserialize, Clone, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Config {
pub size: f32,
pub border_thickness: f32,
pub border_color: [u8; 4],
tiles: fxhash::FxHashMap<(i32, i32), ()>,
pub art_handle: draw::ArtHandle,
#[cfg(feature = "confui")]
#[serde(skip)]
pub dirty: bool,
#[cfg(feature = "confui")]
#[serde(skip)]
mouse_hot: bool,
// #[cfg(feature = "confui")]
// #[serde(skip)]
// selected_tiles: fxhash::FxHashSet<(i32, i32)>,
}
#[cfg(feature = "confui")]
pub fn dev_ui(
super::Game {
config: super::Config { tile, draw, .. },
player,
phys,
..
}: &mut super::Game,
ui: &mut egui::Ui,
) -> Option<()> {
use macroquad::*;
let start = tile.clone();
ui.label("tile size");
ui.add(egui::DragValue::f32(&mut tile.size).speed(0.001));
ui.label("border thickness");
ui.add(egui::DragValue::f32(&mut tile.border_thickness).speed(0.0001));
tile.dirty = *tile != start;
// draw debug hexagon
let index = {
let player_pos = {
let p = phys
.collision_object(player.phys_handle)?
.position()
.translation
.vector;
Vec2::new(p.x, p.y)
};
let size = tile.size + tile.border_thickness;
let offset = Vec2::new(0.1307 * size, size / -2.0);
let index = translation_to_index(size, player_pos + draw.mouse_world() - offset);
let p = index_to_translation(size, index) + offset;
set_camera(draw.camera({
let mut i = phys
.collision_object(player.phys_handle)?
.position()
.inverse();
i.translation.vector.y += draw.camera_move;
i
}));
draw_hexagon(p.x(), p.y(), size, 0.01, true, RED, Color([0, 0, 0, 0]));
let (x, y) = index;
(x - 1, y)
};
if !ui.ctx().wants_mouse_input() && is_mouse_button_down(MouseButton::Left) {
if !tile.mouse_hot {
if tile.tiles.contains_key(&index) {
tile.tiles.remove(&index);
} else {
tile.tiles.insert(index, ());
}
tile.dirty = true;
}
tile.mouse_hot = true;
} else {
tile.mouse_hot = false
}
Some(())
}
#[derive(Debug, Clone)]
pub struct Tile {
pub translation: Vec2,
pub spritesheet_index: usize,
}
pub struct Map {
pub tiles: Vec<Tile>,
}
/// square root of three
fn translation_to_index(tile_size: f32, t: Vec2) -> (i32, i32) {
fn cube_round(x: f32, y: f32, z: f32) -> (f32, f32, f32) {
let (mut rx, mut ry, mut rz) = (x.round(), y.round(), z.round());
let (x_diff, y_diff, z_diff) = ((rx - x).abs(), (ry - y).abs(), (rz - z).abs());
if x_diff > y_diff && x_diff > z_diff {
rx = -ry - rz;
} else if y_diff > z_diff {
ry = -rx - rz;
} else {
rz = -rx - ry;
}
(rx, ry, rz)
}
let q = (3.0_f32.sqrt() / 3.0 * t.x() - 1.0 / 3.0 * t.y()) / tile_size;
let r = (2.0 / 3.0 * t.y()) / tile_size;
let (y, x, _) = cube_round(q, r, -q - r);
(x as i32, y as i32)
}
fn index_to_translation(tile_size: f32, (ri, qi): (i32, i32)) -> Vec2 {
let (r, q) = (ri as f32, qi as f32);
Vec2::new(3.0_f32.sqrt() * q + 3.0_f32.sqrt() / 2.0 * r, 3.0 / 2.0 * r) * tile_size
}
#[test]
fn tile_index_to_translation_and_back() {
println!("starting ..");
for x in -3..=3 {
for y in -3..=3 {
assert_eq!(
(x, y),
translation_to_index(1.0, index_to_translation(1.0, (x, y)))
);
println!("{} {} all good", x, y);
}
}
}
impl Map {
pub fn new(super::Config { draw, tile, .. }: &super::Config) -> Self {
let tile_count = draw.get(tile.art_handle).spritesheet.unwrap().total.get();
Self {
tiles: tile
.tiles
.iter()
.map(|(&(x, y), &())| Tile {
spritesheet_index: macroquad::rand::gen_range(0, tile_count),
translation: index_to_translation(tile.size + tile.border_thickness, (x, y)),
})
.collect(),
}
}
}
|
use std::collections::HashMap;
use serde::{Serialize, Deserialize};
use super::{Asset, AssetExt, AssetResult, category};
use crate::impl_ron_asset;
// -------------------------------------------------------------------------------------------------
#[derive(Default, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Dimensions(HashMap<String, i32>);
impl_ron_asset!(Dimensions, Resource);
#[derive(Deserialize)]
#[serde(from = "(String, String, String)")]
pub struct AssetItem {
pub name: String,
pub asset_type: String,
pub asset_path: String,
}
impl From<(String, String, String)> for AssetItem {
fn from((name, asset_type, asset_path): (String, String, String)) -> Self {
AssetItem { name, asset_type, asset_path }
}
}
#[derive(Default, Deserialize)]
pub struct AssetList {
#[serde(skip)]
name: String,
loader: String,
assets: Vec<AssetItem>,
}
impl Asset for AssetList {
type Category = category::Resource;
fn read(asset_path: &str) -> AssetResult<Self> {
let mut list: AssetList = Self::read_ron(asset_path)?;
list.name = asset_path.to_owned();
Ok(list)
}
}
impl AssetList {
pub fn name(&self) -> &str { &self.name }
pub fn loader(&self) -> &str { &self.loader }
pub fn iter(&self) -> std::slice::Iter<AssetItem> { self.assets.iter() }
}
impl IntoIterator for AssetList {
type Item = AssetItem;
type IntoIter = std::vec::IntoIter<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
self.assets.into_iter()
}
}
|
#![macro_use]
//! LVal: The basic object type
use std::mem;
use std::fmt;
use std::borrow::ToOwned;
use lenv::LEnv;
use parser::ast::{Expr, ExprNode};
use util::{print_error, stringify_vec};
/// Return an error
macro_rules! err(
($msg:expr) => (
return LVal::err($msg.to_string())
);
($msg:expr, $( $args:expr ),* ) => (
return LVal::err(format!($msg, $($args),* ))
);
);
macro_rules! lval_is(
($el:expr, number) => ( if let LVal::Num(..) = $el { true } else { false } );
($el:expr, qexpr) => ( if let LVal::QExpr(..) = $el { true } else { false } );
($el:expr, sexpr) => ( if let LVal::SExpr(..) = $el { true } else { false } );
($el:expr, string) => ( if let LVal::Str(..) = $el { true } else { false } );
);
macro_rules! lval_type_name(
(number) => ("a number");
(err) => ("an error");
(string) => ("a string");
(sym) => ("a symbol");
(function) => ("a lambda");
(builtin) => ("a builtin function");
(sexpr) => ("a s-expression");
(qexpr) => ("a q-expression");
);
/// A builtin function
///
/// Used to implement PartialEq for the function pointer
pub struct LBuiltin(pub fn(&mut LEnv, Vec<LVal>) -> LVal);
impl Clone for LBuiltin {
fn clone(&self) -> LBuiltin {
match *self {
LBuiltin(ptr) => LBuiltin(ptr),
}
}
}
impl PartialEq for LBuiltin {
fn eq(&self, other: &LBuiltin) -> bool {
unsafe {
let ptr_self: *const () = mem::transmute(self);
let ptr_other: *const () = mem::transmute(other);
ptr_self == ptr_other
}
}
}
/// A basic object
#[derive(PartialEq, Clone)]
pub enum LVal {
Num(f64),
Err(String),
Sym(String), // TODO: Use SharedString?
Str(String),
Function {
env: LEnv,
formals: Vec<LVal>, // List of formal argument symbols
body: Vec<LVal> // Actually a S-Expr
},
Builtin(LBuiltin),
SExpr(Vec<LVal>),
QExpr(Vec<LVal>)
}
impl LVal {
// --- Constructors ---------------------------------------------------------
/// Create a new number lval
pub fn num(value: f64) -> LVal {
LVal::Num(value)
}
/// Create a new error lval
pub fn err(msg: String) -> LVal {
LVal::Err(msg)
}
/// Create a new string lval
pub fn str(s: &str) -> LVal {
LVal::Str(s.to_owned())
}
/// Create a new symbol lval
pub fn sym(symbol: &str) -> LVal {
LVal::Sym(symbol.to_owned())
}
// Create a new lambda lval
pub fn lambda(formals: LVal, body: LVal) -> LVal {
LVal::Function {
env: LEnv::new(),
formals: formals.into_values(),
body: body.into_values()
}
}
/// Create a new function lval
pub fn func(f: fn(&mut LEnv, Vec<LVal>) -> LVal) -> LVal {
LVal::Builtin(LBuiltin(f))
}
/// Create a new sepxr lval
pub fn sexpr() -> LVal {
LVal::SExpr(vec![])
}
/// Create a new sepxr lval
pub fn qexpr() -> LVal {
LVal::QExpr(vec![])
}
/// Construct a lval from a given AST
pub fn from_ast(ast: ExprNode) -> LVal {
match ast.value {
Expr::Number(i) => LVal::num(i as f64),
Expr::String(s) => LVal::str(&s),
Expr::Symbol(s) => LVal::sym(&s),
Expr::SExpr(exprs) => {
let mut sexpr = LVal::sexpr();
for child in exprs {
sexpr.append(LVal::from_ast(child));
}
sexpr
},
Expr::QExpr(exprs) => {
let mut qexpr = LVal::qexpr();
for child in exprs {
qexpr.append(LVal::from_ast(child));
}
qexpr
}
}
}
// --- Public methods: Conversions ------------------------------------------
pub fn as_values(&self) -> &Vec<LVal> {
if let &LVal::SExpr(ref values) = self {
values
} else if let &LVal::QExpr(ref values) = self {
values
} else {
panic!("LVal::as_values(self={})", self);
}
}
pub fn into_values(self) -> Vec<LVal> {
if let LVal::SExpr(values) = self {
values
} else if let LVal::QExpr(values) = self {
values
} else {
panic!("LVal::into_values(self={})", self);
}
}
pub fn as_num(&self) -> &f64 {
if let &LVal::Num(ref float) = self {
return float
} else {
panic!("LVal::as_num(self={})", self)
}
}
pub fn into_num(self) -> f64 {
if let LVal::Num(float) = self {
//let Float(ref mut i) = float;
//return i
return float
} else {
panic!("LVal::into_num(self={})", self)
}
}
pub fn into_str(self) -> String {
if let LVal::Str(s) = self {
return s
} else {
panic!("LVal::into_str(self={})", self)
}
}
pub fn as_sym(&self) -> &String {
if let &LVal::Sym(ref value) = self {
return value
} else {
panic!("LVal::as_sym(self={})", self)
}
}
// --- Public methods: Other functions --------------------------------------
/// Delete a lval
pub fn del(self) {}
/// Append a lval to a sexpr
///
/// Panics when `self` is not a SExpr
pub fn append(&mut self, expr: LVal) {
if let LVal::SExpr(ref mut values) = *self {
values.push(expr);
} else if let LVal::QExpr(ref mut values) = *self {
values.push(expr);
} else {
panic!("LVal::append(self={}, expr={})", self, expr);
}
}
/// Append all values from a sexpr to a sexpr
///
/// Panics when `self` or `container` is not a SExpr
pub fn extend(&mut self, container: LVal) {
if let LVal::SExpr(ref mut values) = *self {
values.extend(container.into_values().into_iter());
} else if let LVal::QExpr(ref mut values) = *self {
values.extend(container.into_values().into_iter());
} else {
panic!("LVal::extend(self={}, expr={})", self, container);
}
}
pub fn type_name(&self) -> &'static str {
match *self {
LVal::Num(..) => "a number",
LVal::Err(..) => "an error",
LVal::Sym(..) => "a symbol",
LVal::Str(..) => "a string",
LVal::Function{..} => "a lambda",
LVal::Builtin(..) => "a builtin function",
LVal::SExpr(..) => "a s-expression",
LVal::QExpr(..) => "a q-expression"
}
}
pub fn to_string(&self, env: &LEnv) -> String {
match *self {
LVal::Sym(ref name) => {
match env.get(&name) {
LVal::Err(..) => name.clone(),
value => value.to_string(env)
}
},
LVal::SExpr(ref values) => {
format!(
"({})",
values.iter()
.map(|v| v.to_string(env))
.collect::<Vec<_>>()
.connect(" ")
)
}
LVal::Function { ref env, ref formals, ref body } => {
format!(
"\\ {{{}}} {{{}}}",
stringify_vec(formals),
body.iter()
.map(|v| v.to_string(env))
.collect::<Vec<_>>()
.connect(" ")
)
},
LVal::Builtin(..) => match env.look_up(self) {
Some(name) => format!("<builtin: '{}'>", name),
None => format!("{}", self)
},
_ => { format!("{}", self) }
}
}
pub fn print(&self, env: &LEnv) {
if let LVal::Err(ref msg) = *self {
print_error(&msg);
} else {
print!("{}", self.to_string(env));
}
}
pub fn println(&self, env: &LEnv) {
self.print(env);
println!("");
}
}
// Used for debugging and when the environment is not available
impl fmt::Display for LVal {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
LVal::Num(i) => write!(f, "{}", i),
LVal::Err(ref msg) => write!(f, "{}", msg),
LVal::Str(ref string) => write!(f, "\"{}\"", string.escape_default()),
LVal::Sym(ref symbol) => write!(f, "{}", symbol),
LVal::Function{ env: _, ref formals, ref body } => {
write!(f, "\\ {{{}}} {{{}}}", stringify_vec(formals),
stringify_vec(body))
},
LVal::Builtin(..) => write!(f, "<function>"),
LVal::SExpr(ref values) => {
write!(f, "({})", stringify_vec(values))
},
LVal::QExpr(ref values) => {
write!(f, "{{{}}}", stringify_vec(values))
}
}
}
}
impl fmt::Debug for LVal {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)
}
} |
use rtm::Reminder;
/// Creates a reminder.
///
/// Wraps https://api.slack.com/methods/reminders.add
#[derive(Clone, Debug, Serialize, new)]
pub struct AddRequest<'a> {
/// The content of the reminder
pub text: &'a str,
/// When this reminder should happen: the Unix timestamp (up to five years from now), the number of seconds until the reminder (if within 24 hours), or a natural language description (Ex. "in 15 minutes," or "every Thursday")
pub time: u32,
/// The user who will receive the reminder. If no user is specified, the reminder will go to user who created it.
#[new(default)]
pub user: Option<::UserId>,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AddResponse {
ok: bool,
pub reminder: Option<Reminder>,
}
/// Marks a reminder as complete.
///
/// Wraps https://api.slack.com/methods/reminders.complete
#[derive(Clone, Debug, Serialize, new)]
pub struct CompleteRequest {
/// The ID of the reminder to be marked as complete
pub reminder: ::ReminderId,
}
/// Deletes a reminder.
///
/// Wraps https://api.slack.com/methods/reminders.delete
#[derive(Clone, Debug, Serialize, new)]
pub struct DeleteRequest {
/// The ID of the reminder
pub reminder: ::ReminderId,
}
/// Gets information about a reminder.
///
/// Wraps https://api.slack.com/methods/reminders.info
#[derive(Clone, Debug, Serialize, new)]
pub struct InfoRequest {
/// The ID of the reminder
pub reminder: ::ReminderId,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct InfoResponse {
ok: bool,
pub reminder: Option<Reminder>,
}
/// Lists all reminders created by or for a given user.
///
/// Wraps https://api.slack.com/methods/reminders.list
// TODO: Docs say "created by or for a given user", but also do not mention how to indicate said
// user
#[derive(Clone, Debug, Deserialize)]
pub struct ListResponse {
ok: bool,
pub reminders: Option<Vec<Reminder>>,
}
|
#[macro_use]
extern crate clap;
extern crate env_logger;
#[macro_use]
extern crate log;
extern crate rustpython_parser;
extern crate rustpython_vm;
extern crate rustyline;
use clap::{App, Arg};
use rustpython_parser::error::ParseError;
use rustpython_vm::{
compile, error::CompileError, error::CompileErrorType, frame::Scope, import, obj::objstr,
print_exception, pyobject::PyResult, util, VirtualMachine,
};
use rustyline::{error::ReadlineError, Editor};
use std::path::{Path, PathBuf};
fn main() {
env_logger::init();
let matches = App::new("RustPython")
.version(crate_version!())
.author(crate_authors!())
.about("Rust implementation of the Python language")
.arg(Arg::with_name("script").required(false).index(1))
.arg(
Arg::with_name("v")
.short("v")
.multiple(true)
.help("Give the verbosity"),
)
.arg(
Arg::with_name("c")
.short("c")
.takes_value(true)
.help("run the given string as a program"),
)
.arg(
Arg::with_name("m")
.short("m")
.takes_value(true)
.help("run library module as script"),
)
.arg(Arg::from_usage("[pyargs] 'args for python'").multiple(true))
.get_matches();
// Construct vm:
let vm = VirtualMachine::new();
// Figure out if a -c option was given:
let result = if let Some(command) = matches.value_of("c") {
run_command(&vm, command.to_string())
} else if let Some(module) = matches.value_of("m") {
run_module(&vm, module)
} else {
// Figure out if a script was passed:
match matches.value_of("script") {
None => run_shell(&vm),
Some(filename) => run_script(&vm, filename),
}
};
// See if any exception leaked out:
handle_exception(&vm, result);
}
fn _run_string(vm: &VirtualMachine, source: &str, source_path: String) -> PyResult {
let code_obj = compile::compile(vm, source, &compile::Mode::Exec, source_path)
.map_err(|err| vm.new_syntax_error(&err))?;
// trace!("Code object: {:?}", code_obj.borrow());
let vars = vm.ctx.new_scope(); // Keep track of local variables
vm.run_code_obj(code_obj, vars)
}
fn handle_exception(vm: &VirtualMachine, result: PyResult) {
if let Err(err) = result {
print_exception(vm, &err);
std::process::exit(1);
}
}
fn run_command(vm: &VirtualMachine, mut source: String) -> PyResult {
debug!("Running command {}", source);
// This works around https://github.com/RustPython/RustPython/issues/17
source.push('\n');
_run_string(vm, &source, "<stdin>".to_string())
}
fn run_module(vm: &VirtualMachine, module: &str) -> PyResult {
debug!("Running module {}", module);
let current_path = PathBuf::from(".");
import::import_module(vm, current_path, module)
}
fn run_script(vm: &VirtualMachine, script_file: &str) -> PyResult {
debug!("Running file {}", script_file);
// Parse an ast from it:
let file_path = Path::new(script_file);
match util::read_file(file_path) {
Ok(source) => _run_string(vm, &source, file_path.to_str().unwrap().to_string()),
Err(err) => {
error!("Failed reading file: {:?}", err.kind());
std::process::exit(1);
}
}
}
fn shell_exec(vm: &VirtualMachine, source: &str, scope: Scope) -> Result<(), CompileError> {
match compile::compile(vm, source, &compile::Mode::Single, "<stdin>".to_string()) {
Ok(code) => {
if let Err(err) = vm.run_code_obj(code, scope) {
print_exception(vm, &err);
}
Ok(())
}
// Don't inject syntax errors for line continuation
Err(
err @ CompileError {
error: CompileErrorType::Parse(ParseError::EOF(_)),
..
},
) => Err(err),
Err(err) => {
let exc = vm.new_syntax_error(&err);
print_exception(vm, &exc);
Err(err)
}
}
}
#[cfg(not(unix))]
fn get_history_path() -> PathBuf {
PathBuf::from(".repl_history.txt")
}
#[cfg(unix)]
fn get_history_path() -> PathBuf {
//work around for windows dependent builds. The xdg crate is unix specific
//so access to the BaseDirectories struct breaks builds on python.
extern crate xdg;
let xdg_dirs = xdg::BaseDirectories::with_prefix("rustpython").unwrap();
xdg_dirs.place_cache_file("repl_history.txt").unwrap()
}
fn get_prompt(vm: &VirtualMachine, prompt_name: &str) -> String {
vm.get_attribute(vm.sys_module.clone(), prompt_name)
.ok()
.as_ref()
.map(objstr::get_value)
.unwrap_or_else(String::new)
}
fn run_shell(vm: &VirtualMachine) -> PyResult {
println!(
"Welcome to the magnificent Rust Python {} interpreter \u{1f631} \u{1f596}",
crate_version!()
);
let vars = vm.ctx.new_scope();
// Read a single line:
let mut input = String::new();
let mut repl = Editor::<()>::new();
// Retrieve a `history_path_str` dependent on the OS
let repl_history_path_str = &get_history_path();
if repl.load_history(repl_history_path_str).is_err() {
println!("No previous history.");
}
let mut continuing = false;
loop {
let prompt = if continuing {
get_prompt(vm, "ps2")
} else {
get_prompt(vm, "ps1")
};
match repl.readline(&prompt) {
Ok(line) => {
debug!("You entered {:?}", line);
input.push_str(&line);
input.push('\n');
repl.add_history_entry(line.trim_end());
if continuing {
if line.is_empty() {
continuing = false;
} else {
continue;
}
}
match shell_exec(vm, &input, vars.clone()) {
Err(CompileError {
error: CompileErrorType::Parse(ParseError::EOF(_)),
..
}) => {
continuing = true;
continue;
}
_ => {
input = String::new();
}
}
}
Err(ReadlineError::Interrupted) => {
// TODO: Raise a real KeyboardInterrupt exception
println!("^C");
continuing = false;
continue;
}
Err(ReadlineError::Eof) => {
break;
}
Err(err) => {
println!("Error: {:?}", err);
break;
}
};
}
repl.save_history(repl_history_path_str).unwrap();
Ok(vm.get_none())
}
|
/*
复原IP地址
给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。
示例:
输入: "25525511135"
输出: ["255.255.11.135", "255.255.111.35"]
*/
use crate::string::Solution;
impl Solution {
pub fn restore_ip_addresses(s: String) -> Vec<String> {
use std::cmp::min;
use std::cmp::max;
if s.len() < 4 || s.len() > 12 { return Vec::new(); }
let s = s.as_bytes();
let n = s.len();
let mut ans = Vec::new();
// [0..i) [i..j) [j..k) [k..n) each s.t. 0 <= x <= 255
for i in 1..=min(n - 3, 3) {
let (p0, rem) = s.split_at(i);
if p0.invalid() { break; }
for j in i + 1..=min(n - 2, i + 3) {
let (p1, rem) = rem.split_at(j - i);
if p1.invalid() { break; }
for k in max(j + 1, n - 3)..=min(n - 1, j + 3) { // k - j <= 3 && n - k <= 3
let (p2, p3) = rem.split_at(k - j);
if p2.invalid() { break; }
if p3.invalid() { continue; }
ans.push(format!("{}.{}.{}.{}", p0.to_string(), p1.to_string(), p2.to_string(), p3.to_string()));
}
}
}
ans
}
}
trait Ip {
fn to_string(&self) -> String;
fn invalid(&self) -> bool;
}
impl Ip for &[u8] {
#[inline]
fn to_string(&self) -> String {
String::from_utf8_lossy(self).into()
}
#[inline]
fn invalid(&self) -> bool { // check if not: 0 <= self <= 255 || self == 0*
if (self.len() >= 3 && self.to_string().as_str() > "255") || (self[0] == '0' as u8 && self.len() >= 2) {
true
} else {
false
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::ops::Deref;
#[test]
fn test() {
let cases = vec![
("25525511135", vec!["255.255.11.135", "255.255.111.35"]),
("111111111111", vec!["111.111.111.111"]),
("1111111111110", vec![]),
("111", vec![]),
("010010", vec!["0.10.0.10", "0.100.1.0"])
];
for (input, output) in cases {
assert_eq!(Solution::restore_ip_addresses(input.deref().into()), output);
}
}
}
|
use std::fmt::Debug;
use std::fmt::Display;
pub type ID = String;
pub type Element = String;
pub const MAX_ID_LENGTH: usize = 20; // TODO. Increase max length.
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
pub enum ListError {
ListIdEmptyError,
ListIdTooLongError(ID, usize, usize),
DuplicateListIdError(ID),
ListIdNotFoundError(ID),
ListIndexOutOfRangeError(ID, usize),
ListJsonConversionError(String),
ListDbError(String),
ListLockingError(String),
ListInternalError(String)
}
// Use this as shorthand where possible.
// TODO. How to derive Eq?
pub type ListResult<T> = Result<T, ListError>;
pub fn to_internal_error<E>(error: E) -> ListError
where E: ToString + Display {
ListError::ListInternalError(error.to_string())
}
pub fn to_db_error<E>(error: E) -> ListError
where E: ToString + Display {
ListError::ListDbError(error.to_string())
}
pub fn to_locking_error<E>(error: E) -> ListError
where E: ToString + Display { ListError::ListLockingError(error.to_string()) }
pub fn to_json_error<E>(error: E) -> ListError
where E: ToString + Display { ListError::ListJsonConversionError(error.to_string()) }
pub type BareList = Vec<Element>;
// Could not use unstable library function Vec.remove_item even with enabled feature.
// Vec first has the wrong type.
// Cannot use vector as both mutable and immutable!
pub fn vec_head_option<T>(vec: &Vec<T>) -> Option<T> where T: Clone {
match vec.is_empty() {
true => None,
false => Some(vec.to_vec().remove(0))
}
}
// Q: Why FnMut? What is mutated? And why mut f?
pub fn vec_map<T: Clone, U, F: FnMut(T) -> U>(vec: &Vec<T>, mut f: F) -> Vec<U> {
vec
.iter()
.map(|t| f((*t).clone()))
.collect()
}
|
use crossterm::{style::Color, Result};
use rc_game::{Game, GameState, Position, Renderable, RogueCrossGame, GAME_COLS, GAME_ROWS};
use specs::{prelude::*, Builder, World, WorldExt};
use specs_derive::*;
#[derive(Component)]
struct LeftMover {
pub min_col: i32,
pub max_col: i32,
pub min_row: i32,
pub max_row: i32,
}
impl Default for LeftMover {
fn default() -> Self {
Self {
min_col: 0,
max_col: GAME_COLS as i32,
min_row: 0,
max_row: GAME_ROWS as i32,
}
}
}
struct LeftWalker {}
impl<'a> System<'a> for LeftWalker {
type SystemData = (ReadStorage<'a, LeftMover>, WriteStorage<'a, Position>);
fn run(&mut self, (lefty, mut pos): Self::SystemData) {
for (lefty, pos) in (&lefty, &mut pos).join() {
pos.x -= 1;
if pos.x < 0 {
pos.x = lefty.max_col;
}
}
}
}
#[derive(Default)]
struct Ch02Game {}
impl Game for Ch02Game {
fn init(&self, _gs: &GameState, ecs: &mut World) -> Result<()> {
ecs.register::<LeftMover>();
for i in 0..10 {
ecs.create_entity()
.with(Position { x: i * 7, y: 10 })
.with(Renderable {
glyph: '☺',
fg: Color::Red,
bg: None,
})
.with(LeftMover::default())
.build();
}
Ok(())
}
fn update(&mut self, _: &GameState, ecs: &World) -> Result<()> {
let mut lw = LeftWalker {};
lw.run_now(ecs);
Ok(())
}
}
fn main() -> Result<()> {
let mut game: RogueCrossGame<Ch02Game> = Default::default();
game.start()
}
|
use svm_types::Template;
use crate::env::TemplateHash;
/// Computes Hash derived deterministically from raw `Template`.
pub trait TemplateHasher {
/// Given code as bytes, derives an Hash
fn hash(template: &Template) -> TemplateHash;
}
|
//pub mod ast;
use ghql::parse;
macro_rules! prompt {
() => {
print!("> ");
io::stdout().flush().expect("Could not flush stdout");
}
}
fn main() {
use std::io::{self, BufRead, Write};
println!();
println!("Available features (optional parameters in parentheses):");
println!();
println!(" commits(path==GLOB, path!=GLOB)");
println!(" changes(path==GLOB, path!=GLOB)");
println!(" additions(path==GLOB, path!=GLOB)");
println!(" deletions(path==GLOB, path!=GLOB)");
println!();
println!("Available operators used on features to create selectors:");
println!();
println!(" FEATURE == NUMBER, NUMBER == FEATURE");
println!(" FEATURE != NUMBER, NUMBER != FEATURE");
println!(" FEATURE > NUMBER, NUMBER > FEATURE");
println!(" FEATURE >= NUMBER, NUMBER >= FEATURE");
println!(" FEATURE < NUMBER, NUMBER < FEATURE");
println!(" FEATURE <= NUMBER, NUMBER <= FEATURE");
println!();
println!("Available connectives between feature selectors:");
println!();
println!(" and");
println!();
println!("Examples:");
println!();
println!(" commits >= 1000");
println!();
println!(" returns a list of projects which have at least 1000 commits");
println!();
println!(" deletions(\"README.md\")");
println!();
println!(" returns a list of projects which have at least one commit that deletes");
println!(" a file called \"README.md\" from he project's root directory");
println!();
println!(" commits(path==\"*.rs\") >= 1000 and commits(path==\"*.rs\") <= 10000");
println!();
println!(" returns a list of projects which have between 1000 and 10000 commits");
println!(" that touch a file whose name ends in \"rs\"");
println!();
prompt!();
let stdin = io::stdin();
for line in stdin.lock().lines() {
let query: &str = &line.unwrap();
println!("Parsing: {}", query);
println!("AST: {:?}", parse(query));
prompt!();
}
} |
extern crate argparse;
use argparse::{ArgumentParser, StoreTrue, Store};
mod decoder;
use decoder::*;
mod implementer;
use implementer::{*, rtype::*, itype::*, utype::*, stype::*, ujtype::*, sbtype::*};
mod assembler;
use assembler::*;
#[macro_use]
mod macro_definitions;
const REGFILE_SIZE: usize = 32;
const MEM_SIZE: usize = 1048576 * 4; // 32 address space in RV32I
const INSTRUCTION_ADDRESS_MISALIGNED_THRESHOLD: i32 = 4;
#[allow(dead_code)]
pub struct Extensions {
m: bool,
a: bool,
f: bool,
e: bool,
c: bool,
d: bool,
q: bool,
}
pub enum ExecutionError {
Extension(String),
InvalidInstruction(String),
InstructionAddressMisaligned,
Unimplemented(String),
UserTerminate
}
fn main() {
let mut imem: Vec<u8> = Vec::new();
let mut regfile: Vec<u32> = vec![0; REGFILE_SIZE];
let mut mem: Vec<u8> = vec![0; MEM_SIZE];
let mut src_filepath: String = "./risc-v/sources/test.S".into();
let mut extensions = Extensions{ a: false, m: false, e: false, f: false, d: false, q: false, c: false };
let mut use_hex = false;
{
let mut ap = ArgumentParser::new();
parse_extensions!([ap;extensions] a, m, e, f, d, q, c);
ap.refer(&mut src_filepath)
.add_option(&["--file"], Store, "File to emulate");
ap.refer(&mut use_hex)
.add_option(&["--hex", "-h"], StoreTrue, "Set if the source file is assembled hex");
ap.parse_args_or_exit();
}
if use_hex {
if let Err(e) = load_into_imem(&src_filepath, &mut imem) {
println!("Error loading into IMEM: {}", e);
}
} else {
assemble_and_load(&src_filepath, &mut mem, &mut imem);
}
let mut pc: u32 = 0;
loop {
let bytes = match fetch_inst(pc, &imem) {
Ok(b) => b,
Err(e) => {
println!("{}", e);
break;
}
};
match get_opcode(bytes) {
0x3 | 0x13 | 0x1B | 0x67 | 0x73 => {
process! {
handle_i_type(&mut regfile, &mut mem, bytes, &mut pc, &extensions)
}
}
0x17 | 0x37 => {
process! {
handle_u_type(&mut regfile, bytes, &mut pc, &extensions)
}
}
0x23 => {
process! {
handle_s_type(&mut regfile, &mut mem, bytes, &mut pc, &extensions)
}
}
0x33 | 0x3B => {
process! {
handle_r_type(&mut regfile, bytes, &mut pc, &extensions)
}
}
0x63 => {
process! {
handle_sb_type(&mut regfile, bytes, &mut pc, &extensions)
}
}
0x6F => {
process! {
handle_uj_type(&mut regfile, bytes, &mut pc, &extensions)
}
}
0xFF => {
process! {
handle_fence(&mut regfile, bytes, &mut pc)
}
}
_ => {
println!("UNRECOGNIZED OPCODE: {}", get_opcode(bytes));
println!("Instruction was: {:?}", bytes);
break;
}
}
regfile[0] = 0;
print_registers(&mut regfile);
std::thread::sleep(std::time::Duration::from_millis(1000));
}
}
// Helper functions
fn print_registers(regfile: &mut [u32]) {
for (i, r) in regfile.into_iter().enumerate() {
if *r != 0 {
println!("x{}: 0x{:08x}", i, *r as i32);
}
}
}
fn fetch_inst(pc: u32, imem: &[u8]) -> Result<&[u8], String> {
if (pc as usize + 4) > imem.len() { return Err("End of imem".into()); }
match get_bits(imem[pc as usize]) {
32 => {
let bytes = &imem[(pc as usize)..(pc as usize) + 4];
if encode_hex(bytes) == "00000000".to_string() || encode_hex(bytes) == "11111111".to_string() {
Err(format!("The instruction 0x{} is illegal", encode_hex(bytes)))
}
else { Ok(bytes) }
}
_ => {
Err("Only 32 bit instructions are supported".into())
}
}
}
|
#[doc = "Register `PLLSAI1CFGR` reader"]
pub type R = crate::R<PLLSAI1CFGR_SPEC>;
#[doc = "Register `PLLSAI1CFGR` writer"]
pub type W = crate::W<PLLSAI1CFGR_SPEC>;
#[doc = "Field `PLLSAI1M` reader - Division factor for PLLSAI1 input clock"]
pub type PLLSAI1M_R = crate::FieldReader<PLLSAI1M_A>;
#[doc = "Division factor for PLLSAI1 input clock\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum PLLSAI1M_A {
#[doc = "0: PLLSAI1M = 1"]
Div1 = 0,
#[doc = "1: PLLSAI1M = 2"]
Div2 = 1,
#[doc = "2: PLLSAI1M = 3"]
Div3 = 2,
#[doc = "3: PLLSAI1M = 4"]
Div4 = 3,
#[doc = "4: PLLSAI1M = 5"]
Div5 = 4,
#[doc = "5: PLLSAI1M = 6"]
Div6 = 5,
#[doc = "6: PLLSAI1M = 7"]
Div7 = 6,
#[doc = "7: PLLSAI1M = 8"]
Div8 = 7,
#[doc = "8: PLLSAI1M = 9"]
Div9 = 8,
#[doc = "9: PLLSAI1M = 11"]
Div10 = 9,
#[doc = "10: PLLSAI1M = 12"]
Div11 = 10,
#[doc = "11: PLLSAI1M = 13"]
Div12 = 11,
#[doc = "12: PLLSAI1M = 13"]
Div13 = 12,
#[doc = "13: PLLSAI1M = 14"]
Div14 = 13,
#[doc = "14: PLLSAI1M = 15"]
Div15 = 14,
#[doc = "15: PLLSAI1M = 16"]
Div16 = 15,
}
impl From<PLLSAI1M_A> for u8 {
#[inline(always)]
fn from(variant: PLLSAI1M_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for PLLSAI1M_A {
type Ux = u8;
}
impl PLLSAI1M_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> PLLSAI1M_A {
match self.bits {
0 => PLLSAI1M_A::Div1,
1 => PLLSAI1M_A::Div2,
2 => PLLSAI1M_A::Div3,
3 => PLLSAI1M_A::Div4,
4 => PLLSAI1M_A::Div5,
5 => PLLSAI1M_A::Div6,
6 => PLLSAI1M_A::Div7,
7 => PLLSAI1M_A::Div8,
8 => PLLSAI1M_A::Div9,
9 => PLLSAI1M_A::Div10,
10 => PLLSAI1M_A::Div11,
11 => PLLSAI1M_A::Div12,
12 => PLLSAI1M_A::Div13,
13 => PLLSAI1M_A::Div14,
14 => PLLSAI1M_A::Div15,
15 => PLLSAI1M_A::Div16,
_ => unreachable!(),
}
}
#[doc = "PLLSAI1M = 1"]
#[inline(always)]
pub fn is_div1(&self) -> bool {
*self == PLLSAI1M_A::Div1
}
#[doc = "PLLSAI1M = 2"]
#[inline(always)]
pub fn is_div2(&self) -> bool {
*self == PLLSAI1M_A::Div2
}
#[doc = "PLLSAI1M = 3"]
#[inline(always)]
pub fn is_div3(&self) -> bool {
*self == PLLSAI1M_A::Div3
}
#[doc = "PLLSAI1M = 4"]
#[inline(always)]
pub fn is_div4(&self) -> bool {
*self == PLLSAI1M_A::Div4
}
#[doc = "PLLSAI1M = 5"]
#[inline(always)]
pub fn is_div5(&self) -> bool {
*self == PLLSAI1M_A::Div5
}
#[doc = "PLLSAI1M = 6"]
#[inline(always)]
pub fn is_div6(&self) -> bool {
*self == PLLSAI1M_A::Div6
}
#[doc = "PLLSAI1M = 7"]
#[inline(always)]
pub fn is_div7(&self) -> bool {
*self == PLLSAI1M_A::Div7
}
#[doc = "PLLSAI1M = 8"]
#[inline(always)]
pub fn is_div8(&self) -> bool {
*self == PLLSAI1M_A::Div8
}
#[doc = "PLLSAI1M = 9"]
#[inline(always)]
pub fn is_div9(&self) -> bool {
*self == PLLSAI1M_A::Div9
}
#[doc = "PLLSAI1M = 11"]
#[inline(always)]
pub fn is_div10(&self) -> bool {
*self == PLLSAI1M_A::Div10
}
#[doc = "PLLSAI1M = 12"]
#[inline(always)]
pub fn is_div11(&self) -> bool {
*self == PLLSAI1M_A::Div11
}
#[doc = "PLLSAI1M = 13"]
#[inline(always)]
pub fn is_div12(&self) -> bool {
*self == PLLSAI1M_A::Div12
}
#[doc = "PLLSAI1M = 13"]
#[inline(always)]
pub fn is_div13(&self) -> bool {
*self == PLLSAI1M_A::Div13
}
#[doc = "PLLSAI1M = 14"]
#[inline(always)]
pub fn is_div14(&self) -> bool {
*self == PLLSAI1M_A::Div14
}
#[doc = "PLLSAI1M = 15"]
#[inline(always)]
pub fn is_div15(&self) -> bool {
*self == PLLSAI1M_A::Div15
}
#[doc = "PLLSAI1M = 16"]
#[inline(always)]
pub fn is_div16(&self) -> bool {
*self == PLLSAI1M_A::Div16
}
}
#[doc = "Field `PLLSAI1M` writer - Division factor for PLLSAI1 input clock"]
pub type PLLSAI1M_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 4, O, PLLSAI1M_A>;
impl<'a, REG, const O: u8> PLLSAI1M_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "PLLSAI1M = 1"]
#[inline(always)]
pub fn div1(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1M_A::Div1)
}
#[doc = "PLLSAI1M = 2"]
#[inline(always)]
pub fn div2(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1M_A::Div2)
}
#[doc = "PLLSAI1M = 3"]
#[inline(always)]
pub fn div3(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1M_A::Div3)
}
#[doc = "PLLSAI1M = 4"]
#[inline(always)]
pub fn div4(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1M_A::Div4)
}
#[doc = "PLLSAI1M = 5"]
#[inline(always)]
pub fn div5(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1M_A::Div5)
}
#[doc = "PLLSAI1M = 6"]
#[inline(always)]
pub fn div6(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1M_A::Div6)
}
#[doc = "PLLSAI1M = 7"]
#[inline(always)]
pub fn div7(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1M_A::Div7)
}
#[doc = "PLLSAI1M = 8"]
#[inline(always)]
pub fn div8(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1M_A::Div8)
}
#[doc = "PLLSAI1M = 9"]
#[inline(always)]
pub fn div9(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1M_A::Div9)
}
#[doc = "PLLSAI1M = 11"]
#[inline(always)]
pub fn div10(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1M_A::Div10)
}
#[doc = "PLLSAI1M = 12"]
#[inline(always)]
pub fn div11(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1M_A::Div11)
}
#[doc = "PLLSAI1M = 13"]
#[inline(always)]
pub fn div12(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1M_A::Div12)
}
#[doc = "PLLSAI1M = 13"]
#[inline(always)]
pub fn div13(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1M_A::Div13)
}
#[doc = "PLLSAI1M = 14"]
#[inline(always)]
pub fn div14(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1M_A::Div14)
}
#[doc = "PLLSAI1M = 15"]
#[inline(always)]
pub fn div15(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1M_A::Div15)
}
#[doc = "PLLSAI1M = 16"]
#[inline(always)]
pub fn div16(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1M_A::Div16)
}
}
#[doc = "Field `PLLSAI1N` reader - SAI1PLL multiplication factor for VCO"]
pub type PLLSAI1N_R = crate::FieldReader;
#[doc = "Field `PLLSAI1N` writer - SAI1PLL multiplication factor for VCO"]
pub type PLLSAI1N_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 7, O>;
#[doc = "Field `PLLSAI1PEN` reader - SAI1PLL PLLSAI1CLK output enable"]
pub type PLLSAI1PEN_R = crate::BitReader<PLLSAI1PEN_A>;
#[doc = "SAI1PLL PLLSAI1CLK output enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PLLSAI1PEN_A {
#[doc = "0: PLLSAI1CLK output disable"]
Disabled = 0,
#[doc = "1: PLLSAI1CLK output enabled"]
Enabled = 1,
}
impl From<PLLSAI1PEN_A> for bool {
#[inline(always)]
fn from(variant: PLLSAI1PEN_A) -> Self {
variant as u8 != 0
}
}
impl PLLSAI1PEN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> PLLSAI1PEN_A {
match self.bits {
false => PLLSAI1PEN_A::Disabled,
true => PLLSAI1PEN_A::Enabled,
}
}
#[doc = "PLLSAI1CLK output disable"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == PLLSAI1PEN_A::Disabled
}
#[doc = "PLLSAI1CLK output enabled"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == PLLSAI1PEN_A::Enabled
}
}
#[doc = "Field `PLLSAI1PEN` writer - SAI1PLL PLLSAI1CLK output enable"]
pub type PLLSAI1PEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, PLLSAI1PEN_A>;
impl<'a, REG, const O: u8> PLLSAI1PEN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "PLLSAI1CLK output disable"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1PEN_A::Disabled)
}
#[doc = "PLLSAI1CLK output enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1PEN_A::Enabled)
}
}
#[doc = "Field `PLLSAI1P` reader - SAI1PLL division factor for PLLSAI1CLK (SAI1 or SAI2 clock)"]
pub type PLLSAI1P_R = crate::BitReader<PLLSAI1P_A>;
#[doc = "SAI1PLL division factor for PLLSAI1CLK (SAI1 or SAI2 clock)\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PLLSAI1P_A {
#[doc = "0: PLLSAI1P = 7"]
Div7 = 0,
#[doc = "1: PLLSAI1P = 17"]
Div17 = 1,
}
impl From<PLLSAI1P_A> for bool {
#[inline(always)]
fn from(variant: PLLSAI1P_A) -> Self {
variant as u8 != 0
}
}
impl PLLSAI1P_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> PLLSAI1P_A {
match self.bits {
false => PLLSAI1P_A::Div7,
true => PLLSAI1P_A::Div17,
}
}
#[doc = "PLLSAI1P = 7"]
#[inline(always)]
pub fn is_div7(&self) -> bool {
*self == PLLSAI1P_A::Div7
}
#[doc = "PLLSAI1P = 17"]
#[inline(always)]
pub fn is_div17(&self) -> bool {
*self == PLLSAI1P_A::Div17
}
}
#[doc = "Field `PLLSAI1P` writer - SAI1PLL division factor for PLLSAI1CLK (SAI1 or SAI2 clock)"]
pub type PLLSAI1P_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, PLLSAI1P_A>;
impl<'a, REG, const O: u8> PLLSAI1P_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "PLLSAI1P = 7"]
#[inline(always)]
pub fn div7(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1P_A::Div7)
}
#[doc = "PLLSAI1P = 17"]
#[inline(always)]
pub fn div17(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1P_A::Div17)
}
}
#[doc = "Field `PLLSAI1QEN` reader - SAI1PLL PLLUSB2CLK output enable"]
pub type PLLSAI1QEN_R = crate::BitReader<PLLSAI1QEN_A>;
#[doc = "SAI1PLL PLLUSB2CLK output enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PLLSAI1QEN_A {
#[doc = "0: PLL48M2CLK output disable"]
Disabled = 0,
#[doc = "1: PLL48M2CLK output enabled"]
Enabled = 1,
}
impl From<PLLSAI1QEN_A> for bool {
#[inline(always)]
fn from(variant: PLLSAI1QEN_A) -> Self {
variant as u8 != 0
}
}
impl PLLSAI1QEN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> PLLSAI1QEN_A {
match self.bits {
false => PLLSAI1QEN_A::Disabled,
true => PLLSAI1QEN_A::Enabled,
}
}
#[doc = "PLL48M2CLK output disable"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == PLLSAI1QEN_A::Disabled
}
#[doc = "PLL48M2CLK output enabled"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == PLLSAI1QEN_A::Enabled
}
}
#[doc = "Field `PLLSAI1QEN` writer - SAI1PLL PLLUSB2CLK output enable"]
pub type PLLSAI1QEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, PLLSAI1QEN_A>;
impl<'a, REG, const O: u8> PLLSAI1QEN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "PLL48M2CLK output disable"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1QEN_A::Disabled)
}
#[doc = "PLL48M2CLK output enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1QEN_A::Enabled)
}
}
#[doc = "Field `PLLSAI1Q` reader - SAI1PLL division factor for PLLUSB2CLK (48 MHz clock)"]
pub type PLLSAI1Q_R = crate::FieldReader<PLLSAI1Q_A>;
#[doc = "SAI1PLL division factor for PLLUSB2CLK (48 MHz clock)\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum PLLSAI1Q_A {
#[doc = "0: PLLSAI1x = 2"]
Div2 = 0,
#[doc = "1: PLLSAI1x = 4"]
Div4 = 1,
#[doc = "2: PLLSAI1x = 6"]
Div6 = 2,
#[doc = "3: PLLSAI1x = 8"]
Div8 = 3,
}
impl From<PLLSAI1Q_A> for u8 {
#[inline(always)]
fn from(variant: PLLSAI1Q_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for PLLSAI1Q_A {
type Ux = u8;
}
impl PLLSAI1Q_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> PLLSAI1Q_A {
match self.bits {
0 => PLLSAI1Q_A::Div2,
1 => PLLSAI1Q_A::Div4,
2 => PLLSAI1Q_A::Div6,
3 => PLLSAI1Q_A::Div8,
_ => unreachable!(),
}
}
#[doc = "PLLSAI1x = 2"]
#[inline(always)]
pub fn is_div2(&self) -> bool {
*self == PLLSAI1Q_A::Div2
}
#[doc = "PLLSAI1x = 4"]
#[inline(always)]
pub fn is_div4(&self) -> bool {
*self == PLLSAI1Q_A::Div4
}
#[doc = "PLLSAI1x = 6"]
#[inline(always)]
pub fn is_div6(&self) -> bool {
*self == PLLSAI1Q_A::Div6
}
#[doc = "PLLSAI1x = 8"]
#[inline(always)]
pub fn is_div8(&self) -> bool {
*self == PLLSAI1Q_A::Div8
}
}
#[doc = "Field `PLLSAI1Q` writer - SAI1PLL division factor for PLLUSB2CLK (48 MHz clock)"]
pub type PLLSAI1Q_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 2, O, PLLSAI1Q_A>;
impl<'a, REG, const O: u8> PLLSAI1Q_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "PLLSAI1x = 2"]
#[inline(always)]
pub fn div2(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1Q_A::Div2)
}
#[doc = "PLLSAI1x = 4"]
#[inline(always)]
pub fn div4(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1Q_A::Div4)
}
#[doc = "PLLSAI1x = 6"]
#[inline(always)]
pub fn div6(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1Q_A::Div6)
}
#[doc = "PLLSAI1x = 8"]
#[inline(always)]
pub fn div8(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1Q_A::Div8)
}
}
#[doc = "Field `PLLSAI1REN` reader - PLLSAI1 PLLADC1CLK output enable"]
pub type PLLSAI1REN_R = crate::BitReader<PLLSAI1REN_A>;
#[doc = "PLLSAI1 PLLADC1CLK output enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PLLSAI1REN_A {
#[doc = "0: PLLADC1CLK output disable"]
Disabled = 0,
#[doc = "1: PLLADC1CLK output enabled"]
Enabled = 1,
}
impl From<PLLSAI1REN_A> for bool {
#[inline(always)]
fn from(variant: PLLSAI1REN_A) -> Self {
variant as u8 != 0
}
}
impl PLLSAI1REN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> PLLSAI1REN_A {
match self.bits {
false => PLLSAI1REN_A::Disabled,
true => PLLSAI1REN_A::Enabled,
}
}
#[doc = "PLLADC1CLK output disable"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == PLLSAI1REN_A::Disabled
}
#[doc = "PLLADC1CLK output enabled"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == PLLSAI1REN_A::Enabled
}
}
#[doc = "Field `PLLSAI1REN` writer - PLLSAI1 PLLADC1CLK output enable"]
pub type PLLSAI1REN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, PLLSAI1REN_A>;
impl<'a, REG, const O: u8> PLLSAI1REN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "PLLADC1CLK output disable"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1REN_A::Disabled)
}
#[doc = "PLLADC1CLK output enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1REN_A::Enabled)
}
}
#[doc = "Field `PLLSAI1R` reader - PLLSAI1 division factor for PLLADC1CLK (ADC clock)"]
pub use PLLSAI1Q_R as PLLSAI1R_R;
#[doc = "Field `PLLSAI1R` writer - PLLSAI1 division factor for PLLADC1CLK (ADC clock)"]
pub use PLLSAI1Q_W as PLLSAI1R_W;
#[doc = "Field `PLLSAI1PDIV` reader - PLLSAI1 division factor for PLLSAI1CLK"]
pub type PLLSAI1PDIV_R = crate::FieldReader<PLLSAI1PDIV_A>;
#[doc = "PLLSAI1 division factor for PLLSAI1CLK\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum PLLSAI1PDIV_A {
#[doc = "0: PLLSAI1CLK is controlled by the bit PLLSAI1P"]
Pllsai1p = 0,
#[doc = "2: PLLSAI1CLK = VCOSAI / 2"]
Div2 = 2,
#[doc = "3: PLLSAI1CLK = VCOSAI / 3"]
Div3 = 3,
#[doc = "4: PLLSAI1CLK = VCOSAI / 4"]
Div4 = 4,
#[doc = "5: PLLSAI1CLK = VCOSAI / 5"]
Div5 = 5,
#[doc = "6: PLLSAI1CLK = VCOSAI / 6"]
Div6 = 6,
#[doc = "7: PLLSAI1CLK = VCOSAI / 7"]
Div7 = 7,
#[doc = "8: PLLSAI1CLK = VCOSAI / 8"]
Div8 = 8,
#[doc = "9: PLLSAI1CLK = VCOSAI / 9"]
Div9 = 9,
#[doc = "10: PLLSAI1CLK = VCOSAI / 10"]
Div10 = 10,
#[doc = "11: PLLSAI1CLK = VCOSAI / 11"]
Div11 = 11,
#[doc = "12: PLLSAI1CLK = VCOSAI / 12"]
Div12 = 12,
#[doc = "13: PLLSAI1CLK = VCOSAI / 13"]
Div13 = 13,
#[doc = "14: PLLSAI1CLK = VCOSAI / 14"]
Div14 = 14,
#[doc = "15: PLLSAI1CLK = VCOSAI / 15"]
Div15 = 15,
#[doc = "16: PLLSAI1CLK = VCOSAI / 16"]
Div16 = 16,
#[doc = "17: PLLSAI1CLK = VCOSAI / 17"]
Div17 = 17,
#[doc = "18: PLLSAI1CLK = VCOSAI / 18"]
Div18 = 18,
#[doc = "19: PLLSAI1CLK = VCOSAI / 19"]
Div19 = 19,
#[doc = "20: PLLSAI1CLK = VCOSAI / 20"]
Div20 = 20,
#[doc = "21: PLLSAI1CLK = VCOSAI / 21"]
Div21 = 21,
#[doc = "22: PLLSAI1CLK = VCOSAI / 22"]
Div22 = 22,
#[doc = "23: PLLSAI1CLK = VCOSAI / 23"]
Div23 = 23,
#[doc = "24: PLLSAI1CLK = VCOSAI / 24"]
Div24 = 24,
#[doc = "25: PLLSAI1CLK = VCOSAI / 25"]
Div25 = 25,
#[doc = "26: PLLSAI1CLK = VCOSAI / 26"]
Div26 = 26,
#[doc = "27: PLLSAI1CLK = VCOSAI / 27"]
Div27 = 27,
#[doc = "28: PLLSAI1CLK = VCOSAI / 28"]
Div28 = 28,
#[doc = "29: PLLSAI1CLK = VCOSAI / 29"]
Div29 = 29,
#[doc = "30: PLLSAI1CLK = VCOSAI / 30"]
Div30 = 30,
#[doc = "31: PLLSAI1CLK = VCOSAI / 31"]
Div31 = 31,
}
impl From<PLLSAI1PDIV_A> for u8 {
#[inline(always)]
fn from(variant: PLLSAI1PDIV_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for PLLSAI1PDIV_A {
type Ux = u8;
}
impl PLLSAI1PDIV_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<PLLSAI1PDIV_A> {
match self.bits {
0 => Some(PLLSAI1PDIV_A::Pllsai1p),
2 => Some(PLLSAI1PDIV_A::Div2),
3 => Some(PLLSAI1PDIV_A::Div3),
4 => Some(PLLSAI1PDIV_A::Div4),
5 => Some(PLLSAI1PDIV_A::Div5),
6 => Some(PLLSAI1PDIV_A::Div6),
7 => Some(PLLSAI1PDIV_A::Div7),
8 => Some(PLLSAI1PDIV_A::Div8),
9 => Some(PLLSAI1PDIV_A::Div9),
10 => Some(PLLSAI1PDIV_A::Div10),
11 => Some(PLLSAI1PDIV_A::Div11),
12 => Some(PLLSAI1PDIV_A::Div12),
13 => Some(PLLSAI1PDIV_A::Div13),
14 => Some(PLLSAI1PDIV_A::Div14),
15 => Some(PLLSAI1PDIV_A::Div15),
16 => Some(PLLSAI1PDIV_A::Div16),
17 => Some(PLLSAI1PDIV_A::Div17),
18 => Some(PLLSAI1PDIV_A::Div18),
19 => Some(PLLSAI1PDIV_A::Div19),
20 => Some(PLLSAI1PDIV_A::Div20),
21 => Some(PLLSAI1PDIV_A::Div21),
22 => Some(PLLSAI1PDIV_A::Div22),
23 => Some(PLLSAI1PDIV_A::Div23),
24 => Some(PLLSAI1PDIV_A::Div24),
25 => Some(PLLSAI1PDIV_A::Div25),
26 => Some(PLLSAI1PDIV_A::Div26),
27 => Some(PLLSAI1PDIV_A::Div27),
28 => Some(PLLSAI1PDIV_A::Div28),
29 => Some(PLLSAI1PDIV_A::Div29),
30 => Some(PLLSAI1PDIV_A::Div30),
31 => Some(PLLSAI1PDIV_A::Div31),
_ => None,
}
}
#[doc = "PLLSAI1CLK is controlled by the bit PLLSAI1P"]
#[inline(always)]
pub fn is_pllsai1p(&self) -> bool {
*self == PLLSAI1PDIV_A::Pllsai1p
}
#[doc = "PLLSAI1CLK = VCOSAI / 2"]
#[inline(always)]
pub fn is_div2(&self) -> bool {
*self == PLLSAI1PDIV_A::Div2
}
#[doc = "PLLSAI1CLK = VCOSAI / 3"]
#[inline(always)]
pub fn is_div3(&self) -> bool {
*self == PLLSAI1PDIV_A::Div3
}
#[doc = "PLLSAI1CLK = VCOSAI / 4"]
#[inline(always)]
pub fn is_div4(&self) -> bool {
*self == PLLSAI1PDIV_A::Div4
}
#[doc = "PLLSAI1CLK = VCOSAI / 5"]
#[inline(always)]
pub fn is_div5(&self) -> bool {
*self == PLLSAI1PDIV_A::Div5
}
#[doc = "PLLSAI1CLK = VCOSAI / 6"]
#[inline(always)]
pub fn is_div6(&self) -> bool {
*self == PLLSAI1PDIV_A::Div6
}
#[doc = "PLLSAI1CLK = VCOSAI / 7"]
#[inline(always)]
pub fn is_div7(&self) -> bool {
*self == PLLSAI1PDIV_A::Div7
}
#[doc = "PLLSAI1CLK = VCOSAI / 8"]
#[inline(always)]
pub fn is_div8(&self) -> bool {
*self == PLLSAI1PDIV_A::Div8
}
#[doc = "PLLSAI1CLK = VCOSAI / 9"]
#[inline(always)]
pub fn is_div9(&self) -> bool {
*self == PLLSAI1PDIV_A::Div9
}
#[doc = "PLLSAI1CLK = VCOSAI / 10"]
#[inline(always)]
pub fn is_div10(&self) -> bool {
*self == PLLSAI1PDIV_A::Div10
}
#[doc = "PLLSAI1CLK = VCOSAI / 11"]
#[inline(always)]
pub fn is_div11(&self) -> bool {
*self == PLLSAI1PDIV_A::Div11
}
#[doc = "PLLSAI1CLK = VCOSAI / 12"]
#[inline(always)]
pub fn is_div12(&self) -> bool {
*self == PLLSAI1PDIV_A::Div12
}
#[doc = "PLLSAI1CLK = VCOSAI / 13"]
#[inline(always)]
pub fn is_div13(&self) -> bool {
*self == PLLSAI1PDIV_A::Div13
}
#[doc = "PLLSAI1CLK = VCOSAI / 14"]
#[inline(always)]
pub fn is_div14(&self) -> bool {
*self == PLLSAI1PDIV_A::Div14
}
#[doc = "PLLSAI1CLK = VCOSAI / 15"]
#[inline(always)]
pub fn is_div15(&self) -> bool {
*self == PLLSAI1PDIV_A::Div15
}
#[doc = "PLLSAI1CLK = VCOSAI / 16"]
#[inline(always)]
pub fn is_div16(&self) -> bool {
*self == PLLSAI1PDIV_A::Div16
}
#[doc = "PLLSAI1CLK = VCOSAI / 17"]
#[inline(always)]
pub fn is_div17(&self) -> bool {
*self == PLLSAI1PDIV_A::Div17
}
#[doc = "PLLSAI1CLK = VCOSAI / 18"]
#[inline(always)]
pub fn is_div18(&self) -> bool {
*self == PLLSAI1PDIV_A::Div18
}
#[doc = "PLLSAI1CLK = VCOSAI / 19"]
#[inline(always)]
pub fn is_div19(&self) -> bool {
*self == PLLSAI1PDIV_A::Div19
}
#[doc = "PLLSAI1CLK = VCOSAI / 20"]
#[inline(always)]
pub fn is_div20(&self) -> bool {
*self == PLLSAI1PDIV_A::Div20
}
#[doc = "PLLSAI1CLK = VCOSAI / 21"]
#[inline(always)]
pub fn is_div21(&self) -> bool {
*self == PLLSAI1PDIV_A::Div21
}
#[doc = "PLLSAI1CLK = VCOSAI / 22"]
#[inline(always)]
pub fn is_div22(&self) -> bool {
*self == PLLSAI1PDIV_A::Div22
}
#[doc = "PLLSAI1CLK = VCOSAI / 23"]
#[inline(always)]
pub fn is_div23(&self) -> bool {
*self == PLLSAI1PDIV_A::Div23
}
#[doc = "PLLSAI1CLK = VCOSAI / 24"]
#[inline(always)]
pub fn is_div24(&self) -> bool {
*self == PLLSAI1PDIV_A::Div24
}
#[doc = "PLLSAI1CLK = VCOSAI / 25"]
#[inline(always)]
pub fn is_div25(&self) -> bool {
*self == PLLSAI1PDIV_A::Div25
}
#[doc = "PLLSAI1CLK = VCOSAI / 26"]
#[inline(always)]
pub fn is_div26(&self) -> bool {
*self == PLLSAI1PDIV_A::Div26
}
#[doc = "PLLSAI1CLK = VCOSAI / 27"]
#[inline(always)]
pub fn is_div27(&self) -> bool {
*self == PLLSAI1PDIV_A::Div27
}
#[doc = "PLLSAI1CLK = VCOSAI / 28"]
#[inline(always)]
pub fn is_div28(&self) -> bool {
*self == PLLSAI1PDIV_A::Div28
}
#[doc = "PLLSAI1CLK = VCOSAI / 29"]
#[inline(always)]
pub fn is_div29(&self) -> bool {
*self == PLLSAI1PDIV_A::Div29
}
#[doc = "PLLSAI1CLK = VCOSAI / 30"]
#[inline(always)]
pub fn is_div30(&self) -> bool {
*self == PLLSAI1PDIV_A::Div30
}
#[doc = "PLLSAI1CLK = VCOSAI / 31"]
#[inline(always)]
pub fn is_div31(&self) -> bool {
*self == PLLSAI1PDIV_A::Div31
}
}
#[doc = "Field `PLLSAI1PDIV` writer - PLLSAI1 division factor for PLLSAI1CLK"]
pub type PLLSAI1PDIV_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 5, O, PLLSAI1PDIV_A>;
impl<'a, REG, const O: u8> PLLSAI1PDIV_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "PLLSAI1CLK is controlled by the bit PLLSAI1P"]
#[inline(always)]
pub fn pllsai1p(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1PDIV_A::Pllsai1p)
}
#[doc = "PLLSAI1CLK = VCOSAI / 2"]
#[inline(always)]
pub fn div2(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1PDIV_A::Div2)
}
#[doc = "PLLSAI1CLK = VCOSAI / 3"]
#[inline(always)]
pub fn div3(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1PDIV_A::Div3)
}
#[doc = "PLLSAI1CLK = VCOSAI / 4"]
#[inline(always)]
pub fn div4(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1PDIV_A::Div4)
}
#[doc = "PLLSAI1CLK = VCOSAI / 5"]
#[inline(always)]
pub fn div5(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1PDIV_A::Div5)
}
#[doc = "PLLSAI1CLK = VCOSAI / 6"]
#[inline(always)]
pub fn div6(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1PDIV_A::Div6)
}
#[doc = "PLLSAI1CLK = VCOSAI / 7"]
#[inline(always)]
pub fn div7(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1PDIV_A::Div7)
}
#[doc = "PLLSAI1CLK = VCOSAI / 8"]
#[inline(always)]
pub fn div8(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1PDIV_A::Div8)
}
#[doc = "PLLSAI1CLK = VCOSAI / 9"]
#[inline(always)]
pub fn div9(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1PDIV_A::Div9)
}
#[doc = "PLLSAI1CLK = VCOSAI / 10"]
#[inline(always)]
pub fn div10(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1PDIV_A::Div10)
}
#[doc = "PLLSAI1CLK = VCOSAI / 11"]
#[inline(always)]
pub fn div11(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1PDIV_A::Div11)
}
#[doc = "PLLSAI1CLK = VCOSAI / 12"]
#[inline(always)]
pub fn div12(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1PDIV_A::Div12)
}
#[doc = "PLLSAI1CLK = VCOSAI / 13"]
#[inline(always)]
pub fn div13(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1PDIV_A::Div13)
}
#[doc = "PLLSAI1CLK = VCOSAI / 14"]
#[inline(always)]
pub fn div14(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1PDIV_A::Div14)
}
#[doc = "PLLSAI1CLK = VCOSAI / 15"]
#[inline(always)]
pub fn div15(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1PDIV_A::Div15)
}
#[doc = "PLLSAI1CLK = VCOSAI / 16"]
#[inline(always)]
pub fn div16(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1PDIV_A::Div16)
}
#[doc = "PLLSAI1CLK = VCOSAI / 17"]
#[inline(always)]
pub fn div17(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1PDIV_A::Div17)
}
#[doc = "PLLSAI1CLK = VCOSAI / 18"]
#[inline(always)]
pub fn div18(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1PDIV_A::Div18)
}
#[doc = "PLLSAI1CLK = VCOSAI / 19"]
#[inline(always)]
pub fn div19(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1PDIV_A::Div19)
}
#[doc = "PLLSAI1CLK = VCOSAI / 20"]
#[inline(always)]
pub fn div20(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1PDIV_A::Div20)
}
#[doc = "PLLSAI1CLK = VCOSAI / 21"]
#[inline(always)]
pub fn div21(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1PDIV_A::Div21)
}
#[doc = "PLLSAI1CLK = VCOSAI / 22"]
#[inline(always)]
pub fn div22(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1PDIV_A::Div22)
}
#[doc = "PLLSAI1CLK = VCOSAI / 23"]
#[inline(always)]
pub fn div23(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1PDIV_A::Div23)
}
#[doc = "PLLSAI1CLK = VCOSAI / 24"]
#[inline(always)]
pub fn div24(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1PDIV_A::Div24)
}
#[doc = "PLLSAI1CLK = VCOSAI / 25"]
#[inline(always)]
pub fn div25(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1PDIV_A::Div25)
}
#[doc = "PLLSAI1CLK = VCOSAI / 26"]
#[inline(always)]
pub fn div26(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1PDIV_A::Div26)
}
#[doc = "PLLSAI1CLK = VCOSAI / 27"]
#[inline(always)]
pub fn div27(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1PDIV_A::Div27)
}
#[doc = "PLLSAI1CLK = VCOSAI / 28"]
#[inline(always)]
pub fn div28(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1PDIV_A::Div28)
}
#[doc = "PLLSAI1CLK = VCOSAI / 29"]
#[inline(always)]
pub fn div29(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1PDIV_A::Div29)
}
#[doc = "PLLSAI1CLK = VCOSAI / 30"]
#[inline(always)]
pub fn div30(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1PDIV_A::Div30)
}
#[doc = "PLLSAI1CLK = VCOSAI / 31"]
#[inline(always)]
pub fn div31(self) -> &'a mut crate::W<REG> {
self.variant(PLLSAI1PDIV_A::Div31)
}
}
impl R {
#[doc = "Bits 4:7 - Division factor for PLLSAI1 input clock"]
#[inline(always)]
pub fn pllsai1m(&self) -> PLLSAI1M_R {
PLLSAI1M_R::new(((self.bits >> 4) & 0x0f) as u8)
}
#[doc = "Bits 8:14 - SAI1PLL multiplication factor for VCO"]
#[inline(always)]
pub fn pllsai1n(&self) -> PLLSAI1N_R {
PLLSAI1N_R::new(((self.bits >> 8) & 0x7f) as u8)
}
#[doc = "Bit 16 - SAI1PLL PLLSAI1CLK output enable"]
#[inline(always)]
pub fn pllsai1pen(&self) -> PLLSAI1PEN_R {
PLLSAI1PEN_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 17 - SAI1PLL division factor for PLLSAI1CLK (SAI1 or SAI2 clock)"]
#[inline(always)]
pub fn pllsai1p(&self) -> PLLSAI1P_R {
PLLSAI1P_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bit 20 - SAI1PLL PLLUSB2CLK output enable"]
#[inline(always)]
pub fn pllsai1qen(&self) -> PLLSAI1QEN_R {
PLLSAI1QEN_R::new(((self.bits >> 20) & 1) != 0)
}
#[doc = "Bits 21:22 - SAI1PLL division factor for PLLUSB2CLK (48 MHz clock)"]
#[inline(always)]
pub fn pllsai1q(&self) -> PLLSAI1Q_R {
PLLSAI1Q_R::new(((self.bits >> 21) & 3) as u8)
}
#[doc = "Bit 24 - PLLSAI1 PLLADC1CLK output enable"]
#[inline(always)]
pub fn pllsai1ren(&self) -> PLLSAI1REN_R {
PLLSAI1REN_R::new(((self.bits >> 24) & 1) != 0)
}
#[doc = "Bits 25:26 - PLLSAI1 division factor for PLLADC1CLK (ADC clock)"]
#[inline(always)]
pub fn pllsai1r(&self) -> PLLSAI1R_R {
PLLSAI1R_R::new(((self.bits >> 25) & 3) as u8)
}
#[doc = "Bits 27:31 - PLLSAI1 division factor for PLLSAI1CLK"]
#[inline(always)]
pub fn pllsai1pdiv(&self) -> PLLSAI1PDIV_R {
PLLSAI1PDIV_R::new(((self.bits >> 27) & 0x1f) as u8)
}
}
impl W {
#[doc = "Bits 4:7 - Division factor for PLLSAI1 input clock"]
#[inline(always)]
#[must_use]
pub fn pllsai1m(&mut self) -> PLLSAI1M_W<PLLSAI1CFGR_SPEC, 4> {
PLLSAI1M_W::new(self)
}
#[doc = "Bits 8:14 - SAI1PLL multiplication factor for VCO"]
#[inline(always)]
#[must_use]
pub fn pllsai1n(&mut self) -> PLLSAI1N_W<PLLSAI1CFGR_SPEC, 8> {
PLLSAI1N_W::new(self)
}
#[doc = "Bit 16 - SAI1PLL PLLSAI1CLK output enable"]
#[inline(always)]
#[must_use]
pub fn pllsai1pen(&mut self) -> PLLSAI1PEN_W<PLLSAI1CFGR_SPEC, 16> {
PLLSAI1PEN_W::new(self)
}
#[doc = "Bit 17 - SAI1PLL division factor for PLLSAI1CLK (SAI1 or SAI2 clock)"]
#[inline(always)]
#[must_use]
pub fn pllsai1p(&mut self) -> PLLSAI1P_W<PLLSAI1CFGR_SPEC, 17> {
PLLSAI1P_W::new(self)
}
#[doc = "Bit 20 - SAI1PLL PLLUSB2CLK output enable"]
#[inline(always)]
#[must_use]
pub fn pllsai1qen(&mut self) -> PLLSAI1QEN_W<PLLSAI1CFGR_SPEC, 20> {
PLLSAI1QEN_W::new(self)
}
#[doc = "Bits 21:22 - SAI1PLL division factor for PLLUSB2CLK (48 MHz clock)"]
#[inline(always)]
#[must_use]
pub fn pllsai1q(&mut self) -> PLLSAI1Q_W<PLLSAI1CFGR_SPEC, 21> {
PLLSAI1Q_W::new(self)
}
#[doc = "Bit 24 - PLLSAI1 PLLADC1CLK output enable"]
#[inline(always)]
#[must_use]
pub fn pllsai1ren(&mut self) -> PLLSAI1REN_W<PLLSAI1CFGR_SPEC, 24> {
PLLSAI1REN_W::new(self)
}
#[doc = "Bits 25:26 - PLLSAI1 division factor for PLLADC1CLK (ADC clock)"]
#[inline(always)]
#[must_use]
pub fn pllsai1r(&mut self) -> PLLSAI1R_W<PLLSAI1CFGR_SPEC, 25> {
PLLSAI1R_W::new(self)
}
#[doc = "Bits 27:31 - PLLSAI1 division factor for PLLSAI1CLK"]
#[inline(always)]
#[must_use]
pub fn pllsai1pdiv(&mut self) -> PLLSAI1PDIV_W<PLLSAI1CFGR_SPEC, 27> {
PLLSAI1PDIV_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 = "PLLSAI1 configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`pllsai1cfgr::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 [`pllsai1cfgr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct PLLSAI1CFGR_SPEC;
impl crate::RegisterSpec for PLLSAI1CFGR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`pllsai1cfgr::R`](R) reader structure"]
impl crate::Readable for PLLSAI1CFGR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`pllsai1cfgr::W`](W) writer structure"]
impl crate::Writable for PLLSAI1CFGR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets PLLSAI1CFGR to value 0x1000"]
impl crate::Resettable for PLLSAI1CFGR_SPEC {
const RESET_VALUE: Self::Ux = 0x1000;
}
|
#[doc = "Register `CSICFGR` reader"]
pub type R = crate::R<CSICFGR_SPEC>;
#[doc = "Register `CSICFGR` writer"]
pub type W = crate::W<CSICFGR_SPEC>;
#[doc = "Field `CSICAL` reader - CSI clock calibration Set by hardware by option byte loading during system reset nreset. Adjusted by software through trimming bits CSITRIM. This field represents the sum of engineering option byte calibration value and CSITRIM bits value."]
pub type CSICAL_R = crate::FieldReader;
#[doc = "Field `CSITRIM` reader - CSI clock trimming Set by software to adjust calibration. CSITRIM field is added to the engineering option bytes loaded during reset phase (FLASH_CSI_opt) in order to form the calibration trimming value. CSICALÂ =Â CSITRIMÂ +Â FLASH_CSI_opt. Note: The reset value of the field is 0x20."]
pub type CSITRIM_R = crate::FieldReader;
#[doc = "Field `CSITRIM` writer - CSI clock trimming Set by software to adjust calibration. CSITRIM field is added to the engineering option bytes loaded during reset phase (FLASH_CSI_opt) in order to form the calibration trimming value. CSICALÂ =Â CSITRIMÂ +Â FLASH_CSI_opt. Note: The reset value of the field is 0x20."]
pub type CSITRIM_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 6, O>;
impl R {
#[doc = "Bits 0:7 - CSI clock calibration Set by hardware by option byte loading during system reset nreset. Adjusted by software through trimming bits CSITRIM. This field represents the sum of engineering option byte calibration value and CSITRIM bits value."]
#[inline(always)]
pub fn csical(&self) -> CSICAL_R {
CSICAL_R::new((self.bits & 0xff) as u8)
}
#[doc = "Bits 24:29 - CSI clock trimming Set by software to adjust calibration. CSITRIM field is added to the engineering option bytes loaded during reset phase (FLASH_CSI_opt) in order to form the calibration trimming value. CSICALÂ =Â CSITRIMÂ +Â FLASH_CSI_opt. Note: The reset value of the field is 0x20."]
#[inline(always)]
pub fn csitrim(&self) -> CSITRIM_R {
CSITRIM_R::new(((self.bits >> 24) & 0x3f) as u8)
}
}
impl W {
#[doc = "Bits 24:29 - CSI clock trimming Set by software to adjust calibration. CSITRIM field is added to the engineering option bytes loaded during reset phase (FLASH_CSI_opt) in order to form the calibration trimming value. CSICALÂ =Â CSITRIMÂ +Â FLASH_CSI_opt. Note: The reset value of the field is 0x20."]
#[inline(always)]
#[must_use]
pub fn csitrim(&mut self) -> CSITRIM_W<CSICFGR_SPEC, 24> {
CSITRIM_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 = "RCC CSI calibration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csicfgr::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 [`csicfgr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct CSICFGR_SPEC;
impl crate::RegisterSpec for CSICFGR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`csicfgr::R`](R) reader structure"]
impl crate::Readable for CSICFGR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`csicfgr::W`](W) writer structure"]
impl crate::Writable for CSICFGR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets CSICFGR to value 0x2000_0000"]
impl crate::Resettable for CSICFGR_SPEC {
const RESET_VALUE: Self::Ux = 0x2000_0000;
}
|
#[doc = "Reader of register HV_CTL"]
pub type R = crate::R<u32, super::HV_CTL>;
#[doc = "Writer for register HV_CTL"]
pub type W = crate::W<u32, super::HV_CTL>;
#[doc = "Register HV_CTL `reset()`'s with value 0x32"]
impl crate::ResetValue for super::HV_CTL {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0x32
}
}
#[doc = "Reader of field `TIMER_CLOCK_FREQ`"]
pub type TIMER_CLOCK_FREQ_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `TIMER_CLOCK_FREQ`"]
pub struct TIMER_CLOCK_FREQ_W<'a> {
w: &'a mut W,
}
impl<'a> TIMER_CLOCK_FREQ_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 & !0xff) | ((value as u32) & 0xff);
self.w
}
}
impl R {
#[doc = "Bits 0:7 - Specifies the frequency in MHz of the timer clock 'clk_t' as provide to the flash macro. E.g., if '4', the timer clock 'clk_t' has a frequency of 4 MHz."]
#[inline(always)]
pub fn timer_clock_freq(&self) -> TIMER_CLOCK_FREQ_R {
TIMER_CLOCK_FREQ_R::new((self.bits & 0xff) as u8)
}
}
impl W {
#[doc = "Bits 0:7 - Specifies the frequency in MHz of the timer clock 'clk_t' as provide to the flash macro. E.g., if '4', the timer clock 'clk_t' has a frequency of 4 MHz."]
#[inline(always)]
pub fn timer_clock_freq(&mut self) -> TIMER_CLOCK_FREQ_W {
TIMER_CLOCK_FREQ_W { w: self }
}
}
|
#[cfg(any(feature = "dst_arrow", feature = "dst_arrow2"))]
pub(crate) const SECONDS_IN_DAY: i64 = 86_400;
#[allow(dead_code)]
const KILO: usize = 1 << 10;
#[cfg(any(feature = "dst_arrow", feature = "dst_arrow2"))]
pub const RECORD_BATCH_SIZE: usize = 64 * KILO;
#[cfg(any(
feature = "src_postgres",
feature = "src_mysql",
feature = "src_oracle",
feature = "src_mssql"
))]
pub const DB_BUFFER_SIZE: usize = 32;
#[cfg(any(feature = "src_oracle"))]
pub const ORACLE_ARRAY_SIZE: u32 = (1 * KILO) as u32;
#[cfg(all(not(debug_assertions), feature = "federation"))]
pub const J4RS_BASE_PATH: &str = "../target/release";
#[cfg(all(debug_assertions, feature = "federation"))]
pub const J4RS_BASE_PATH: &str = "../target/debug";
#[cfg(feature = "federation")]
pub const CX_REWRITER_PATH: &str =
"../connectorx-python/connectorx/dependencies/federated-rewriter.jar";
#[cfg(feature = "federation")]
pub const POSTGRES_JDBC_DRIVER: &str = "org.postgresql.Driver";
#[cfg(feature = "federation")]
pub const MYSQL_JDBC_DRIVER: &str = "com.mysql.cj.jdbc.Driver";
#[cfg(feature = "federation")]
pub const DUCKDB_JDBC_DRIVER: &str = "org.duckdb.DuckDBDriver";
pub const CONNECTORX_PROTOCOL: &str = "cxprotocol";
|
use crate::vec3::Vec3;
#[derive(Copy, Clone)]
pub struct Ray {
pub origin: Vec3,
pub direction: Vec3
}
impl Ray {
pub fn new() -> Ray {
Ray {origin: Vec3::new(), direction: Vec3::new()}
}
pub fn new_filled(o: Vec3, d: Vec3) -> Ray {
Ray {origin: o, direction: d}
}
pub fn at(&self, t: f32) -> Vec3 {
self.origin + self.direction * t
}
} |
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct TitleAssetFormat {
len: u32,
ext: Option<TitleAssetFormatExt>,
}
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct TitleAssetFormatExt {}
|
use proconio::{fastout, input};
#[fastout]
fn main() {
input! {
k: u32,
s: String,
}
println!(
"{}",
if s.len() <= k as usize {
s
} else {
s.as_str()[..k as usize].to_string() + "..."
}
)
}
|
//! Abstractions for standard return codes.
use sqlstate_macros::state;
use crate::Category;
pub mod class;
use self::class::*;
/// A representation for a standard `SQLSTATE` code.
#[state(standard)]
#[derive(Clone, Eq, PartialEq, Hash, Debug)]
#[non_exhaustive]
pub enum SqlState {
#[class("00")]
Success(Option<Success>),
#[class("01")]
Warning(Option<Warning>),
#[class("02")]
NoData(Option<NoData>),
#[class("07")]
DynamicSqlError(Option<DynamicSqlError>),
#[class("08")]
ConnectionException(Option<ConnectionException>),
#[class("09")]
TriggeredActionException(Option<TriggeredActionException>),
#[class("0A")]
FeatureNotSupported(Option<FeatureNotSupported>),
#[class("0D")]
InvalidTargetTypeSpecification(Option<InvalidTargetTypeSpecification>),
#[class("0E")]
InvalidSchemaNameListSpecification(Option<InvalidSchemaNameListSpecification>),
#[class("0F")]
LocatorException(Option<LocatorException>),
#[class("0K")]
ResignalWhenHandlerNotActive(Option<ResignalWhenHandlerNotActive>),
#[class("0L")]
InvalidGrantor(Option<InvalidGrantor>),
#[class("0M")]
InvalidSqlInvokedProcedureReference(Option<InvalidSqlInvokedProcedureReference>),
#[class("0N")]
SqlXmlMappingError(Option<SqlXmlMappingError>),
#[class("0P")]
InvalidRoleSpecification(Option<InvalidRoleSpecification>),
#[class("0S")]
InvalidTransformGroupNameSpecification(Option<InvalidTransformGroupNameSpecification>),
#[class("0T")]
TargetTableDisagreesWithCursorSpecification(
Option<TargetTableDisagreesWithCursorSpecification>,
),
#[class("0U")]
AttemptToAssignToNonUpdatableColumn(Option<AttemptToAssignToNonUpdatableColumn>),
#[class("0V")]
AttemptToAssignToOrderingColumn(Option<AttemptToAssignToOrderingColumn>),
#[class("0W")]
ProhibitedStatementDuringTriggerExecution(Option<ProhibitedStatementDuringTriggerExecution>),
#[class("0X")]
InvalidForeignServerSpecification(Option<InvalidForeignServerSpecification>),
#[class("0Y")]
PassthroughSpecificCondition(Option<PassthroughSpecificCondition>),
#[class("0Z")]
DiagnosticsException(Option<DiagnosticsException>),
#[class("10")]
XQueryError(Option<XQueryError>),
#[class("20")]
CaseNotFoundForCaseStatement(Option<CaseNotFoundForCaseStatement>),
#[class("21")]
CardinalityViolation(Option<CardinalityViolation>),
#[class("22")]
DataException(Option<DataException>),
#[class("23")]
IntegrityConstraintViolation(Option<IntegrityConstraintViolation>),
#[class("24")]
InvalidCursorState(Option<InvalidCursorState>),
#[class("25")]
InvalidTransactionState(Option<InvalidTransactionState>),
#[class("26")]
InvalidSqlStatementName(Option<InvalidSqlStatementName>),
#[class("27")]
TriggeredDataChangeViolation(Option<TriggeredDataChangeViolation>),
#[class("28")]
InvalidAuthorizationSpecification(Option<InvalidAuthorizationSpecification>),
#[class("2B")]
DependentPrivilegeDescriptorsExist(Option<DependentPrivilegeDescriptorsExist>),
#[class("2C")]
InvalidCharsetName(Option<InvalidCharsetName>),
#[class("2D")]
InvalidTransactionTermination(Option<InvalidTransactionTermination>),
#[class("2E")]
InvalidConnectionName(Option<InvalidConnectionName>),
#[class("2F")]
SqlRoutineException(Option<SqlRoutineException>),
#[class("2H")]
InvalidCollationName(Option<InvalidCollationName>),
#[class("30")]
InvalidSqlStatementIdentifier(Option<InvalidSqlStatementIdentifier>),
#[class("33")]
InvalidSqlDescriptorName(Option<InvalidSqlDescriptorName>),
#[class("34")]
InvalidCursorName(Option<InvalidCursorName>),
#[class("35")]
InvalidConditionNumber(Option<InvalidConditionNumber>),
#[class("36")]
CursorSensitivityException(Option<CursorSensitivityException>),
#[class("38")]
ExternalRoutineException(Option<ExternalRoutineException>),
#[class("39")]
ExternalRoutineInvocationException(Option<ExternalRoutineInvocationException>),
#[class("3B")]
SavepointException(Option<SavepointException>),
#[class("3C")]
AmbiguousCursorName(Option<AmbiguousCursorName>),
#[class("3D")]
InvalidCatalogName(Option<InvalidCatalogName>),
#[class("3F")]
InvalidSchemaName(Option<InvalidSchemaName>),
#[class("40")]
TransactionRollback(Option<TransactionRollback>),
#[class("42")]
SyntaxErrorOrAccessRuleViolation(Option<SyntaxErrorOrAccessRuleViolation>),
#[class("44")]
WithCheckOptionViolation(Option<WithCheckOptionViolation>),
#[class("45")]
UnhandledUserDefinedException(Option<UnhandledUserDefinedException>),
#[class("46")]
OlbSpecificError(Option<OlbSpecificError>),
#[class("HW")]
DatalinkException(Option<DatalinkException>),
#[class("HV")]
FdwSpecificCondition(Option<FdwSpecificCondition>),
#[class("HY")]
CliSpecificCondition(Option<CliSpecificCondition>),
#[class("HZ")]
RemoteDatabaseAccess(Option<RemoteDatabaseAccess>),
}
impl SqlState {
pub fn category(&self) -> Category {
match self {
Self::Success(_) => Category::Success,
Self::Warning(_) => Category::Warning,
Self::NoData(_) => Category::NoData,
_ => Category::Exception,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::error::ParseError;
fn check(state: &str, value: SqlState) {
assert_eq!(state.parse::<SqlState>().unwrap(), value);
}
#[test]
fn class() {
assert_eq!(SqlState::Success(None).class(), "00");
assert_eq!(SqlState::Warning(None).class(), "01");
assert_eq!(SqlState::DynamicSqlError(None).class(), "07");
}
#[test]
fn subclass() {
assert_eq!(SqlState::Success(None).subclass(), None);
assert_eq!(
SqlState::Warning(Some(Warning::InsufficientItemDescriptorAreas)).subclass(),
Some("005")
);
assert_eq!(
SqlState::DynamicSqlError(Some(DynamicSqlError::InvalidDataTarget)).subclass(),
Some("00D")
);
}
#[test]
fn category() {
assert_eq!(SqlState::Success(None).category(), Category::Success);
assert_eq!(SqlState::Warning(None).category(), Category::Warning);
assert_eq!(SqlState::NoData(None).category(), Category::NoData);
assert_eq!(
SqlState::DynamicSqlError(Some(DynamicSqlError::InvalidDataTarget)).category(),
Category::Exception
);
}
#[test]
fn invalid_length() {
for i in 0..5 {
assert_eq!(
"0".repeat(i).parse::<SqlState>(),
Err(ParseError::InvalidLength(i))
);
}
}
#[test]
fn empty_class() {
check("00000", SqlState::Success(None));
check(
"00001",
SqlState::Success(Some(Success::Other(String::from("001")))),
);
}
#[test]
fn unknown_class() {
check("QQ999", SqlState::Other(String::from("QQ999")));
}
#[test]
fn one_subclass() {
check("02000", SqlState::NoData(None));
check(
"02001",
SqlState::NoData(Some(NoData::NoAdditionalResultSetsReturned)),
);
check(
"0200F",
SqlState::NoData(Some(NoData::Other(String::from("00F")))),
);
}
#[test]
fn many_subclasses() {
check("01000", SqlState::Warning(None));
check(
"01005",
SqlState::Warning(Some(Warning::InsufficientItemDescriptorAreas)),
);
check(
"0100A",
SqlState::Warning(Some(Warning::QueryExpressionTooLongForInformationSchema)),
);
check(
"0102F",
SqlState::Warning(Some(Warning::ArrayDataRightTruncation)),
);
check(
"01FFF",
SqlState::Warning(Some(Warning::Other(String::from("FFF")))),
)
}
}
|
use std::fs;
struct Segment {
x1: i32,
y1: i32,
x2: i32,
y2: i32,
steps: i32,
}
struct Intersection {
x: i32,
y: i32,
steps: i32,
}
impl Segment {
/// Normalize a segment so it always points right or down.
fn normalize(&self) -> Segment {
Segment {
x1: i32::min(self.x1, self.x2),
y1: i32::min(self.y1, self.y2),
x2: i32::max(self.x1, self.x2),
y2: i32::max(self.y1, self.y2),
steps: -1,
}
}
/// Find the intersection point with another segment if it exists.
/// Also returns the number of combined steps from the starting point.
fn intersect(&self, other: &Segment) -> Option<Intersection> {
// Central point is not an intersection
if self.x1 == 0 && self.y1 == 0 && other.x1 == 0 && other.y1 == 0 {
return None;
}
// Self vertical, other horizontal
if self.x1 == self.x2 && other.y1 == other.y2 {
let self_norm = self.normalize();
let other_norm = other.normalize();
if other_norm.x1 <= self_norm.x1 && other_norm.x2 >= self_norm.x2
&& self_norm.y1 <= other_norm.y1 && self_norm.y2 >= other_norm.y2
{
let x = self_norm.x1;
let y = other_norm.y1;
let steps = self.steps + other.steps - (y - self.y2).abs() - (x - other.x2).abs();
return Some(Intersection { x, y, steps, });
}
// Self horizontal, other vertical
} else if self.y1 == self.y2 && other.x1 == other.x2 {
return other.intersect(self);
}
None
}
}
fn main() {
let wires: Vec<Vec<Segment>> = fs::read_to_string("input")
.unwrap()
.lines()
.map(|line| parse_wire(line))
.collect();
part1(&wires[0], &wires[1]);
part2(&wires[0], &wires[1]);
}
fn parse_wire(line: &str) -> Vec<Segment> {
let mut wire = Vec::new();
line.split(',')
.fold((0, 0, 0), |(x, y, steps), movement| {
let n: i32 = movement[1..].parse().unwrap();
let next = match &movement[..1] {
"U" => (x, y + n),
"D" => (x, y - n),
"L" => (x - n, y),
"R" => (x + n, y),
_ => unreachable!(),
};
wire.push(Segment {
x1: x,
y1: y,
x2: next.0,
y2: next.1,
steps: steps + n,
});
(next.0, next.1, steps + n)
});
wire
}
/// Part 1: find the intersection closest to the central point.
fn part1(wire_1: &[Segment], wire_2: &[Segment]) {
let mut min_dist = i32::max_value();
for segment_1 in wire_1 {
for segment_2 in wire_2 {
if let Some(Intersection { x, y, steps: _ }) = segment_1.intersect(segment_2) {
let dist = x + y;
if dist < min_dist {
min_dist = dist;
}
}
}
}
println!("{}", min_dist);
}
/// Part 2: find the intersection with the least amount of combined steps from the central point.
fn part2(wire_1: &[Segment], wire_2: &[Segment]) {
let mut min_steps = i32::max_value();
for segment_1 in wire_1 {
for segment_2 in wire_2 {
if let Some(intersection) = segment_1.intersect(segment_2) {
if intersection.steps < min_steps {
min_steps = intersection.steps;
}
}
}
}
println!("{}", min_steps);
} |
use failure;
use failure::ResultExt;
use stderrlog;
use utils::types;
///This sets up logging, and takes the output from the commandline
///options
pub fn configure_logger(config: &types::Settings) -> Result<(), failure::Error> {
let mut logger = stderrlog::new();
logger
.quiet(config.quiet)
.verbosity(config.verbosity)
.timestamp(config.timestamp);
if let Some(ref module_path) = config.module_path {
logger.module(module_path.clone());
}
logger.init().context("failed to initialize logger")?;
Ok(())
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_configure_logger() {
//test that we don't panic creating a default logger
assert!(configure_logger(&Default::default()).is_ok());
}
}
|
pub trait Codec<Input = u8> {
type Output: Iterator<Item = u8>;
fn accept(&mut self, input: Input) -> Self::Output;
fn finish(self) -> Self::Output;
}
#[derive(Debug)]
pub struct BitDiscard {
buf: u16, // Use the higher byte for storing the leftovers
buf_bits: u8, // How many bits are valid in the buffer
valid_len: u8, // How many bits to keep from the input
shift_len: u8, // Pre-computed shift of the input byte
}
impl BitDiscard {
pub fn new(discard: u8) -> Self {
assert!(discard < 8);
BitDiscard {
buf: 0,
buf_bits: 0,
valid_len: 8 - discard,
shift_len: 8 + discard,
}
}
}
impl Codec<u8> for BitDiscard {
type Output = std::option::IntoIter<u8>;
fn accept(&mut self, input: u8) -> Self::Output {
let add = ((input as u16) << self.shift_len) >> self.buf_bits;
self.buf |= add;
self.buf_bits += self.valid_len;
let result = if self.buf_bits >= 8 {
let result = (self.buf >> 8) as u8;
self.buf <<= 8;
self.buf_bits -= 8;
Some(result)
} else {
None
};
result.into_iter()
}
fn finish(self) -> Self::Output {
let result = if self.buf_bits > 0 {
Some((self.buf >> 8) as u8)
} else {
None
};
result.into_iter()
}
}
#[derive(Debug)]
pub struct BitExpand {
buf: u16, // For storing the leftovers
buf_bits: u8, // How many bits are valid in the buffer
valid_len: u8, // How many bits are valid in the input
shift_len: u8, // How many bits to shift when expanding
}
impl BitExpand {
pub fn new(expand: u8) -> Self {
assert!(expand < 8);
Self {
buf: 0,
buf_bits: 0,
valid_len: 8 - expand,
shift_len: 8 + expand,
}
}
}
impl Codec<u8> for BitExpand {
type Output = BitExpandIter;
fn accept(&mut self, input: u8) -> Self::Output {
let add = ((input as u16) << 8) >> self.buf_bits;
self.buf |= add;
self.buf_bits += 8;
let buf = self.buf;
let leftover = self.buf_bits % self.valid_len;
let buf_bits = self.buf_bits - leftover;
self.buf <<= buf_bits;
self.buf_bits = leftover;
Self::Output {
buf,
buf_bits,
shift_len: self.shift_len,
valid_len: self.valid_len,
}
}
fn finish(self) -> Self::Output {
Self::Output {
buf: 0,
buf_bits: 0,
shift_len: 0,
valid_len: self.valid_len,
}
}
}
#[derive(Debug)]
pub struct BitExpandIter {
buf: u16,
buf_bits: u8,
valid_len: u8,
shift_len: u8,
}
impl Iterator for BitExpandIter {
type Item = u8;
fn next(&mut self) -> Option<u8> {
if self.buf_bits < self.valid_len {
None
} else {
let result = (self.buf >> self.shift_len) as u8;
self.buf <<= self.valid_len;
self.buf_bits -= self.valid_len;
Some(result)
}
}
}
fn process_bytes<C: Codec>(mut codec: C, bytes: &[u8]) -> Vec<u8> {
let mut result: Vec<u8> = bytes.iter().flat_map(|byte| codec.accept(*byte)).collect();
codec.finish().for_each(|byte| result.push(byte));
result
}
fn print_bytes(bytes: &[u8]) {
for byte in bytes {
print!("{:08b} ", byte);
}
println!();
for byte in bytes {
print!("{:02x} ", byte);
}
println!();
}
fn main() {
let original = b"STRINGIFY!";
let discard = 1;
print_bytes(&original[..]);
let compressed = process_bytes(BitDiscard::new(discard), &original[..]);
print_bytes(&compressed);
let decompressed = process_bytes(BitExpand::new(discard), &compressed);
print_bytes(&decompressed);
} |
#[doc = "Register `RFDCR` reader"]
pub type R = crate::R<RFDCR_SPEC>;
#[doc = "Register `RFDCR` writer"]
pub type W = crate::W<RFDCR_SPEC>;
#[doc = "Field `RFTBSEL` reader - radio debug test bus selection"]
pub type RFTBSEL_R = crate::BitReader<RFTBSEL_A>;
#[doc = "radio debug test bus selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RFTBSEL_A {
#[doc = "0: Digital test bus selected on RF_ADTB\\[3:0\\]"]
Digital = 0,
#[doc = "1: Analog test bus selected on RF_ADTB\\[3:0\\]"]
Analog = 1,
}
impl From<RFTBSEL_A> for bool {
#[inline(always)]
fn from(variant: RFTBSEL_A) -> Self {
variant as u8 != 0
}
}
impl RFTBSEL_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> RFTBSEL_A {
match self.bits {
false => RFTBSEL_A::Digital,
true => RFTBSEL_A::Analog,
}
}
#[doc = "Digital test bus selected on RF_ADTB\\[3:0\\]"]
#[inline(always)]
pub fn is_digital(&self) -> bool {
*self == RFTBSEL_A::Digital
}
#[doc = "Analog test bus selected on RF_ADTB\\[3:0\\]"]
#[inline(always)]
pub fn is_analog(&self) -> bool {
*self == RFTBSEL_A::Analog
}
}
#[doc = "Field `RFTBSEL` writer - radio debug test bus selection"]
pub type RFTBSEL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, RFTBSEL_A>;
impl<'a, REG, const O: u8> RFTBSEL_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Digital test bus selected on RF_ADTB\\[3:0\\]"]
#[inline(always)]
pub fn digital(self) -> &'a mut crate::W<REG> {
self.variant(RFTBSEL_A::Digital)
}
#[doc = "Analog test bus selected on RF_ADTB\\[3:0\\]"]
#[inline(always)]
pub fn analog(self) -> &'a mut crate::W<REG> {
self.variant(RFTBSEL_A::Analog)
}
}
impl R {
#[doc = "Bit 0 - radio debug test bus selection"]
#[inline(always)]
pub fn rftbsel(&self) -> RFTBSEL_R {
RFTBSEL_R::new((self.bits & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - radio debug test bus selection"]
#[inline(always)]
#[must_use]
pub fn rftbsel(&mut self) -> RFTBSEL_W<RFDCR_SPEC, 0> {
RFTBSEL_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 = "radio debug control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`rfdcr::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 [`rfdcr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct RFDCR_SPEC;
impl crate::RegisterSpec for RFDCR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`rfdcr::R`](R) reader structure"]
impl crate::Readable for RFDCR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`rfdcr::W`](W) writer structure"]
impl crate::Writable for RFDCR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets RFDCR to value 0"]
impl crate::Resettable for RFDCR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use crate::{
neighbour::{nlas::NeighbourNla, NeighbourBuffer, NeighbourHeader},
traits::{Emitable, Parseable},
DecodeError,
};
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct NeighbourMessage {
pub header: NeighbourHeader,
pub nlas: Vec<NeighbourNla>,
}
impl Emitable for NeighbourMessage {
fn buffer_len(&self) -> usize {
self.header.buffer_len() + self.nlas.as_slice().buffer_len()
}
fn emit(&self, buffer: &mut [u8]) {
self.header.emit(buffer);
self.nlas.as_slice().emit(buffer);
}
}
impl<'buffer, T: AsRef<[u8]> + 'buffer> Parseable<NeighbourMessage>
for NeighbourBuffer<&'buffer T>
{
fn parse(&self) -> Result<NeighbourMessage, DecodeError> {
Ok(NeighbourMessage {
header: self.parse()?,
nlas: self.parse()?,
})
}
}
impl<'buffer, T: AsRef<[u8]> + 'buffer> Parseable<Vec<NeighbourNla>>
for NeighbourBuffer<&'buffer T>
{
fn parse(&self) -> Result<Vec<NeighbourNla>, DecodeError> {
let mut nlas = vec![];
for nla_buf in self.nlas() {
nlas.push(nla_buf?.parse()?);
}
Ok(nlas)
}
}
|
fn bottles(n: i32) -> String {
match n {
1 => "1 bottle of beer".to_string(),
0 => "no more bottles of beer".to_string(),
-1 => "99 bottles of beer".to_string(),
_ => n.to_string() + " bottles of beer",
}
}
fn first_phrase(n: i32) -> String {
match n {
1 => "1 bottle of beer on the wall, 1 bottle of beer.".to_string(),
0 => "No more bottles of beer on the wall, no more bottles of beer.".to_string(),
_ => bottles(n) + " on the wall, " + &bottles(n) + ".",
}
}
fn second_phrase(n: i32) -> String {
match n {
1 => "Take it down and pass it around, ".to_string() + &bottles(n - 1) + " on the wall.",
0 => "Go to the store and buy some more, ".to_string() + &bottles(n - 1) + " on the wall.",
_ => "Take one down and pass it around, ".to_string() + &bottles(n - 1) + " on the wall.",
}
}
pub fn verse(n: i32) -> String {
first_phrase(n) + "\n" + &second_phrase(n) + "\n"
}
pub fn sing(start: i32, end: i32) -> String {
let mut result = String::new();
let mut n: i32 = start;
while n > end {
result = result + &verse(n) + "\n";
n -= 1;
}
result = result + &verse(n);
result
}
|
use std::fmt;
use std::borrow::Cow;
use response::{Backup, Image, Kernel, NamedResponse, Networks, Region, Size};
// Have to duplicate Droplet because of lack of negative trait bounds
#[derive(Deserialize, Debug)]
pub struct DropletNeighbor {
pub id: f64,
pub name: String,
pub memory: f64,
pub vcpus: f64,
pub disk: f64,
pub locked: bool,
pub status: String,
pub kernel: Option<Kernel>,
pub created_at: String,
pub features: Vec<String>,
pub backup_ids: Vec<Option<f64>>,
pub next_backup_window: Option<Backup>,
pub snapshot_ids: Vec<Option<f64>>,
pub image: Image,
pub region: Region,
pub size: Size,
pub size_slug: String,
pub networks: Networks,
}
impl fmt::Display for DropletNeighbor {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,
"ID: {:.0}\n\
Name: {}\n\
Memory: {} MB\n\
Virtual CPUs: {:.0}\n\
Disk: {} GB\n\
Locked: {}\n\
Created At: {}\n\
Status: {}\n\
Backup IDs: {}\n\
Snapshot IDs: {}\n\
Features: {}\n\
Region: \n\t{}\n\
Image: \n\t{}\n\
Size: \n\t{}\n\
Size Slug: {}\n\
Network: \n\t{}\n\
Kernel: \n\t{}\n\
Next Backup Window: {}\n",
self.id,
self.name,
self.memory,
self.vcpus,
self.disk,
self.locked,
self.created_at,
self.status,
self.backup_ids
.iter()
.filter_map(|n| {
if n.is_some() {
Some(n.clone().unwrap().to_string())
} else {
None
}
})
.fold(String::new(), |acc, s| acc + &format!(" {},", s)[..]),
self.snapshot_ids
.iter()
.filter_map(|n| {
if n.is_some() {
Some(n.clone().unwrap().to_string())
} else {
None
}
})
.fold(String::new(), |acc, s| acc + &format!(" {},", s)[..]),
self.features
.iter()
.fold(String::new(), |acc, s| acc + &format!(" {},", s)[..]),
&self.region.to_string()[..].replace("\n", "\n\t"),
&self.image.to_string()[..].replace("\n", "\n\t"),
&self.size.to_string()[..].replace("\n", "\n\t"),
self.size_slug,
&self.networks.to_string()[..].replace("\n", "\n\t"),
if let Some(ref k) = self.kernel {
format!("{}", &k.to_string()[..].replace("\n", "\n\t"))
} else {
"None".to_owned()
},
if let Some(ref k) = self.next_backup_window {
format!("{}", &k.to_string()[..].replace("\n", "\n\t"))
} else {
"None".to_owned()
})
}
}
pub type Neighbor = Vec<DropletNeighbor>;
impl NamedResponse for Neighbor {
fn name<'a>() -> Cow<'a, str> { "neighbor".into() }
}
pub type Neighbors = Vec<Neighbor>;
|
use anyhow::{bail, Context, Result};
use std::ffi::OsStr;
use std::path::Path;
use std::process::Command;
static MISSING_PATCHELF_ERROR: &str = "Failed to execute 'patchelf', did you install it? Hint: Try `pip install maturin[patchelf]` (or just `pip install patchelf`)";
/// Verify patchelf version
pub fn verify_patchelf() -> Result<()> {
let output = Command::new("patchelf")
.arg("--version")
.output()
.context(MISSING_PATCHELF_ERROR)?;
let version = String::from_utf8(output.stdout)
.context("Failed to parse patchelf version")?
.trim()
.to_string();
let version = version.strip_prefix("patchelf").unwrap_or(&version).trim();
let semver = version
.parse::<semver::Version>()
.context("Failed to parse patchelf version")?;
if semver < semver::Version::new(0, 14, 0) {
bail!(
"patchelf {} found. auditwheel repair requires patchelf >= 0.14.",
version
);
}
Ok(())
}
/// Replace a declared dependency on a dynamic library with another one (`DT_NEEDED`)
pub fn replace_needed<O: AsRef<OsStr>, N: AsRef<OsStr>>(
file: impl AsRef<Path>,
old_new_pairs: &[(O, N)],
) -> Result<()> {
let mut cmd = Command::new("patchelf");
for (old, new) in old_new_pairs {
cmd.arg("--replace-needed").arg(old).arg(new);
}
cmd.arg(file.as_ref());
let output = cmd.output().context(MISSING_PATCHELF_ERROR)?;
if !output.status.success() {
bail!(
"patchelf --replace-needed failed: {}",
String::from_utf8_lossy(&output.stderr)
);
}
Ok(())
}
/// Change `SONAME` of a dynamic library
pub fn set_soname<S: AsRef<OsStr>>(file: impl AsRef<Path>, soname: &S) -> Result<()> {
let mut cmd = Command::new("patchelf");
cmd.arg("--set-soname").arg(soname).arg(file.as_ref());
let output = cmd.output().context(MISSING_PATCHELF_ERROR)?;
if !output.status.success() {
bail!(
"patchelf --set-soname failed: {}",
String::from_utf8_lossy(&output.stderr)
);
}
Ok(())
}
/// Remove a `RPATH` from executables and libraries
pub fn remove_rpath(file: impl AsRef<Path>) -> Result<()> {
let mut cmd = Command::new("patchelf");
cmd.arg("--remove-rpath").arg(file.as_ref());
let output = cmd.output().context(MISSING_PATCHELF_ERROR)?;
if !output.status.success() {
bail!(
"patchelf --remove-rpath failed: {}",
String::from_utf8_lossy(&output.stderr)
);
}
Ok(())
}
/// Change the `RPATH` of executables and libraries
pub fn set_rpath<S: AsRef<OsStr>>(file: impl AsRef<Path>, rpath: &S) -> Result<()> {
remove_rpath(&file)?;
let mut cmd = Command::new("patchelf");
cmd.arg("--force-rpath")
.arg("--set-rpath")
.arg(rpath)
.arg(file.as_ref());
let output = cmd.output().context(MISSING_PATCHELF_ERROR)?;
if !output.status.success() {
bail!(
"patchelf --set-rpath failed: {}",
String::from_utf8_lossy(&output.stderr)
);
}
Ok(())
}
/// Get the `RPATH` of executables and libraries
pub fn get_rpath(file: impl AsRef<Path>) -> Result<Vec<String>> {
let file = file.as_ref();
let contents = fs_err::read(file)?;
match goblin::Object::parse(&contents) {
Ok(goblin::Object::Elf(elf)) => {
let rpaths = if !elf.runpaths.is_empty() {
elf.runpaths
} else {
elf.rpaths
};
Ok(rpaths.iter().map(|r| r.to_string()).collect())
}
Ok(_) => bail!("'{}' is not an ELF file", file.display()),
Err(e) => bail!("Failed to parse ELF file at '{}': {}", file.display(), e),
}
}
|
use std::fs;
use std::env;
use std::io::{self, Write};
use std::process::{Command, Stdio};
const CARGONAUTS_GIT: &str = "https://github.com/cargonauts-rs/cargonauts";
const CARGONAUTS_BRANCH: &str = "0.2-release";
const DIRS: &[(&str, Option<&str>)] = &[
("bin", None),
("assets", None),
("clients", Some(CLIENTS)),
("formats", Some(FORMATS)),
("methods", Some(METHODS)),
("middleware", Some(MIDDLEWARE)),
("resources", Some(RESOURCES)),
("templates", None),
];
const CLIENTS: &'static str = "\
// The clients module is for defining your server's API clients.
//
// When your server establishes a connection to another service, it is good
// practice to wrap that connection in a higher-level API. cargonauts provides
// a pair of trait - `Client` and `ConnectClient` which you can use to write
// these wrappers.
//
// These traits are also designed to support easily mocking the other service
// when testing your client, which you can do with the MockConnection type.";
const FORMATS: &'static str = "\
// The formats module is for defining custom formats for displaying your
// resources.
//
// A Format, which implements the `Format` trait, encapsulates the logic for
// displaying responses from that resource's methods as HTTP responses, and of
// translating the body of an HTTP request into the semantic type supported
// by a particular method.
//
// Usually, you will not need to define your own formats; cargonauts comes with
// several formats built-in that should be satisfactory for most use cases.";
const METHODS: &'static str = "\
// The methods module is for defining custom methods you want your resources to
// support.
//
// A method must implement the `Method` trait and either `ResourceMethod` or
// `CollectionMethod` (but not both!). Methods are themselves traits, and can
// be a bit tricky to implement correctly. Read the docs for more info.
//
// Usually, you will not need to define your own methods; cargonauts comes with
// several methods built-in that should be satisfactory for most use cases.";
const MIDDLEWARE: &'static str ="\
// The middleware module is for defining middleware you need in your server.
//
// Middleware let you wrap your endpoint in arbitrary code that can manipulate
// an HTTP service. A middleware must implement the `Middleware` trait.
";
const RESOURCES: &'static str = "\
// The resources module is for defining your application's resources. Every
// app will have many resources.
//
// Each resource must implement the `Resource` trait. For every method you've
// associated with the resource in your routing file, you must also implement
// that method for your resource.
";
const ROUTING: &'static str = "\
// This is your routing file, which contains the `routes!` macro that defines
// the surface API for your application.
//
// Every time you add a new endpoint, you will need to modify this file to
// declare how it will be used.
use cargonauts::methods::*;
use cargonauts::formats::*;
use methods::*;
use formats::*;
use resources::*;
routes! {
}
";
const LIB: &'static str = "\
#![feature(associated_consts)]
#[macro_use] extern crate cargonauts;
mod clients;
mod formats;
mod methods;
mod middleware;
mod resources;
mod routing;
pub use routing::routes;
";
pub fn build_cargonauts_app(name: &str) -> io::Result<()> {
// Create a new app with cargo.
Command::new("cargo").arg("new").arg(name)
.stdout(Stdio::inherit()).stderr(Stdio::inherit())
.output()?;
let path = env::current_dir()?.join(name);
let src_path = path.join("src");
// Create subdirectories
for &(dir, mod_file) in DIRS {
let dir = src_path.join(dir);
fs::create_dir(&dir)?;
if let Some(content) = mod_file {
write!(fs::File::create(dir.join("mod.rs"))?, "{}", content)?;
}
}
// Create routing file
write!(fs::File::create(src_path.join("routing.rs"))?, "{}", ROUTING)?;
// Create server file
write!(fs::File::create(src_path.join("bin/server.rs"))?, "{}", server(name))?;
// Rewrite lib.rs file
write!(fs::File::create(src_path.join("lib.rs"))?, "{}", LIB)?;
// Rewrite Cargo.toml
let mut file = fs::OpenOptions::new().append(true).open(path.join("Cargo.toml"))?;
write!(file, "\n[dependencies.cargonauts]\ngit = \"{}\"\nbranch = \"{}\"",
CARGONAUTS_GIT, CARGONAUTS_BRANCH)?;
Ok(())
}
fn server(name: &str) -> String {
format!("\
// This is your actual server application. By default it just runs the app you
// created with the `routes!` macro. You can edit it to have it do additional
// set-up or tear-down as necesary.
extern crate cargonauts;
extern crate {};
fn main() {{
cargonauts::serve({}::routes).unwrap();
}}", name, name)
}
|
pub struct Solution {}
use std::cmp::Ordering;
impl Solution {
// O(log(n)) time | O(1) space
pub fun search(nums: Vec<i32>, target: i32) -> i32 {
let mut low = 0i32;
let mut high = (nums.len() as i32) - 1;
while low <= high {
let mid = low + (hi - low) / 2;
match nums[mid as usize].cmp(&target) {
Ordering::Less => {
low = mid - 1;
} Ordering::Greater => {
hi = mid - 1;
} Ordering::Equal => {
return mid;
}
}
}
-1
}
} |
use rustimate_core::util::NotificationLevel;
macro_rules! debug {
($($t:tt)*) => (crate::js::log(&format_args!($($t)*).to_string().replacen("", "%c [debug] ", 1), "color: #999;"))
}
macro_rules! info {
($($t:tt)*) => (crate::js::log(&format_args!($($t)*).to_string().replacen("", "%c [info] ", 1), "color: #003049;"))
}
macro_rules! warn {
($($t:tt)*) => (crate::js::log(&format_args!($($t)*).to_string().replacen("", "%c [warn] ", 1), "color: #fcbf49;"))
}
macro_rules! error {
($($t:tt)*) => (crate::js::log(&format_args!($($t)*).to_string().replacen("", "%c [error] ", 1), "color: #d62828;"))
}
pub(crate) fn notify(level: &NotificationLevel, content: &str) -> anyhow::Result<()> {
let level = match level {
NotificationLevel::Info => "primary",
NotificationLevel::Success => "success",
NotificationLevel::Warn => "warning",
NotificationLevel::Error => "danger"
};
crate::js::notify(level, content);
Ok(())
}
|
#![macro_use]
use std::sync::{Arc, Mutex, MutexGuard};
use std::ops::CoerceUnsized;
use std::marker::Unsize;
pub struct Ctx<T: ?Sized> {
content: Arc<Mutex<T>>
}
impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Ctx<U>> for Ctx<T> {}
impl<T: ?Sized> Clone for Ctx<T> {
fn clone(&self) -> Self {
Ctx {
content: self.content.clone()
}
}
}
impl<T: ?Sized> Ctx<T> {
pub fn new(c: T) -> Self where T: Sized {
Ctx {
content: (Arc::new(Mutex::new(c)))
}
}
pub fn ctx<F>(&self, f: F) where F: Fn(&mut T) {
f(&mut *self.content.lock().unwrap())
}
pub fn get(&self) -> MutexGuard<T> {
self.content.lock().unwrap()
}
pub fn ptr_eq(ctx1: &Ctx<T>, ctx2: &Ctx<T>) -> bool {
Arc::ptr_eq(&ctx1.content, &ctx2.content)
}
}
#[macro_export]
macro_rules! ctx {
($x:expr) => {
Ctx {
content: Arc::new(Mutex::new($x))
}
}
}
|
use assert_cmd::prelude::*;
use predicates::prelude::*;
use std::io::{self, Write};
use std::process::Command;
use tempfile::NamedTempFile;
macro_rules! cli_test_success {
($($name:ident: $value:expr,)*) => {
$(
#[test]
fn $name() -> Result<(), Box<dyn std::error::Error>> {
let (input, pattern, expected) = $value;
let mut file = NamedTempFile::new()?;
writeln!(file, "{}", input)?;
let mut cmd = Command::cargo_bin("grrs")?;
cmd.arg(pattern).arg(file.path());
cmd.assert()
.success()
.stdout(predicate::str::contains(expected));
Ok(())
}
)*
}
}
cli_test_success! {
simple: ("A test\nActual content\nMore content\nAnother test", "test", "A test\nAnother test"),
empty_pattern: ("A test\nActual content\nMore content\nAnother test", "", ""),
empty_input: ("", "test", ""),
}
#[test]
fn file_doesnt_exist() -> Result<(), Box<dyn std::error::Error>> {
let mut cmd = Command::cargo_bin("grrs")?;
cmd.arg("foobar").arg("test/file/doesnt/exist");
cmd.assert()
.failure()
.stderr(predicate::str::contains("No such file or directory"));
Ok(())
}
#[test]
fn cli_args_insufficient() -> Result<(), Box<dyn std::error::Error>> {
let mut cmd = Command::cargo_bin("grrs")?;
cmd.arg("foobar");
cmd.assert()
.failure()
.stderr(predicate::str::contains("The following required arguments were not provided"));
Ok(())
}
|
use std::convert::{TryFrom, TryInto};
use proc_macro2::Span;
use syn::{spanned::Spanned, Error, ExprField, Result};
use crate::glsl::Glsl;
use super::YaslExprLineScope;
#[derive(Debug)]
pub struct YaslExprField {
base: Box<YaslExprLineScope>,
member: syn::Ident,
}
impl YaslExprField {
pub fn span(&self) -> Span {
self.member.span()
}
}
impl From<&YaslExprField> for Glsl {
fn from(expr: &YaslExprField) -> Glsl {
Glsl::Expr(format!(
"{}.{}",
Glsl::from(&*expr.base),
expr.member.to_string()
))
}
}
impl TryFrom<ExprField> for YaslExprField {
type Error = Error;
fn try_from(f: ExprField) -> Result<Self> {
let base = Box::new((*f.base).try_into()?);
let member = match f.member {
syn::Member::Named(i) => i.into(),
syn::Member::Unnamed(i) => Err(Error::new(i.span(), "Expected Ident"))?,
};
Ok(Self { base, member })
}
}
|
#[doc = "Register `DDRPHYC_DTPR1` reader"]
pub type R = crate::R<DDRPHYC_DTPR1_SPEC>;
#[doc = "Register `DDRPHYC_DTPR1` writer"]
pub type W = crate::W<DDRPHYC_DTPR1_SPEC>;
#[doc = "Field `TAOND` reader - TAOND"]
pub type TAOND_R = crate::FieldReader;
#[doc = "Field `TAOND` writer - TAOND"]
pub type TAOND_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `TRTW` reader - TRTW"]
pub type TRTW_R = crate::BitReader;
#[doc = "Field `TRTW` writer - TRTW"]
pub type TRTW_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TFAW` reader - TFAW"]
pub type TFAW_R = crate::FieldReader;
#[doc = "Field `TFAW` writer - TFAW"]
pub type TFAW_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 6, O>;
#[doc = "Field `TMOD` reader - TMOD"]
pub type TMOD_R = crate::FieldReader;
#[doc = "Field `TMOD` writer - TMOD"]
pub type TMOD_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `TRTODT` reader - TRTODT"]
pub type TRTODT_R = crate::BitReader;
#[doc = "Field `TRTODT` writer - TRTODT"]
pub type TRTODT_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TRFC` reader - TRFC"]
pub type TRFC_R = crate::FieldReader;
#[doc = "Field `TRFC` writer - TRFC"]
pub type TRFC_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>;
#[doc = "Field `TDQSCKMIN` reader - TDQSCKMIN"]
pub type TDQSCKMIN_R = crate::FieldReader;
#[doc = "Field `TDQSCKMIN` writer - TDQSCKMIN"]
pub type TDQSCKMIN_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O>;
#[doc = "Field `TDQSCKMAX` reader - TDQSCKMAX"]
pub type TDQSCKMAX_R = crate::FieldReader;
#[doc = "Field `TDQSCKMAX` writer - TDQSCKMAX"]
pub type TDQSCKMAX_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O>;
impl R {
#[doc = "Bits 0:1 - TAOND"]
#[inline(always)]
pub fn taond(&self) -> TAOND_R {
TAOND_R::new((self.bits & 3) as u8)
}
#[doc = "Bit 2 - TRTW"]
#[inline(always)]
pub fn trtw(&self) -> TRTW_R {
TRTW_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bits 3:8 - TFAW"]
#[inline(always)]
pub fn tfaw(&self) -> TFAW_R {
TFAW_R::new(((self.bits >> 3) & 0x3f) as u8)
}
#[doc = "Bits 9:10 - TMOD"]
#[inline(always)]
pub fn tmod(&self) -> TMOD_R {
TMOD_R::new(((self.bits >> 9) & 3) as u8)
}
#[doc = "Bit 11 - TRTODT"]
#[inline(always)]
pub fn trtodt(&self) -> TRTODT_R {
TRTODT_R::new(((self.bits >> 11) & 1) != 0)
}
#[doc = "Bits 16:23 - TRFC"]
#[inline(always)]
pub fn trfc(&self) -> TRFC_R {
TRFC_R::new(((self.bits >> 16) & 0xff) as u8)
}
#[doc = "Bits 24:26 - TDQSCKMIN"]
#[inline(always)]
pub fn tdqsckmin(&self) -> TDQSCKMIN_R {
TDQSCKMIN_R::new(((self.bits >> 24) & 7) as u8)
}
#[doc = "Bits 27:29 - TDQSCKMAX"]
#[inline(always)]
pub fn tdqsckmax(&self) -> TDQSCKMAX_R {
TDQSCKMAX_R::new(((self.bits >> 27) & 7) as u8)
}
}
impl W {
#[doc = "Bits 0:1 - TAOND"]
#[inline(always)]
#[must_use]
pub fn taond(&mut self) -> TAOND_W<DDRPHYC_DTPR1_SPEC, 0> {
TAOND_W::new(self)
}
#[doc = "Bit 2 - TRTW"]
#[inline(always)]
#[must_use]
pub fn trtw(&mut self) -> TRTW_W<DDRPHYC_DTPR1_SPEC, 2> {
TRTW_W::new(self)
}
#[doc = "Bits 3:8 - TFAW"]
#[inline(always)]
#[must_use]
pub fn tfaw(&mut self) -> TFAW_W<DDRPHYC_DTPR1_SPEC, 3> {
TFAW_W::new(self)
}
#[doc = "Bits 9:10 - TMOD"]
#[inline(always)]
#[must_use]
pub fn tmod(&mut self) -> TMOD_W<DDRPHYC_DTPR1_SPEC, 9> {
TMOD_W::new(self)
}
#[doc = "Bit 11 - TRTODT"]
#[inline(always)]
#[must_use]
pub fn trtodt(&mut self) -> TRTODT_W<DDRPHYC_DTPR1_SPEC, 11> {
TRTODT_W::new(self)
}
#[doc = "Bits 16:23 - TRFC"]
#[inline(always)]
#[must_use]
pub fn trfc(&mut self) -> TRFC_W<DDRPHYC_DTPR1_SPEC, 16> {
TRFC_W::new(self)
}
#[doc = "Bits 24:26 - TDQSCKMIN"]
#[inline(always)]
#[must_use]
pub fn tdqsckmin(&mut self) -> TDQSCKMIN_W<DDRPHYC_DTPR1_SPEC, 24> {
TDQSCKMIN_W::new(self)
}
#[doc = "Bits 27:29 - TDQSCKMAX"]
#[inline(always)]
#[must_use]
pub fn tdqsckmax(&mut self) -> TDQSCKMAX_W<DDRPHYC_DTPR1_SPEC, 27> {
TDQSCKMAX_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 = "DDRPHYC DTP register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ddrphyc_dtpr1::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 [`ddrphyc_dtpr1::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct DDRPHYC_DTPR1_SPEC;
impl crate::RegisterSpec for DDRPHYC_DTPR1_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`ddrphyc_dtpr1::R`](R) reader structure"]
impl crate::Readable for DDRPHYC_DTPR1_SPEC {}
#[doc = "`write(|w| ..)` method takes [`ddrphyc_dtpr1::W`](W) writer structure"]
impl crate::Writable for DDRPHYC_DTPR1_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets DDRPHYC_DTPR1 to value 0x0a03_0090"]
impl crate::Resettable for DDRPHYC_DTPR1_SPEC {
const RESET_VALUE: Self::Ux = 0x0a03_0090;
}
|
fn main() {
println!("Hello world");
let immutable_variable = 12;
let imut_var_with_type: i32 = 12;
let mut mutable_variable = 12;
let my_bool = true;
let my_char = 'b';
println!("Print a variable: {}, like this", my_bool);
let (var_1, var_2) = ("my_var1", 12);
println!(
"Print this variable: {0}, again: {0}, and this one: {1}",
my_char, my_bool
);
println!("Format a float to 2 decimal places: {:.2}", 1.234);
println!(
"Convert to binary: {:b}, hexidecimal: {:x}, octal: {:o}",
12, 12, 12
);
println!("{myArg}", myArg = "Hello");
println!("abs(-12) = {}", 12i32.abs());
println!("12^34 = {}", 12i128.pow(34));
println!("sqrt 12 = {}", 12f32.sqrt());
println!("cbrt 12 = {}", 12f32.cbrt());
println!("Round 12.34 = {}", 12.34f32.round());
println!("Floor 12.34 = {}", 12.34f32.floor());
println!("Ceiling 12.34 = {}", 12.34f32.ceil());
println!("e ^ 12 = {}", 12f32.exp());
println!("log(12) = {}", 12f32.ln());
println!("12 to Radians = {}", 12f32.to_radians());
println!("Pi to Degrees = {}", 3.13f32.to_degrees());
println!("Max 12, 34 = {}", 12i32.max(34i32));
println!("Min 12, 34 = {}", 12i32.min(34i32));
let age = 19;
let _can_vote = if age >= 18 { true } else { false };
let mut x = 0;
loop {
println!("Loop: {}", x);
if x == 10 {
break;
}
x += 1;
}
let mut y = 0;
while y < 10 {
println!("While: {}", y);
y += 1;
}
for z in 1..10 {
println!("For: {}", z);
}
let my_string = "This is an example string.";
println!("Length: {}", my_string.len());
let (first, second) = my_string.split_at(9);
println!("First: {}, Second: {}", first, second);
for c in my_string.chars() {
println!("{}", c);
}
for (i, c) in my_string.chars().enumerate() {
println!("Index: {}, Character: {}", i, c);
}
let split_ws = my_string.split_whitespace();
for w in split_ws {
println!("{}", w);
}
println!("Find 'example': {}", my_string.contains("example"));
} |
#[derive(Debug, Clone, Copy)]
pub struct DebugSettings {
pub(crate) view_info: bool,
pub(crate) cursor_info: bool,
pub(crate) egui_inspection: bool,
pub(crate) egui_settings: bool,
pub(crate) egui_memory: bool,
}
impl std::default::Default for DebugSettings {
fn default() -> Self {
Self {
view_info: false,
cursor_info: false,
egui_inspection: false,
egui_settings: false,
egui_memory: false,
}
}
}
impl DebugSettings {
pub fn ui(&mut self, ui: &mut egui::Ui) {
ui.checkbox(&mut self.view_info, "Viewport Info");
ui.checkbox(&mut self.cursor_info, "Cursor Info");
ui.separator();
ui.label("Egui Debug Windows");
ui.checkbox(&mut self.egui_inspection, "Inspection");
ui.checkbox(&mut self.egui_settings, "Settings");
ui.checkbox(&mut self.egui_memory, "Memory");
}
}
|
use azure_storage::core::prelude::*;
use azure_storage::table::prelude::*;
use futures::stream::StreamExt;
use serde::{Deserialize, Serialize};
use std::error::Error;
#[derive(Debug, Clone, Serialize, Deserialize)]
struct MyEntity {
#[serde(rename = "PartitionKey")]
pub city: String,
pub name: String,
#[serde(rename = "RowKey")]
pub surname: String,
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
// First we retrieve the account name and master key from environment variables.
let account =
std::env::var("STORAGE_ACCOUNT").expect("Set env variable STORAGE_ACCOUNT first!");
let master_key =
std::env::var("STORAGE_MASTER_KEY").expect("Set env variable STORAGE_MASTER_KEY first!");
let table_name = std::env::args()
.nth(1)
.expect("please specify the table name as first command line parameter");
let http_client = azure_core::new_http_client();
let storage_account_client =
StorageAccountClient::new_access_key(http_client.clone(), &account, &master_key);
let table_service = storage_account_client
.as_storage_client()
.as_table_service_client()?;
let table = table_service.as_table_client(table_name);
let response = table.create().execute().await?;
println!("response = {:?}\n", response);
let mut entity = MyEntity {
city: "Milan".to_owned(),
name: "Francesco".to_owned(),
surname: "Cogno".to_owned(),
};
let partition_key_client = table.as_partition_key_client(&entity.city);
let mut transaction = Transaction::default();
transaction.add(table.insert().to_transaction_operation(&entity)?);
entity.surname = "Doe".to_owned();
transaction.add(table.insert().to_transaction_operation(&entity)?);
entity.surname = "Karl".to_owned();
transaction.add(table.insert().to_transaction_operation(&entity)?);
entity.surname = "Potter".to_owned();
let entity_client = partition_key_client.as_entity_client(&entity.surname)?;
transaction.add(
entity_client
.insert_or_replace()
.to_transaction_operation(&entity)?,
);
let response = partition_key_client
.submit_transaction()
.execute(&transaction)
.await?;
println!("response = {:?}\n", response);
let response = entity_client.delete().execute().await?;
println!("response = {:?}\n", response);
let response = table.insert().return_entity(false).execute(&entity).await?;
println!("response = {:?}\n", response);
// Get an entity from the table
let response = entity_client.get().execute().await?;
println!("response = {:?}\n", response);
let mut entity: MyEntity = response.entity;
entity.city = "Rome".to_owned();
let response = table.insert().return_entity(true).execute(&entity).await?;
println!("response = {:?}\n", response);
let entity_client = table
.as_partition_key_client(&entity.city)
.as_entity_client(&entity.surname)?;
// update the name passing the Etag received from the previous call.
entity.name = "Ryan".to_owned();
let response = entity_client
.update()
.execute(&entity, &(response.etag.into()))
.await?;
println!("response = {:?}\n", response);
// now we perform an upsert
entity.name = "Carl".to_owned();
let response = entity_client.insert_or_replace().execute(&entity).await?;
println!("response = {:?}\n", response);
let mut stream = Box::pin(table_service.list().top(2).stream());
while let Some(response) = stream.next().await {
println!("response = {:?}\n", response);
}
let mut stream = Box::pin(
table
.query()
.filter("Name = 'Carl'")
.top(2)
.stream::<MyEntity>(),
);
while let Some(response) = stream.next().await {
println!("response = {:?}\n", response);
}
let response = table.delete().execute().await?;
println!("response = {:?}\n", response);
Ok(())
}
|
use std::collections::HashMap;
pub struct SymbolTable {
class_table: HashMap<String, JackVariable>,
subroutine_table: HashMap<String, JackVariable>,
static_idx: usize,
field_idx: usize,
arg_idx: usize,
var_idx: usize,
}
impl SymbolTable {
pub fn new() -> Self {
SymbolTable {
class_table: HashMap::new(),
subroutine_table: HashMap::new(),
static_idx: 0,
field_idx: 0,
arg_idx: 0,
var_idx: 0,
}
}
pub fn startSubroutine(&mut self) {
self.subroutine_table.clear();
self.arg_idx = 0;
self.var_idx = 0;
}
pub fn define(&mut self, v_name: &str, v_type: &str, v_kind: &VarKind) {
let name = v_name.to_string();
let t = v_type.to_string();
match v_kind {
VarKind::Static => {
self.class_table.insert(name, JackVariable {
var_type: t,
var_kind: VarKind::Static,
number: self.static_idx,
});
self.static_idx += 1;
},
VarKind::Field => {
self.class_table.insert(name, JackVariable {
var_type: t,
var_kind: VarKind::Field,
number: self.field_idx,
});
self.field_idx += 1;
}
VarKind::Argument => {
self.subroutine_table.insert(name, JackVariable {
var_type: t,
var_kind: VarKind::Argument,
number: self.arg_idx,
});
self.arg_idx += 1;
}
VarKind::Var => {
self.subroutine_table.insert(name, JackVariable {
var_type: t,
var_kind: VarKind::Var,
number: self.var_idx,
});
self.var_idx += 1;
}
}
}
pub fn contains(&self, name: &str) -> bool {
self.conteins_class(name) || self.contains_subroutine(name)
}
pub fn conteins_class(&self, name: &str) -> bool {
self.class_table.contains_key(name)
}
pub fn contains_subroutine(&self, name: &str) -> bool {
self.subroutine_table.contains_key(name)
}
pub fn var_count(&self, kind: &VarKind) -> usize {
match kind {
VarKind::Static => self.static_idx,
VarKind::Field => self.field_idx,
VarKind::Argument => self.arg_idx,
VarKind::Var => self.var_idx,
}
}
pub fn kind_of(&self, name: &str) -> Option<&VarKind> {
if let Some(var) = self.get_variable(name) {
Some(&var.var_kind)
} else {
None
}
}
pub fn type_of(&self, name: &str) -> Option<String> {
if let Some(var) = self.get_variable(name) {
Some(var.var_type.to_string())
} else {
None
}
}
pub fn index_of(&self, name: &str) -> Option<usize> {
if let Some(var) = self.get_variable(name) {
Some(var.number)
} else {
None
}
}
fn get_variable(&self, name: &str) -> Option<&JackVariable> {
if self.class_table.contains_key(name) {
self.class_table.get(name)
} else {
self.subroutine_table.get(name)
}
}
pub fn debug_print_class_table(&self) {
println!("*** CLASS VARIABLES *** ");
for class in &self.class_table {
println!("{:?}", class);
}
println!();
}
pub fn debug_print_subroutine_table(&self) {
println!("*** SUBROUTINE VARIABLES ***");
for subroutine in &self.subroutine_table {
println!("{:?}", subroutine);
}
println!();
}
}
#[derive(Debug)]
struct JackVariable {
var_type: String,
var_kind: VarKind,
number: usize,
}
#[derive(Debug, PartialEq, Clone)]
pub enum VarKind {
Static,
Field,
Argument,
Var,
}
impl VarKind {
pub fn to_string(&self) -> String {
match self {
VarKind::Static => "static".to_string(),
VarKind::Field => "this".to_string(),
VarKind::Argument => "argument".to_string(),
VarKind::Var => "local".to_string(),
}
}
}
|
use super::congestion::CongestionController;
use super::crypto::{
fulfillment_to_condition, generate_condition, generate_fulfillment, random_condition,
random_u32,
};
use super::data_money_stream::DataMoneyStream;
use super::packet::*;
use super::StreamPacket;
use bytes::{Bytes, BytesMut};
use chrono::{Duration, Utc};
use futures::sync::mpsc::{UnboundedReceiver, UnboundedSender};
use futures::task;
use futures::task::Task;
use futures::{Async, Future, Poll, Stream};
use hex;
use ilp::{parse_f08_error, IlpFulfill, IlpPacket, IlpPrepare, IlpReject, PacketType};
use num_bigint::BigUint;
use num_traits::ToPrimitive;
use parking_lot::{Mutex, RwLock};
use plugin::IlpRequest;
use std::cmp::min;
use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
pub struct CloseFuture {
conn: Connection,
}
impl Future for CloseFuture {
type Item = ();
type Error = ();
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
trace!("Polling to see whether connection was closed");
self.conn.try_handle_incoming()?;
if self.conn.state.load(Ordering::SeqCst) == ConnectionState::Closed as usize {
trace!("Connection was closed, resolving close future");
Ok(Async::Ready(()))
} else {
self.conn.try_send()?;
trace!("Connection wasn't closed yet, returning NotReady");
Ok(Async::NotReady)
}
}
}
#[derive(Clone)]
pub struct Connection {
// TODO is it okay for this to be an AtomicUsize instead of a RwLock around the enum?
// it ran into deadlocks with the RwLock
state: Arc<AtomicUsize>,
// TODO should this be a bounded sender? Don't want too many outgoing packets in the queue
outgoing: UnboundedSender<IlpRequest>,
incoming: Arc<Mutex<UnboundedReceiver<IlpRequest>>>,
shared_secret: Bytes,
source_account: Arc<String>,
destination_account: Arc<String>,
next_stream_id: Arc<AtomicUsize>,
next_packet_sequence: Arc<AtomicUsize>,
streams: Arc<RwLock<HashMap<u64, DataMoneyStream>>>,
closed_streams: Arc<RwLock<HashSet<u64>>>,
pending_outgoing_packets: Arc<Mutex<HashMap<u32, OutgoingPacketRecord>>>,
new_streams: Arc<Mutex<VecDeque<u64>>>,
frames_to_resend: Arc<Mutex<Vec<Frame>>>,
// This is used to wake the task polling for incoming streams
recv_task: Arc<Mutex<Option<Task>>>,
// TODO add connection-level stats
congestion_controller: Arc<Mutex<CongestionController>>,
}
struct OutgoingPacketRecord {
original_amount: u64,
original_packet: StreamPacket,
}
#[derive(PartialEq, Eq, Debug)]
#[repr(usize)]
enum ConnectionState {
Opening,
Open,
Closing,
CloseSent,
Closed,
}
impl Connection {
pub fn new(
outgoing: UnboundedSender<IlpRequest>,
incoming: UnboundedReceiver<IlpRequest>,
shared_secret: Bytes,
source_account: String,
destination_account: String,
is_server: bool,
) -> Self {
let next_stream_id = if is_server { 2 } else { 1 };
let conn = Connection {
state: Arc::new(AtomicUsize::new(ConnectionState::Opening as usize)),
outgoing,
incoming: Arc::new(Mutex::new(incoming)),
shared_secret,
source_account: Arc::new(source_account),
destination_account: Arc::new(destination_account),
next_stream_id: Arc::new(AtomicUsize::new(next_stream_id)),
next_packet_sequence: Arc::new(AtomicUsize::new(1)),
streams: Arc::new(RwLock::new(HashMap::new())),
closed_streams: Arc::new(RwLock::new(HashSet::new())),
pending_outgoing_packets: Arc::new(Mutex::new(HashMap::new())),
new_streams: Arc::new(Mutex::new(VecDeque::new())),
frames_to_resend: Arc::new(Mutex::new(Vec::new())),
recv_task: Arc::new(Mutex::new(None)),
congestion_controller: Arc::new(Mutex::new(CongestionController::default())),
};
// TODO figure out a better way to send the initial packet - get the exchange rate and wait for response
if !is_server {
conn.send_handshake();
}
// TODO wait for handshake reply before setting state to open
conn.state
.store(ConnectionState::Open as usize, Ordering::SeqCst);
conn
}
pub fn create_stream(&self) -> DataMoneyStream {
let id = self.next_stream_id.fetch_add(2, Ordering::SeqCst) as u64;
let stream = DataMoneyStream::new(id, self.clone());
(*self.streams.write()).insert(id, stream.clone());
debug!("Created stream {}", id);
stream
}
pub fn close(&self) -> CloseFuture {
debug!("Closing connection");
self.state
.store(ConnectionState::Closing as usize, Ordering::SeqCst);
// TODO make sure we don't send stream close frames for every stream
for stream in (*self.streams.read()).values() {
stream.set_closing();
}
CloseFuture { conn: self.clone() }
}
pub(super) fn is_closed(&self) -> bool {
self.state.load(Ordering::SeqCst) == ConnectionState::Closed as usize
}
pub(super) fn try_send(&self) -> Result<(), ()> {
// Loop until we don't need to send any more packets or doing so would
// violate limits imposed by the congestion controller
loop {
if self.is_closed() {
trace!("Connection was closed, not sending any more packets");
return Ok(());
}
trace!("Checking if we should send an outgoing packet");
let mut outgoing_amount: u64 = 0;
let mut frames: Vec<Frame> = Vec::new();
let mut closed_streams: Vec<u64> = Vec::new();
let mut congestion_controller = self.congestion_controller.lock();
let max_packet_amount = congestion_controller.get_max_amount();
let streams = self.streams.read();
for stream in streams.values() {
// Send money
if max_packet_amount > 0 {
trace!("Checking if stream {} has money or data to send", stream.id);
let stream_amount = stream.money.send_max()
- stream.money.pending()
- stream.money.total_sent();
let amount_to_send = min(stream_amount, max_packet_amount - outgoing_amount);
if amount_to_send > 0 {
trace!("Stream {} sending {}", stream.id, amount_to_send);
stream.money.add_to_pending(amount_to_send);
outgoing_amount += amount_to_send;
frames.push(Frame::StreamMoney(StreamMoneyFrame {
stream_id: BigUint::from(stream.id),
shares: BigUint::from(amount_to_send),
}));
}
}
// Send data
// TODO don't send too much data
let max_data: usize = 1_000_000_000;
if let Some((data, offset)) = stream.data.get_outgoing_data(max_data) {
trace!(
"Stream {} has {} bytes to send (offset: {})",
stream.id,
data.len(),
offset
);
frames.push(Frame::StreamData(StreamDataFrame {
stream_id: BigUint::from(stream.id),
data,
offset: BigUint::from(offset),
}))
} else {
trace!("Stream {} does not have any data to send", stream.id);
}
// Inform other side about closing streams
if stream.is_closing() {
trace!("Sending stream close frame for stream {}", stream.id);
frames.push(Frame::StreamClose(StreamCloseFrame {
stream_id: BigUint::from(stream.id),
code: ErrorCode::NoError,
message: String::new(),
}));
closed_streams.push(stream.id);
stream.set_closed();
// TODO don't block
(*self.closed_streams.write()).insert(stream.id);
}
}
if self.state.load(Ordering::SeqCst) == ConnectionState::Closing as usize {
trace!("Sending connection close frame");
frames.push(Frame::ConnectionClose(ConnectionCloseFrame {
code: ErrorCode::NoError,
message: String::new(),
}));
self.state
.store(ConnectionState::CloseSent as usize, Ordering::SeqCst);
}
if frames.is_empty() {
trace!("Not sending packet, no frames need to be sent");
return Ok(());
}
// Note we need to remove them after we've given up the read lock on self.streams
if !closed_streams.is_empty() {
let mut streams = self.streams.write();
for stream_id in closed_streams.iter() {
debug!("Removed stream {}", stream_id);
streams.remove(&stream_id);
}
}
let stream_packet = StreamPacket {
sequence: self.next_packet_sequence.fetch_add(1, Ordering::SeqCst) as u64,
ilp_packet_type: PacketType::IlpPrepare,
prepare_amount: 0, // TODO set min amount
frames,
};
let encrypted = stream_packet.to_encrypted(&self.shared_secret).unwrap();
let condition = generate_condition(&self.shared_secret, &encrypted);
let prepare = IlpPrepare::new(
self.destination_account.to_string(),
outgoing_amount,
condition,
// TODO use less predictable timeout
Utc::now() + Duration::seconds(30),
encrypted,
);
let request_id = random_u32();
let request = (request_id, IlpPacket::Prepare(prepare));
debug!(
"Sending outgoing request {} with stream packet: {:?}",
request_id, stream_packet
);
congestion_controller.prepare(request_id, outgoing_amount);
(*self.pending_outgoing_packets.lock()).insert(
request_id,
OutgoingPacketRecord {
original_amount: outgoing_amount,
original_packet: stream_packet.clone(),
},
);
self.outgoing.unbounded_send(request).map_err(|err| {
error!("Error sending outgoing packet: {:?}", err);
})?;
}
}
pub(super) fn try_handle_incoming(&self) -> Result<(), ()> {
// Handle incoming requests until there are no more
// Note: looping until we get Async::NotReady tells Tokio to wake us up when there are more incoming requests
loop {
if self.is_closed() {
trace!("Connection was closed, not handling any more incoming packets");
return Ok(());
}
trace!("Polling for incoming requests");
let next = (*self.incoming.lock()).poll();
match next {
Ok(Async::Ready(Some((request_id, packet)))) => {
match packet {
IlpPacket::Prepare(prepare) => {
self.handle_incoming_prepare(request_id, prepare)?
}
IlpPacket::Fulfill(fulfill) => self.handle_fulfill(request_id, fulfill)?,
IlpPacket::Reject(reject) => self.handle_reject(request_id, reject)?,
}
self.try_send()?
}
Ok(Async::Ready(None)) => {
error!("Incoming stream closed");
// TODO should this error?
return Ok(());
}
Ok(Async::NotReady) => {
trace!("No more incoming requests for now");
return Ok(());
}
Err(err) => {
error!("Error polling incoming request stream: {:?}", err);
return Err(());
}
};
}
}
fn handle_incoming_prepare(&self, request_id: u32, prepare: IlpPrepare) -> Result<(), ()> {
debug!("Handling incoming prepare {}", request_id);
let response_frames: Vec<Frame> = Vec::new();
let fulfillment = generate_fulfillment(&self.shared_secret, &prepare.data);
let condition = fulfillment_to_condition(&fulfillment);
let is_fulfillable = condition == prepare.execution_condition;
// TODO avoid copying data
let stream_packet =
StreamPacket::from_encrypted(&self.shared_secret, BytesMut::from(prepare.data));
if stream_packet.is_err() {
warn!(
"Got Prepare with data that we cannot parse. Rejecting request {}",
request_id
);
self.outgoing
.unbounded_send((
request_id,
IlpPacket::Reject(IlpReject::new("F02", "", "", Bytes::new())),
)).map_err(|err| {
error!("Error sending Reject {} {:?}", request_id, err);
})?;
return Ok(());
}
let stream_packet = stream_packet.unwrap();
debug!(
"Prepare {} had stream packet: {:?}",
request_id, stream_packet
);
// Handle new streams
for frame in stream_packet.frames.iter() {
match frame {
Frame::StreamMoney(frame) => {
self.handle_new_stream(frame.stream_id.to_u64().unwrap());
}
Frame::StreamData(frame) => {
self.handle_new_stream(frame.stream_id.to_u64().unwrap());
}
// TODO handle other frames that open streams
_ => {}
}
}
// Count up the total number of money "shares" in the packet
let total_money_shares: u64 = stream_packet.frames.iter().fold(0, |sum, frame| {
if let Frame::StreamMoney(frame) = frame {
sum + frame.shares.to_u64().unwrap()
} else {
sum
}
});
// Handle incoming money
if is_fulfillable {
for frame in stream_packet.frames.iter() {
if let Frame::StreamMoney(frame) = frame {
// TODO only add money to incoming if sending the fulfill is successful
// TODO make sure all other checks pass first
let stream_id = frame.stream_id.to_u64().unwrap();
let streams = self.streams.read();
let stream = streams.get(&stream_id).unwrap();
let amount: u64 =
frame.shares.to_u64().unwrap() * prepare.amount / total_money_shares;
debug!("Stream {} received {}", stream_id, amount);
stream.money.add_received(amount);
stream.money.try_wake_polling();
}
}
}
self.handle_incoming_data(&stream_packet).unwrap();
self.handle_stream_closes(&stream_packet);
self.handle_connection_close(&stream_packet);
// Fulfill or reject Preapre
if is_fulfillable {
let response_packet = StreamPacket {
sequence: stream_packet.sequence,
ilp_packet_type: PacketType::IlpFulfill,
prepare_amount: prepare.amount,
frames: response_frames,
};
let encrypted_response = response_packet.to_encrypted(&self.shared_secret).unwrap();
let fulfill =
IlpPacket::Fulfill(IlpFulfill::new(fulfillment.clone(), encrypted_response));
debug!(
"Fulfilling request {} with fulfillment: {} and encrypted stream packet: {:?}",
request_id,
hex::encode(&fulfillment[..]),
response_packet
);
self.outgoing.unbounded_send((request_id, fulfill)).unwrap();
} else {
let response_packet = StreamPacket {
sequence: stream_packet.sequence,
ilp_packet_type: PacketType::IlpReject,
prepare_amount: prepare.amount,
frames: response_frames,
};
let encrypted_response = response_packet.to_encrypted(&self.shared_secret).unwrap();
let reject = IlpPacket::Reject(IlpReject::new("F99", "", "", encrypted_response));
debug!(
"Rejecting request {} and including encrypted stream packet {:?}",
request_id, response_packet
);
self.outgoing.unbounded_send((request_id, reject)).unwrap();
}
Ok(())
}
fn handle_new_stream(&self, stream_id: u64) {
// TODO make sure they don't open streams with our number (even or odd, depending on whether we're the client or server)
let is_new = !(*self.streams.read()).contains_key(&stream_id);
let already_closed = (*self.closed_streams.read()).contains(&stream_id);
if is_new && !already_closed {
debug!("Got new stream {}", stream_id);
let stream = DataMoneyStream::new(stream_id, self.clone());
(*self.streams.write()).insert(stream_id, stream);
(*self.new_streams.lock()).push_back(stream_id);
}
}
fn handle_incoming_data(&self, stream_packet: &StreamPacket) -> Result<(), ()> {
for frame in stream_packet.frames.iter() {
if let Frame::StreamData(frame) = frame {
let stream_id = frame.stream_id.to_u64().unwrap();
let streams = self.streams.read();
let stream = streams.get(&stream_id).unwrap();
// TODO make sure the offset number isn't too big
let data = frame.data.clone();
let offset = frame.offset.to_usize().unwrap();
debug!(
"Stream {} got {} bytes of incoming data",
stream.id,
data.len()
);
stream.data.push_incoming_data(data, offset)?;
stream.data.try_wake_polling();
}
}
Ok(())
}
fn handle_stream_closes(&self, stream_packet: &StreamPacket) {
for frame in stream_packet.frames.iter() {
if let Frame::StreamClose(frame) = frame {
let stream_id = frame.stream_id.to_u64().unwrap();
debug!("Remote closed stream {}", stream_id);
let streams = self.streams.read();
let stream = streams.get(&stream_id).unwrap();
// TODO finish sending the money and data first
stream.set_closed();
}
}
}
fn handle_connection_close(&self, stream_packet: &StreamPacket) {
for frame in stream_packet.frames.iter() {
if let Frame::ConnectionClose(frame) = frame {
debug!(
"Remote closed connection with code: {:?}: {}",
frame.code, frame.message
);
self.close_now();
}
}
}
fn close_now(&self) {
debug!("Closing connection now");
self.state
.store(ConnectionState::Closed as usize, Ordering::SeqCst);
for stream in (*self.streams.read()).values() {
stream.set_closed();
}
(*self.incoming.lock()).close();
// Wake up the task polling for incoming streams so it ends
self.try_wake_polling();
}
fn handle_fulfill(&self, request_id: u32, fulfill: IlpFulfill) -> Result<(), ()> {
debug!(
"Request {} was fulfilled with fulfillment: {}",
request_id,
hex::encode(&fulfill.fulfillment[..])
);
let OutgoingPacketRecord {
original_amount,
original_packet,
} = (*self.pending_outgoing_packets.lock())
.remove(&request_id)
.unwrap();
let response = {
let decrypted =
StreamPacket::from_encrypted(&self.shared_secret, BytesMut::from(fulfill.data))
.ok();
if let Some(packet) = decrypted {
if packet.sequence != original_packet.sequence {
warn!("Got Fulfill with stream packet whose sequence does not match the original request. Request ID: {}, sequence: {}, fulfill packet: {:?}", request_id, original_packet.sequence, packet);
None
} else if packet.ilp_packet_type != PacketType::IlpFulfill {
warn!("Got Fulfill with stream packet that should have been on a differen type of ILP packet. Request ID: {}, fulfill packet: {:?}", request_id, packet);
None
} else {
trace!("Got Fulfill with stream packet: {:?}", packet);
Some(packet)
}
} else {
None
}
};
(*self.congestion_controller.lock()).fulfill(request_id);
let total_delivered = {
match response.as_ref() {
Some(packet) => packet.prepare_amount,
None => 0,
}
};
for frame in original_packet.frames.iter() {
if let Frame::StreamMoney(frame) = frame {
let stream_id = frame.stream_id.to_u64().unwrap();
let streams = self.streams.read();
let stream = streams.get(&stream_id).unwrap();
let shares = frame.shares.to_u64().unwrap();
stream.money.pending_to_sent(shares);
let amount_delivered: u64 = total_delivered * shares / original_amount;
stream.money.add_delivered(amount_delivered);
}
}
if let Some(packet) = response.as_ref() {
self.handle_incoming_data(&packet)?;
}
// TODO handle response frames
// Close the connection if they sent a close frame or we sent one and they ACKed it
if let Some(packet) = response {
self.handle_connection_close(&packet);
}
let we_sent_close_frame = original_packet.frames.iter().any(|frame| {
if let Frame::ConnectionClose(_) = frame {
true
} else {
false
}
});
if we_sent_close_frame {
debug!("ConnectionClose frame was ACKed, closing connection now");
self.close_now();
}
Ok(())
}
fn handle_reject(&self, request_id: u32, reject: IlpReject) -> Result<(), ()> {
debug!(
"Request {} was rejected with code: {}",
request_id, reject.code
);
let entry = (*self.pending_outgoing_packets.lock()).remove(&request_id);
if entry.is_none() {
return Ok(());
}
let OutgoingPacketRecord {
original_amount,
mut original_packet,
} = entry.unwrap();
// Handle F08 errors, which communicate the maximum packet amount
if let Some(err_details) = parse_f08_error(&reject) {
let max_packet_amount: u64 =
original_amount * err_details.max_amount / err_details.amount_received;
debug!("Found path Maximum Packet Amount: {}", max_packet_amount);
(*self.congestion_controller.lock()).set_max_packet_amount(max_packet_amount);
}
// Parse STREAM response packet from F99 errors
let response = {
if &reject.code == "F99" && !reject.data.is_empty() {
match StreamPacket::from_encrypted(&self.shared_secret, BytesMut::from(reject.data))
{
Ok(packet) => {
if packet.sequence != original_packet.sequence {
warn!("Got Reject with stream packet whose sequence does not match the original request. Request ID: {}, sequence: {}, packet: {:?}", request_id, original_packet.sequence, packet);
None
} else if packet.ilp_packet_type != PacketType::IlpReject {
warn!("Got Reject with stream packet that should have been on a differen type of ILP packet. Request ID: {}, packet: {:?}", request_id, packet);
None
} else {
trace!("Got Reject with stream packet: {:?}", packet);
Some(packet)
}
}
Err(err) => {
warn!(
"Got encrypted response packet that we could not decrypt: {:?}",
err
);
None
}
}
} else {
None
}
};
(*self.congestion_controller.lock()).reject(request_id, &reject.code);
let streams = self.streams.read();
// Release pending money
for frame in original_packet.frames.iter() {
if let Frame::StreamMoney(frame) = frame {
let stream_id = frame.stream_id.to_u64().unwrap();
let stream = streams.get(&stream_id).unwrap();
let shares = frame.shares.to_u64().unwrap();
stream.money.subtract_from_pending(shares);
}
}
// TODO handle response frames
if let Some(packet) = response.as_ref() {
self.handle_incoming_data(&packet)?;
self.handle_connection_close(&packet);
}
// Only resend frames if they didn't get to the receiver
if response.is_none() {
let mut frames_to_resend = self.frames_to_resend.lock();
while !original_packet.frames.is_empty() {
match original_packet.frames.pop().unwrap() {
Frame::StreamData(frame) => frames_to_resend.push(Frame::StreamData(frame)),
Frame::StreamClose(frame) => frames_to_resend.push(Frame::StreamClose(frame)),
Frame::ConnectionClose(frame) => {
frames_to_resend.push(Frame::ConnectionClose(frame))
}
_ => {}
}
}
}
Ok(())
}
fn send_handshake(&self) {
let sequence = self.next_packet_sequence.fetch_add(1, Ordering::SeqCst) as u64;
let packet = StreamPacket {
sequence,
ilp_packet_type: PacketType::IlpPrepare,
prepare_amount: 0,
frames: vec![Frame::ConnectionNewAddress(ConnectionNewAddressFrame {
source_account: self.source_account.to_string(),
})],
};
self.send_unfulfillable_prepare(&packet);
}
// TODO wait for response
fn send_unfulfillable_prepare(&self, stream_packet: &StreamPacket) -> () {
let request_id = random_u32();
let prepare = IlpPacket::Prepare(IlpPrepare::new(
// TODO do we need to clone this?
self.destination_account.to_string(),
0,
random_condition(),
Utc::now() + Duration::seconds(30),
stream_packet.to_encrypted(&self.shared_secret).unwrap(),
));
self.outgoing.unbounded_send((request_id, prepare)).unwrap();
}
fn try_wake_polling(&self) {
if let Some(task) = (*self.recv_task.lock()).take() {
debug!("Notifying incoming stream poller that it should wake up");
task.notify();
}
}
}
impl Stream for Connection {
type Item = DataMoneyStream;
type Error = ();
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
trace!("Polling for new incoming streams");
self.try_handle_incoming()?;
// Store the current task so that it can be woken up if the
// MoneyStream or DataStream poll for incoming packets and the connection is closed
*self.recv_task.lock() = Some(task::current());
let mut new_streams = self.new_streams.lock();
if let Some(stream_id) = new_streams.pop_front() {
let streams = self.streams.read();
Ok(Async::Ready(Some(streams.get(&stream_id).unwrap().clone())))
} else if self.is_closed() {
trace!("Connection was closed, no more incoming streams");
Ok(Async::Ready(None))
} else {
Ok(Async::NotReady)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use futures::sync::mpsc::unbounded;
fn test_conn() -> (
Connection,
UnboundedSender<IlpRequest>,
UnboundedReceiver<IlpRequest>,
) {
let (incoming_tx, incoming_rx) = unbounded::<IlpRequest>();
let (outgoing_tx, outgoing_rx) = unbounded::<IlpRequest>();
let conn = Connection::new(
outgoing_tx,
incoming_rx,
Bytes::from(&[0u8; 32][..]),
String::from("example.alice"),
String::from("example.bob"),
// Set as server so it doesn't bother sending the handshake
true,
);
(conn, incoming_tx, outgoing_rx)
}
mod max_packet_amount {
use super::*;
use futures::future::ok;
use futures::Sink;
use ilp::packet::create_f08_error;
use tokio::runtime::current_thread::block_on_all;
#[test]
fn discovery() {
let (conn, incoming, outgoing) = test_conn();
let mut stream = conn.create_stream();
// Send money
stream.money.start_send(100).unwrap();
let (request, outgoing) = outgoing.into_future().wait().unwrap();
let (request_id, _prepare) = request.unwrap();
// Respond with F08
let error = (request_id, IlpPacket::Reject(create_f08_error(100, 50)));
incoming.unbounded_send(error).unwrap();
block_on_all(ok(()).and_then(|_| conn.try_handle_incoming())).unwrap();
// Check that next packet is smaller
let (request, _outgoing) = outgoing.into_future().wait().unwrap();
let (_request_id, prepare) = request.unwrap();
if let IlpPacket::Prepare(prepare) = prepare {
assert_eq!(prepare.amount, 50);
} else {
assert!(false);
}
}
#[test]
fn discovery_with_exchange_rate() {
let (conn, incoming, outgoing) = test_conn();
let mut stream = conn.create_stream();
// Send money
stream.money.start_send(1000).unwrap();
let (request, outgoing) = outgoing.into_future().wait().unwrap();
let (request_id, _prepare) = request.unwrap();
// Respond with F08
let error = (request_id, IlpPacket::Reject(create_f08_error(542, 107)));
incoming.unbounded_send(error).unwrap();
block_on_all(ok(()).and_then(|_| conn.try_handle_incoming())).unwrap();
// Check that next packet is smaller
let (request, _outgoing) = outgoing.into_future().wait().unwrap();
let (_request_id, prepare) = request.unwrap();
if let IlpPacket::Prepare(prepare) = prepare {
assert_eq!(prepare.amount, 197);
} else {
assert!(false);
}
}
}
}
|
#[derive(Serialize, Deserialize, Debug, Default)]
pub struct Chat {
pub id: u64,
}
|
// use failure::Context;
// use failure::Fail;
pub use failure::ResultExt; // For .context()
pub use lazy_static::*;
pub use log::*;
pub use serde_derive::*;
pub use std::collections::{HashMap, HashSet, VecDeque};
pub use std::path::Path;
pub use std::path::PathBuf;
pub use std::rc::Rc;
pub type Result<T> = std::result::Result<T, failure::Error>;
#[cfg(test)]
mod tests {
#[test]
fn predule_test_dummy() {
assert_eq!(0, 0);
}
}
|
use std::io::prelude::*;
use std::fs::File;
use std::collections::HashMap;
use std::process::Command;
use {Result, Error};
pub use self::gpio::{
Pin,
PinInput,
PinOutput,
};
pub use self::fs::{
Selector,
GPIOSelector,
GPIOPinSelector
};
mod gpio;
mod fs;
#[derive(Copy, Clone, Debug)]
pub enum Edge {
NoInterrupt,
RisingEdge,
FallingEdge,
BothEdges
}
#[derive(Clone, Debug)]
pub struct CPUInfo(pub HashMap<String, String>);
pub fn cpuinfo() -> Result<CPUInfo> {
let mut f = try!(File::open("/proc/cpuinfo"));
let mut s = String::new();
let mut h = HashMap::new();
try!(f.read_to_string(&mut s));
let v: Vec<&str> = s.split("\n").collect();
for i in &v {
let l: Vec<&str> = i.splitn(2,":").collect();
if l.len() >= 2 {
h.insert(l[0].trim().to_string(), l[1].trim().to_string());
}
}
Ok(CPUInfo(h))
}
#[derive(Copy, Clone, Debug)]
pub struct Memory {
pub total: u32,
pub used: u32,
pub free: u32,
pub shared: u32,
pub buffers: u32,
pub cached: u32
}
pub fn memory() -> Result<Memory> {
let o = try!(Command::new("free").output());
let f = o.stdout;
let s = try!(String::from_utf8(f));
//try!(f.read_to_string(&mut s));
let v: Vec<&str> = s.split("\n").collect();
for i in &v {
let w: Vec<&str> = i.split(" ").filter(|&s| s.len() != 0).collect();
if w[0] == "Mem:" && w.len() == 7 {
let total = try!(w[1].parse::<u32>());
let used = try!(w[2].parse::<u32>());
let free = try!(w[3].parse::<u32>());
let shared = try!(w[4].parse::<u32>());
let buffers = try!(w[5].parse::<u32>());
let cached = try!(w[6].parse::<u32>());
return Ok(Memory { total: total, used: used, free: free, shared: shared, buffers: buffers, cached: cached })
}
};
Err(Error::UnexpectedError)
}
|
use std::cmp::{Eq, PartialEq};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::convert::Into;
use std::fmt;
use std::fs::File;
use std::hash::{Hash, Hasher};
use std::io::{Read, Write};
use std::iter::{IntoIterator, Iterator};
use std::path;
use crate::message::Field;
use crate::quickfix_errors::*;
use chrono::{NaiveDate, NaiveDateTime, NaiveTime};
use roxmltree::{Document, Node, NodeType};
type FxStr = &'static str;
type DictResult<T> = std::result::Result<T, SessionLevelRejectErr>;
#[derive(Debug, Copy, Clone)]
enum FixType {
CHAR,
BOOLEAN,
DATA,
FLOAT,
AMT,
PERCENTAGE,
PRICE,
PRICEOFFSET,
QTY,
INT,
LENGTH,
NUMINGROUP,
SEQNUM,
TAGNUM,
STRING,
COUNTRY,
CURRENCY,
EXCHANGE,
LOCALMKTDATE,
MONTHYEAR,
MULTIPLEVALUESTRING,
UTCDATE,
UTCTIMEONLY,
UTCTIMESTAMP,
}
impl FixType {
fn value_of(value: &str) -> Self {
match value {
"CHAR" => FixType::CHAR,
"BOOLEAN" => FixType::BOOLEAN,
"DATA" => FixType::DATA,
"FLOAT" => FixType::FLOAT,
"AMT" => FixType::AMT,
"PERCENTAGE" => FixType::PERCENTAGE,
"PRICE" => FixType::PRICE,
"PRICEOFFSET" => FixType::PRICEOFFSET,
"QTY" => FixType::QTY,
"INT" => FixType::INT,
"LENGTH" => FixType::LENGTH,
"NUMINGROUP" => FixType::NUMINGROUP,
"SEQNUM" => FixType::SEQNUM,
"TAGNUM" => FixType::TAGNUM,
"STRING" => FixType::STRING,
"COUNTRY" => FixType::COUNTRY,
"CURRENCY" => FixType::CURRENCY,
"EXCHANGE" => FixType::EXCHANGE,
"LOCALMKTDATE" => FixType::LOCALMKTDATE,
"MONTHYEAR" => FixType::MONTHYEAR,
"MULTIPLEVALUESTRING" => FixType::MULTIPLEVALUESTRING,
"UTCDATE" => FixType::UTCDATE,
"UTCTIMEONLY" => FixType::UTCTIMEONLY,
"UTCTIMESTAMP" => FixType::UTCTIMESTAMP,
_ => panic!("Unknown Fix Type..aborting"),
}
}
}
#[derive(Debug)]
pub struct DataDictionary {
begin_string: String,
header: Header,
trailer: Trailer,
fields_by_tag: HashMap<u32, FieldEntry>,
fields_by_name: HashMap<String, u32>,
groups: HashMap<String, Group>,
messages: HashMap<String, Message>,
}
impl DataDictionary {
fn new() -> Self {
Self {
begin_string: String::new(),
header: Header::new(),
trailer: Trailer::new(),
fields_by_tag: HashMap::new(),
fields_by_name: HashMap::new(),
groups: HashMap::new(),
messages: HashMap::new(),
}
}
pub fn with_xml(xml_file: &str) -> Self {
create_data_dict(xml_file)
}
fn get_field_type(&self, field: &Field) -> FixType {
let field_entry = self.fields_by_tag.get(&field.get_tag()).unwrap();
return field_entry.field_type;
}
fn check_valid_tag(&self, field: &Field) -> DictResult<&FieldEntry> {
// checks if the tag is valid according to data dictionary
let tag = field.get_tag();
self.fields_by_tag
.get(&tag)
.ok_or_else(|| SessionLevelRejectErr::invalid_tag_err())
}
fn check_msg_type(&self, msg_type: &str) -> DictResult<&Message> {
// checks that message type is valid according to data dictionary
self.messages
.get(msg_type)
.ok_or_else(|| SessionLevelRejectErr::invalid_msg_type_err())
}
pub fn check_tag_for_message(
&self,
tag: u32,
msg_type: &str,
) -> Result<(), SessionLevelRejectErr> {
let message = match self.check_msg_type(msg_type) {
Ok(m) => m,
Err(e) => return Err(e),
};
match message.fields.get(&tag) {
Some(_) => return Ok(()),
None => {
for (grp_name, _) in message.groups.iter() {
if check_tag_in_group(tag, grp_name, self) {
return Ok(());
}
}
}
}
Err(SessionLevelRejectErr::undefined_tag_err())
}
pub fn check_tag_valid_value(&self, field: &Field) -> Result<(), SessionLevelRejectErr> {
// returns true or false based on valid/invalid value
let value = field.get_str().unwrap();
if value.is_empty() {
return Err(SessionLevelRejectErr::tag_without_value_err());
}
let field_entry = match self.check_valid_tag(field) {
Ok(f) => f,
Err(e) => return Err(e),
};
if field_entry.field_values.is_empty() {
// empty field values means its free value tag
return self.check_tag_format(field);
} else if field_entry.field_values.get(&value).is_none() {
// no need to check format here. it will result in error regardless
return Err(SessionLevelRejectErr::value_out_of_range_err());
}
Ok(())
}
fn check_has_required(&self, msg: &crate::message::Message) -> DictResult<()> {
todo!()
}
fn check_tag_format(&self, field: &Field) -> DictResult<()> {
let expected_format = self.get_field_type(field);
let result = match expected_format {
FixType::FLOAT
| FixType::AMT
| FixType::PERCENTAGE
| FixType::PRICEOFFSET
| FixType::PRICE
| FixType::QTY => field.get_float().map(|_| ()),
FixType::INT
| FixType::LENGTH
| FixType::NUMINGROUP
| FixType::SEQNUM
| FixType::TAGNUM => field.get_int().map(|_| ()),
FixType::CHAR => field.get_char().map(|_| ()),
FixType::BOOLEAN => field.get_bool().map(|_| ()),
FixType::DATA
| FixType::STRING
| FixType::CURRENCY
| FixType::COUNTRY
| FixType::EXCHANGE
| FixType::MULTIPLEVALUESTRING => field.get_str().map(|_| ()),
FixType::LOCALMKTDATE | FixType::UTCDATE => {
// todo!("implement time related parsing using other crates")
match field.get_str() {
Ok(s) => {
if NaiveDate::parse_from_str(&s, "%Y%m%d").is_err() {
return Err(SessionLevelRejectErr::incorrect_data_format_err());
}
}
Err(_) => return Err(SessionLevelRejectErr::incorrect_data_format_err()),
}
Ok(())
}
FixType::MONTHYEAR => {
match field.get_str() {
Ok(s) => {
if NaiveDate::parse_from_str(&s, "%Y%m").is_err() {
return Err(SessionLevelRejectErr::incorrect_data_format_err());
}
}
Err(_) => return Err(SessionLevelRejectErr::incorrect_data_format_err()),
}
Ok(())
}
FixType::UTCTIMEONLY => {
match field.get_str() {
Ok(s) => {
if NaiveTime::parse_from_str(&s, "%T%.3f").is_err() {
return Err(SessionLevelRejectErr::incorrect_data_format_err());
}
}
Err(_) => return Err(SessionLevelRejectErr::incorrect_data_format_err()),
}
Ok(())
}
FixType::UTCTIMESTAMP => {
match field.get_str() {
Ok(s) => {
if NaiveDateTime::parse_from_str(&s, "%Y%m%d-%T%.3f").is_err() {
return Err(SessionLevelRejectErr::incorrect_data_format_err());
}
}
Err(_) => return Err(SessionLevelRejectErr::incorrect_data_format_err()),
}
Ok(())
}
};
return result;
}
}
#[derive(Debug)]
struct FieldEntry {
field_number: u32,
field_name: String,
field_type: FixType,
field_values: BTreeMap<String, FieldValueEntry>,
}
impl FieldEntry {
fn new(field_number: u32, field_name: &str, field_type: &str) -> Self {
let ftype = FixType::value_of(field_type);
Self {
field_number,
field_name: field_name.to_owned(),
field_type: ftype,
field_values: BTreeMap::new(),
}
}
fn get_field_name(&self) -> &str {
&self.field_name.as_str()
}
}
#[derive(Debug)]
struct FieldValueEntry {
value: String,
description: String,
}
impl FieldValueEntry {
fn new(value: &str, desc: &str) -> Self {
Self {
value: value.to_owned(),
description: desc.to_owned(),
}
}
fn get_field_value(&self) -> &str {
self.value.as_str()
}
}
trait FieldAndGroupSetter {
fn add_required_field(&mut self, field: u32, required: bool);
fn add_required_group(&mut self, group_name: &str, required: bool);
fn add_delim(&mut self, delim: u32);
}
#[derive(Debug)]
struct Group {
group_name: String,
group_delim: u32,
group_fields: HashMap<u32, bool>, // field number to required mapping
sub_groups: HashMap<String, bool>, // (sub)group to required mapping
}
impl Group {
fn new(name: &str) -> Self {
Self {
group_name: name.to_owned(),
group_delim: 0,
group_fields: HashMap::new(),
sub_groups: HashMap::new(),
}
}
}
#[derive(Debug)]
struct Header {
header_field: HashMap<u32, bool>,
header_groups: HashMap<String, bool>,
}
impl Header {
fn new() -> Self {
Self {
header_field: HashMap::new(),
header_groups: HashMap::new(),
}
}
}
#[derive(Debug)]
struct Trailer {
trailer_field: HashMap<u32, bool>,
}
impl Trailer {
fn new() -> Self {
Self {
trailer_field: HashMap::new(),
}
}
}
fn check_tag_in_group(tag: u32, group_name: &str, dict: &DataDictionary) -> bool {
// check if the field is supported by the group or not
let group = match dict.groups.get(group_name) {
Some(g) => g,
None => {
eprintln!("Group {} not found in dictionary", group_name);
return false;
}
};
if group.group_fields.contains_key(&tag) {
return true;
}
for (group_name, _) in group.sub_groups.iter() {
if check_tag_in_group(tag, group_name, dict) {
return true;
}
}
return false;
}
impl FieldAndGroupSetter for Group {
fn add_required_field(&mut self, field: u32, required: bool) {
self.group_fields.insert(field, required);
}
fn add_required_group(&mut self, group_name: &str, required: bool) {
self.sub_groups.insert(group_name.to_string(), required);
}
fn add_delim(&mut self, delim: u32) {
if self.group_delim == 0 {
self.group_delim = delim;
}
}
}
#[derive(Debug)]
struct Message {
name: String,
m_type: String,
category: String,
fields: HashMap<u32, bool>, // field tag to required
groups: HashMap<String, bool>, // group name to required mapping
}
impl Message {
fn new(msg_name: &str, msg_type: &str, msg_cat: &str) -> Self {
Self {
name: msg_name.to_owned(),
m_type: msg_type.to_owned(),
category: msg_cat.to_owned(),
fields: HashMap::new(),
groups: HashMap::new(),
}
}
}
impl FieldAndGroupSetter for Message {
fn add_required_field(&mut self, field: u32, required: bool) {
self.fields.insert(field, required);
}
fn add_required_group(&mut self, group_name: &str, required: bool) {
self.groups.insert(group_name.to_string(), required);
}
fn add_delim(&mut self, delim: u32) {}
}
fn update_fields(field_node: Node, dict: &mut DataDictionary) {
for node in field_node
.children()
.filter(|n| n.node_type() == NodeType::Element)
{
let fname = node.attribute("name").unwrap();
let fnum = node.attribute("number").unwrap().parse::<u32>().unwrap();
let ftype = node.attribute("type").unwrap();
let mut f_entry = FieldEntry::new(fnum, fname, ftype);
for child in node
.children()
.filter(|n| n.node_type() == NodeType::Element && n.has_tag_name("value"))
{
let valid_value = child.attribute("enum").unwrap();
let fvalue_entry =
FieldValueEntry::new(valid_value, child.attribute("description").unwrap());
f_entry
.field_values
.insert(valid_value.to_string(), fvalue_entry);
}
dict.fields_by_tag.insert(fnum, f_entry);
dict.fields_by_name.insert(fname.to_string(), fnum);
}
}
fn add_component<T: FieldAndGroupSetter>(
comp_node: &Node,
comp_node_req: bool,
field_map: &mut T,
dict: &mut DataDictionary,
) {
for child_node in comp_node
.children()
.filter(|n| n.node_type() == NodeType::Element)
{
match child_node.tag_name().name() {
"field" => {
// field details are in struct.
let field_tag = get_field_tag(child_node, dict);
let required = get_required_attribute(child_node);
// if comp is required and components field is required then add as required
// otherwise optional
field_map.add_required_field(field_tag, required && comp_node_req);
field_map.add_delim(field_tag)
}
"group" => {
let grp_name = get_name_attribute(child_node);
let grp_req = get_required_attribute(child_node);
let group_field_tag = dict.fields_by_name.get(grp_name).unwrap();
field_map.add_required_field(*group_field_tag, grp_req && comp_node_req);
field_map.add_required_group(grp_name, grp_req && comp_node_req);
if dict.groups.get(grp_name).is_none() {
let sub_group = add_group(child_node, dict);
dict.groups.insert(grp_name.to_string(), sub_group);
}
}
_ => panic!("Invalid xml tag in component"),
}
}
}
fn add_group(group_node: Node, dict: &mut DataDictionary) -> Group {
// create group, subgroup and components entry and return
let group_name = group_node.attribute("name").unwrap();
let mut group = Group::new(group_name);
for child_node in group_node
.children()
.filter(|n| n.node_type() == NodeType::Element)
{
match child_node.tag_name().name() {
"field" => {
let field_tag = get_field_tag(child_node, dict);
let required = get_required_attribute(child_node);
group.group_fields.insert(field_tag, required);
if group.group_delim == 0 {
group.group_delim = field_tag;
}
}
"component" => {
let required = get_required_attribute(child_node);
add_component(&child_node, required, &mut group, dict);
}
"group" => {
let sub_group_name = get_name_attribute(child_node);
let required = get_required_attribute(child_node);
group
.sub_groups
.insert(sub_group_name.to_string(), required);
if dict.groups.get(sub_group_name).is_none() {
let sub_group = add_group(child_node, dict);
dict.groups.insert(sub_group_name.to_string(), sub_group);
}
}
_ => panic!("Unknown xml tag in groups. Aborting."),
}
}
group
}
fn get_name_attribute<'a>(node: Node<'a, '_>) -> &'a str {
node.attribute("name").unwrap()
}
fn get_required_attribute(node: Node) -> bool {
node.attribute("required")
.map(|req| req.eq_ignore_ascii_case("y"))
.unwrap()
}
fn get_field_tag(node: Node, dict: &DataDictionary) -> u32 {
let field_tag = node
.attribute("name")
.and_then(|n| dict.fields_by_name.get(n))
.unwrap();
*field_tag
}
fn add_messages(node: Node, dict: &mut DataDictionary, components: &HashMap<&str, Node>) {
for msg_node in node
.children()
.filter(|n| n.node_type() == NodeType::Element)
{
let msg_name = msg_node.attribute("name").unwrap();
let msg_type = msg_node.attribute("msgtype").unwrap();
let msg_cat = msg_node.attribute("msgcat").unwrap();
let mut message = Message::new(msg_name, msg_type, msg_cat);
for msg_child_node in msg_node
.children()
.filter(|n| n.node_type() == NodeType::Element)
{
match msg_child_node.tag_name().name() {
"field" => {
let field_tag = get_field_tag(msg_child_node, dict);
let required = get_required_attribute(msg_child_node);
message.fields.insert(field_tag, required);
}
"group" => {
let grp_name = get_name_attribute(msg_child_node);
let required = get_required_attribute(msg_child_node);
message.groups.insert(grp_name.to_string(), required);
if dict.groups.get(grp_name).is_none() {
let msg_group = add_group(msg_child_node, dict);
dict.groups.insert(grp_name.to_string(), msg_group);
}
}
"component" => {
let cname = get_name_attribute(msg_child_node);
let required = get_required_attribute(msg_child_node);
let component = components.get(cname).unwrap();
// message.components.insert(cname.to_string(), required);
add_component(component, required, &mut message, dict);
}
_ => panic!("Unknown xml tag in message section. Aborting."),
}
}
dict.messages.insert(msg_type.to_string(), message);
}
}
fn add_header(header_node: Node, dict: &mut DataDictionary) {
for node in header_node
.children()
.filter(|n| n.node_type() == NodeType::Element)
{
match node.tag_name().name() {
"field" => {
let field_tag = get_field_tag(node, dict);
let required = get_required_attribute(node);
dict.header.header_field.insert(field_tag, required);
}
"group" => {
let grp_name = get_name_attribute(node);
let required = get_required_attribute(node);
dict.header
.header_groups
.insert(grp_name.to_string(), required);
if dict.groups.get(grp_name).is_none() {
let hdr_group = add_group(node, dict);
dict.groups.insert(grp_name.to_string(), hdr_group);
}
}
_ => panic!("Unknown xml tag in header section. Aborting."),
}
}
}
fn add_trailer(trailer_node: Node, dict: &mut DataDictionary) {
for node in trailer_node
.children()
.filter(|n| n.node_type() == NodeType::Element)
{
match node.tag_name().name() {
"field" => {
let field_tag = get_field_tag(node, dict);
let required = get_required_attribute(node);
dict.trailer.trailer_field.insert(field_tag, required);
}
_ => panic!("Unknown xml tag in header section. Aborting."),
}
}
}
pub fn create_data_dict(fix_xml: &str) -> DataDictionary {
let mut file_data = String::with_capacity(1024 * 64);
let mut file = File::open(fix_xml).unwrap();
file.read_to_string(&mut file_data).unwrap();
let doc = Document::parse(&file_data).unwrap();
let mut data_dict = DataDictionary::new();
let dict_type = doc.root_element().attribute("type").unwrap();
let major_version = doc.root_element().attribute("major").unwrap();
let minor_verion = doc.root_element().attribute("minor").unwrap();
let begin_string = format!("{}.{}.{}", dict_type, major_version, minor_verion);
data_dict.begin_string = begin_string;
let field_node = doc
.root_element()
.children()
.find(|node| node.tag_name().name() == "fields")
.unwrap();
update_fields(field_node, &mut data_dict);
let component_node = doc
.root_element()
.children()
.find(|node| node.tag_name().name() == "components")
.unwrap();
let mut component_map: HashMap<&str, Node> = HashMap::new();
for cnode in component_node
.children()
.filter(|n| n.node_type() == NodeType::Element)
{
let cmp_name = get_name_attribute(cnode);
component_map.insert(cmp_name, cnode);
}
let header_node = doc
.root_element()
.children()
.find(|node| node.tag_name().name() == "header")
.unwrap();
add_header(header_node, &mut data_dict);
let trailer_node = doc
.root_element()
.children()
.find(|node| node.tag_name().name() == "trailer")
.unwrap();
add_trailer(trailer_node, &mut data_dict);
let message_node = doc
.root_element()
.children()
.find(|node| node.tag_name().name() == "messages")
.unwrap();
add_messages(message_node, &mut data_dict, &component_map);
data_dict
}
#[cfg(test)]
mod dict_test {
use super::*;
#[test]
fn test_it_works() {
let data_dict = create_data_dict("src/fix43/FIX43.xml");
// println!("\ndictionary fields by name: {:?}", data_dict.fields_by_name);
// println!("\ndictionary fields by tag: {:?}", data_dict.fields_by_tag);
// println!("\ndictionary components: {:?}", data_dict.components);
// println!("\ndictionary groups: {:?}", data_dict.groups);
// println!("\ndictionary messages {:?}", data_dict.messages);
println!("\ndictionary header {:?}", data_dict.header);
println!("\ndictionary begin string {}", data_dict.begin_string);
println!("\ndictionary trailer {:?}", data_dict.trailer);
}
fn test_date_time_fields() {}
}
|
use http;
use net;
use http::response::Response;
use std::net::TcpStream;
use std::io::{Write, Read};
use std::io::ErrorKind::WouldBlock;
use std::collections::HashMap;
use std::fmt;
pub struct Request
{
pub version: http::Version,
pub method: http::Method,
pub url: net::url::URL,
pub header: HashMap<String, String>
}
impl Request
{
pub fn new(method : http::Method, version : http::Version) -> Self
{
Request
{
version: version,
method: method,
url: net::url::URL::new(),
header: HashMap::new(),
}
}
fn as_bytes(&self) -> Vec<u8>
{
let mut header = String::new();
for (k, v) in self.header.iter()
{
header.push_str(format!("{}: {}\r\n", k, v).as_str());
}
if header.is_empty()
{
header.push_str("\r\n");
}
format!("{} {}{} {}\r\n{}\r\n",
self.method,
self.url.get_path(),
self.url.get_params(),
self.version,
header
).as_bytes().to_vec()
}
}
impl fmt::Display for Request
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
{
write!(f, "Request({}{}, {})",
self.url.get_path(), self.url.get_params(), self.method
)
}
}
pub fn get(url : net::url::URL) -> Result<Response, http::Error>
{
if url.host.is_none() || url.get_port().is_none()
{
Err(http::Error::Missing("host, port".to_string()))
}
else
{
let request = &mut Request::new(http::Method::Get, http::Version::V1_1);
//request.header.insert(String::from("Connection"), String::from("Close"));
request.url = url.clone();
if request.url.is_decoded()
{
request.url.encode();
}
let host = request.url.clone().host.unwrap();
let port = request.url.get_port().unwrap();
if let Ok(mut stream) = TcpStream::connect(format!("{}:{}", host, port))
{
send(&mut stream, &request)
}
else
{
Err(http::Error::Connect(host, port))
}
}
}
pub fn post(_url : net::url::URL) -> Result<Response, http::Error>
{
Ok(Response::new())
}
fn send(stream : &mut TcpStream, request : &Request) -> Result<Response, http::Error>
{
let request_data = request.as_bytes();
if let Ok(size) = stream.write(request_data.as_slice())
{
if size != request_data.len()
{
return Err(http::Error::ReadWrite)
}
}
else
{
return Err(http::Error::ReadWrite)
}
let mut response = Response::new();
if let Err(error) = read(stream, &mut response)
{
Err(error)
}
else
{
Ok(response)
}
}
fn send_chunk(stream : &mut TcpStream, chunk : Vec<u8>) -> Result<usize, http::Error>
{
let bytes_sent : usize = 0;
let err_val = usize::max_value();
bytes_sent.saturating_add
(
stream.write(format!("{:X}\r\n", chunk.len()).as_bytes()).unwrap_or(err_val)
);
if !chunk.is_empty()
{
bytes_sent.saturating_add(stream.write(chunk.as_slice()).unwrap_or(err_val));
bytes_sent.saturating_add(stream.write(b"\r\n").unwrap_or(err_val));
}
if bytes_sent == err_val
{
Err(http::Error::ReadWrite)
}
else
{
Ok(bytes_sent)
}
}
fn read(stream : &mut TcpStream, response : &mut Response) -> Result<usize, http::Error>
{
let data : &mut Vec<u8> = &mut Vec::new();
let buffer = &mut [0; 4096];
let mut expecting_header = true;
let mut chunked = false;
let _ = stream.set_nonblocking(true);
loop
{
match stream.read(buffer)
{
Ok(size) =>
{
if size == 0
{
break
}
data.append(&mut buffer[..size].to_vec());
continue;
},
Err(e) =>
{
if e.kind() != WouldBlock
{
return Err(http::Error::ReadWrite);
}
}
}
if data.len() == 0
{
continue;
}
if expecting_header
{
let mut skip = 0;
for line in String::from_utf8_lossy(data.as_slice()).lines()
{
if line.is_empty()
{
skip += 2;
break;
}
match response.parse_line(line)
{
Ok(is_header) =>
{
if !is_header
{
break;
}
skip += line.len() + 2
},
Err(e) => return Err(e)
}
}
let _ = data.drain(..skip);
expecting_header = false;
chunked = response.header.get(&"transfer-encoding".to_string())
.unwrap_or(&"".into())
.contains("chunked")
}
else
{
if chunked
{
match read_chunk(data, response)
{
Ok(size) =>
{
if size == 0
{
break;
}
},
Err(e) =>
{
if http::Error::NeedMoreData == e
{
continue; // wait for more data
}
else
{
return Err(e)
}
}
}
}
else
{
response.content.append(&mut data.drain(..).collect());
}
}
}
let _ = stream.set_nonblocking(false);
println!("read {} bytes", response.content.len());
Ok(0)
}
fn read_chunk(data : &mut Vec<u8>, response : &mut Response) -> Result<usize, http::Error>
{
let parts : &mut Vec<Vec<u8>> = &mut Vec::new();
let mut tmp = data.clone();
while parts.len() < 2
{
match tmp.windows(2).position(|w| w == [b'\r', b'\n'])
{
Some(pos) =>
{
parts.push(tmp.drain(..pos).collect());
},
None =>
{
parts.push(tmp.drain(..).collect());
break;
}
}
tmp.drain(..2);
}
if parts.len() < 2
{
return Err(http::Error::NeedMoreData);
}
let expected_size = usize::from_str_radix(&String::from_utf8_lossy(&parts[0][..]), 16).unwrap_or(0);
if expected_size > parts[1].len()
{
return Err(http::Error::NeedMoreData);
}
else if expected_size < parts[1].len()
{
Err(http::Error::InvalidChunkSize(expected_size, parts[1].len()))
}
else
{
data.drain(..expected_size + parts[0].len() + 4);
response.content.append(&mut parts[1]);
// TODO: trailer
Ok(expected_size)
}
} |
#[doc = "Register `MPCBB2_VCTR51` reader"]
pub type R = crate::R<MPCBB2_VCTR51_SPEC>;
#[doc = "Register `MPCBB2_VCTR51` writer"]
pub type W = crate::W<MPCBB2_VCTR51_SPEC>;
#[doc = "Field `B1632` reader - B1632"]
pub type B1632_R = crate::BitReader;
#[doc = "Field `B1632` writer - B1632"]
pub type B1632_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1633` reader - B1633"]
pub type B1633_R = crate::BitReader;
#[doc = "Field `B1633` writer - B1633"]
pub type B1633_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1634` reader - B1634"]
pub type B1634_R = crate::BitReader;
#[doc = "Field `B1634` writer - B1634"]
pub type B1634_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1635` reader - B1635"]
pub type B1635_R = crate::BitReader;
#[doc = "Field `B1635` writer - B1635"]
pub type B1635_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1636` reader - B1636"]
pub type B1636_R = crate::BitReader;
#[doc = "Field `B1636` writer - B1636"]
pub type B1636_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1637` reader - B1637"]
pub type B1637_R = crate::BitReader;
#[doc = "Field `B1637` writer - B1637"]
pub type B1637_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1638` reader - B1638"]
pub type B1638_R = crate::BitReader;
#[doc = "Field `B1638` writer - B1638"]
pub type B1638_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1639` reader - B1639"]
pub type B1639_R = crate::BitReader;
#[doc = "Field `B1639` writer - B1639"]
pub type B1639_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1640` reader - B1640"]
pub type B1640_R = crate::BitReader;
#[doc = "Field `B1640` writer - B1640"]
pub type B1640_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1641` reader - B1641"]
pub type B1641_R = crate::BitReader;
#[doc = "Field `B1641` writer - B1641"]
pub type B1641_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1642` reader - B1642"]
pub type B1642_R = crate::BitReader;
#[doc = "Field `B1642` writer - B1642"]
pub type B1642_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1643` reader - B1643"]
pub type B1643_R = crate::BitReader;
#[doc = "Field `B1643` writer - B1643"]
pub type B1643_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1644` reader - B1644"]
pub type B1644_R = crate::BitReader;
#[doc = "Field `B1644` writer - B1644"]
pub type B1644_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1645` reader - B1645"]
pub type B1645_R = crate::BitReader;
#[doc = "Field `B1645` writer - B1645"]
pub type B1645_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1646` reader - B1646"]
pub type B1646_R = crate::BitReader;
#[doc = "Field `B1646` writer - B1646"]
pub type B1646_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1647` reader - B1647"]
pub type B1647_R = crate::BitReader;
#[doc = "Field `B1647` writer - B1647"]
pub type B1647_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1648` reader - B1648"]
pub type B1648_R = crate::BitReader;
#[doc = "Field `B1648` writer - B1648"]
pub type B1648_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1649` reader - B1649"]
pub type B1649_R = crate::BitReader;
#[doc = "Field `B1649` writer - B1649"]
pub type B1649_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1650` reader - B1650"]
pub type B1650_R = crate::BitReader;
#[doc = "Field `B1650` writer - B1650"]
pub type B1650_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1651` reader - B1651"]
pub type B1651_R = crate::BitReader;
#[doc = "Field `B1651` writer - B1651"]
pub type B1651_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1652` reader - B1652"]
pub type B1652_R = crate::BitReader;
#[doc = "Field `B1652` writer - B1652"]
pub type B1652_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1653` reader - B1653"]
pub type B1653_R = crate::BitReader;
#[doc = "Field `B1653` writer - B1653"]
pub type B1653_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1654` reader - B1654"]
pub type B1654_R = crate::BitReader;
#[doc = "Field `B1654` writer - B1654"]
pub type B1654_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1655` reader - B1655"]
pub type B1655_R = crate::BitReader;
#[doc = "Field `B1655` writer - B1655"]
pub type B1655_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1656` reader - B1656"]
pub type B1656_R = crate::BitReader;
#[doc = "Field `B1656` writer - B1656"]
pub type B1656_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1657` reader - B1657"]
pub type B1657_R = crate::BitReader;
#[doc = "Field `B1657` writer - B1657"]
pub type B1657_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1658` reader - B1658"]
pub type B1658_R = crate::BitReader;
#[doc = "Field `B1658` writer - B1658"]
pub type B1658_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1659` reader - B1659"]
pub type B1659_R = crate::BitReader;
#[doc = "Field `B1659` writer - B1659"]
pub type B1659_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1660` reader - B1660"]
pub type B1660_R = crate::BitReader;
#[doc = "Field `B1660` writer - B1660"]
pub type B1660_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1661` reader - B1661"]
pub type B1661_R = crate::BitReader;
#[doc = "Field `B1661` writer - B1661"]
pub type B1661_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1662` reader - B1662"]
pub type B1662_R = crate::BitReader;
#[doc = "Field `B1662` writer - B1662"]
pub type B1662_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1663` reader - B1663"]
pub type B1663_R = crate::BitReader;
#[doc = "Field `B1663` writer - B1663"]
pub type B1663_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - B1632"]
#[inline(always)]
pub fn b1632(&self) -> B1632_R {
B1632_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - B1633"]
#[inline(always)]
pub fn b1633(&self) -> B1633_R {
B1633_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - B1634"]
#[inline(always)]
pub fn b1634(&self) -> B1634_R {
B1634_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - B1635"]
#[inline(always)]
pub fn b1635(&self) -> B1635_R {
B1635_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - B1636"]
#[inline(always)]
pub fn b1636(&self) -> B1636_R {
B1636_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - B1637"]
#[inline(always)]
pub fn b1637(&self) -> B1637_R {
B1637_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 6 - B1638"]
#[inline(always)]
pub fn b1638(&self) -> B1638_R {
B1638_R::new(((self.bits >> 6) & 1) != 0)
}
#[doc = "Bit 7 - B1639"]
#[inline(always)]
pub fn b1639(&self) -> B1639_R {
B1639_R::new(((self.bits >> 7) & 1) != 0)
}
#[doc = "Bit 8 - B1640"]
#[inline(always)]
pub fn b1640(&self) -> B1640_R {
B1640_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - B1641"]
#[inline(always)]
pub fn b1641(&self) -> B1641_R {
B1641_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - B1642"]
#[inline(always)]
pub fn b1642(&self) -> B1642_R {
B1642_R::new(((self.bits >> 10) & 1) != 0)
}
#[doc = "Bit 11 - B1643"]
#[inline(always)]
pub fn b1643(&self) -> B1643_R {
B1643_R::new(((self.bits >> 11) & 1) != 0)
}
#[doc = "Bit 12 - B1644"]
#[inline(always)]
pub fn b1644(&self) -> B1644_R {
B1644_R::new(((self.bits >> 12) & 1) != 0)
}
#[doc = "Bit 13 - B1645"]
#[inline(always)]
pub fn b1645(&self) -> B1645_R {
B1645_R::new(((self.bits >> 13) & 1) != 0)
}
#[doc = "Bit 14 - B1646"]
#[inline(always)]
pub fn b1646(&self) -> B1646_R {
B1646_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bit 15 - B1647"]
#[inline(always)]
pub fn b1647(&self) -> B1647_R {
B1647_R::new(((self.bits >> 15) & 1) != 0)
}
#[doc = "Bit 16 - B1648"]
#[inline(always)]
pub fn b1648(&self) -> B1648_R {
B1648_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 17 - B1649"]
#[inline(always)]
pub fn b1649(&self) -> B1649_R {
B1649_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bit 18 - B1650"]
#[inline(always)]
pub fn b1650(&self) -> B1650_R {
B1650_R::new(((self.bits >> 18) & 1) != 0)
}
#[doc = "Bit 19 - B1651"]
#[inline(always)]
pub fn b1651(&self) -> B1651_R {
B1651_R::new(((self.bits >> 19) & 1) != 0)
}
#[doc = "Bit 20 - B1652"]
#[inline(always)]
pub fn b1652(&self) -> B1652_R {
B1652_R::new(((self.bits >> 20) & 1) != 0)
}
#[doc = "Bit 21 - B1653"]
#[inline(always)]
pub fn b1653(&self) -> B1653_R {
B1653_R::new(((self.bits >> 21) & 1) != 0)
}
#[doc = "Bit 22 - B1654"]
#[inline(always)]
pub fn b1654(&self) -> B1654_R {
B1654_R::new(((self.bits >> 22) & 1) != 0)
}
#[doc = "Bit 23 - B1655"]
#[inline(always)]
pub fn b1655(&self) -> B1655_R {
B1655_R::new(((self.bits >> 23) & 1) != 0)
}
#[doc = "Bit 24 - B1656"]
#[inline(always)]
pub fn b1656(&self) -> B1656_R {
B1656_R::new(((self.bits >> 24) & 1) != 0)
}
#[doc = "Bit 25 - B1657"]
#[inline(always)]
pub fn b1657(&self) -> B1657_R {
B1657_R::new(((self.bits >> 25) & 1) != 0)
}
#[doc = "Bit 26 - B1658"]
#[inline(always)]
pub fn b1658(&self) -> B1658_R {
B1658_R::new(((self.bits >> 26) & 1) != 0)
}
#[doc = "Bit 27 - B1659"]
#[inline(always)]
pub fn b1659(&self) -> B1659_R {
B1659_R::new(((self.bits >> 27) & 1) != 0)
}
#[doc = "Bit 28 - B1660"]
#[inline(always)]
pub fn b1660(&self) -> B1660_R {
B1660_R::new(((self.bits >> 28) & 1) != 0)
}
#[doc = "Bit 29 - B1661"]
#[inline(always)]
pub fn b1661(&self) -> B1661_R {
B1661_R::new(((self.bits >> 29) & 1) != 0)
}
#[doc = "Bit 30 - B1662"]
#[inline(always)]
pub fn b1662(&self) -> B1662_R {
B1662_R::new(((self.bits >> 30) & 1) != 0)
}
#[doc = "Bit 31 - B1663"]
#[inline(always)]
pub fn b1663(&self) -> B1663_R {
B1663_R::new(((self.bits >> 31) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - B1632"]
#[inline(always)]
#[must_use]
pub fn b1632(&mut self) -> B1632_W<MPCBB2_VCTR51_SPEC, 0> {
B1632_W::new(self)
}
#[doc = "Bit 1 - B1633"]
#[inline(always)]
#[must_use]
pub fn b1633(&mut self) -> B1633_W<MPCBB2_VCTR51_SPEC, 1> {
B1633_W::new(self)
}
#[doc = "Bit 2 - B1634"]
#[inline(always)]
#[must_use]
pub fn b1634(&mut self) -> B1634_W<MPCBB2_VCTR51_SPEC, 2> {
B1634_W::new(self)
}
#[doc = "Bit 3 - B1635"]
#[inline(always)]
#[must_use]
pub fn b1635(&mut self) -> B1635_W<MPCBB2_VCTR51_SPEC, 3> {
B1635_W::new(self)
}
#[doc = "Bit 4 - B1636"]
#[inline(always)]
#[must_use]
pub fn b1636(&mut self) -> B1636_W<MPCBB2_VCTR51_SPEC, 4> {
B1636_W::new(self)
}
#[doc = "Bit 5 - B1637"]
#[inline(always)]
#[must_use]
pub fn b1637(&mut self) -> B1637_W<MPCBB2_VCTR51_SPEC, 5> {
B1637_W::new(self)
}
#[doc = "Bit 6 - B1638"]
#[inline(always)]
#[must_use]
pub fn b1638(&mut self) -> B1638_W<MPCBB2_VCTR51_SPEC, 6> {
B1638_W::new(self)
}
#[doc = "Bit 7 - B1639"]
#[inline(always)]
#[must_use]
pub fn b1639(&mut self) -> B1639_W<MPCBB2_VCTR51_SPEC, 7> {
B1639_W::new(self)
}
#[doc = "Bit 8 - B1640"]
#[inline(always)]
#[must_use]
pub fn b1640(&mut self) -> B1640_W<MPCBB2_VCTR51_SPEC, 8> {
B1640_W::new(self)
}
#[doc = "Bit 9 - B1641"]
#[inline(always)]
#[must_use]
pub fn b1641(&mut self) -> B1641_W<MPCBB2_VCTR51_SPEC, 9> {
B1641_W::new(self)
}
#[doc = "Bit 10 - B1642"]
#[inline(always)]
#[must_use]
pub fn b1642(&mut self) -> B1642_W<MPCBB2_VCTR51_SPEC, 10> {
B1642_W::new(self)
}
#[doc = "Bit 11 - B1643"]
#[inline(always)]
#[must_use]
pub fn b1643(&mut self) -> B1643_W<MPCBB2_VCTR51_SPEC, 11> {
B1643_W::new(self)
}
#[doc = "Bit 12 - B1644"]
#[inline(always)]
#[must_use]
pub fn b1644(&mut self) -> B1644_W<MPCBB2_VCTR51_SPEC, 12> {
B1644_W::new(self)
}
#[doc = "Bit 13 - B1645"]
#[inline(always)]
#[must_use]
pub fn b1645(&mut self) -> B1645_W<MPCBB2_VCTR51_SPEC, 13> {
B1645_W::new(self)
}
#[doc = "Bit 14 - B1646"]
#[inline(always)]
#[must_use]
pub fn b1646(&mut self) -> B1646_W<MPCBB2_VCTR51_SPEC, 14> {
B1646_W::new(self)
}
#[doc = "Bit 15 - B1647"]
#[inline(always)]
#[must_use]
pub fn b1647(&mut self) -> B1647_W<MPCBB2_VCTR51_SPEC, 15> {
B1647_W::new(self)
}
#[doc = "Bit 16 - B1648"]
#[inline(always)]
#[must_use]
pub fn b1648(&mut self) -> B1648_W<MPCBB2_VCTR51_SPEC, 16> {
B1648_W::new(self)
}
#[doc = "Bit 17 - B1649"]
#[inline(always)]
#[must_use]
pub fn b1649(&mut self) -> B1649_W<MPCBB2_VCTR51_SPEC, 17> {
B1649_W::new(self)
}
#[doc = "Bit 18 - B1650"]
#[inline(always)]
#[must_use]
pub fn b1650(&mut self) -> B1650_W<MPCBB2_VCTR51_SPEC, 18> {
B1650_W::new(self)
}
#[doc = "Bit 19 - B1651"]
#[inline(always)]
#[must_use]
pub fn b1651(&mut self) -> B1651_W<MPCBB2_VCTR51_SPEC, 19> {
B1651_W::new(self)
}
#[doc = "Bit 20 - B1652"]
#[inline(always)]
#[must_use]
pub fn b1652(&mut self) -> B1652_W<MPCBB2_VCTR51_SPEC, 20> {
B1652_W::new(self)
}
#[doc = "Bit 21 - B1653"]
#[inline(always)]
#[must_use]
pub fn b1653(&mut self) -> B1653_W<MPCBB2_VCTR51_SPEC, 21> {
B1653_W::new(self)
}
#[doc = "Bit 22 - B1654"]
#[inline(always)]
#[must_use]
pub fn b1654(&mut self) -> B1654_W<MPCBB2_VCTR51_SPEC, 22> {
B1654_W::new(self)
}
#[doc = "Bit 23 - B1655"]
#[inline(always)]
#[must_use]
pub fn b1655(&mut self) -> B1655_W<MPCBB2_VCTR51_SPEC, 23> {
B1655_W::new(self)
}
#[doc = "Bit 24 - B1656"]
#[inline(always)]
#[must_use]
pub fn b1656(&mut self) -> B1656_W<MPCBB2_VCTR51_SPEC, 24> {
B1656_W::new(self)
}
#[doc = "Bit 25 - B1657"]
#[inline(always)]
#[must_use]
pub fn b1657(&mut self) -> B1657_W<MPCBB2_VCTR51_SPEC, 25> {
B1657_W::new(self)
}
#[doc = "Bit 26 - B1658"]
#[inline(always)]
#[must_use]
pub fn b1658(&mut self) -> B1658_W<MPCBB2_VCTR51_SPEC, 26> {
B1658_W::new(self)
}
#[doc = "Bit 27 - B1659"]
#[inline(always)]
#[must_use]
pub fn b1659(&mut self) -> B1659_W<MPCBB2_VCTR51_SPEC, 27> {
B1659_W::new(self)
}
#[doc = "Bit 28 - B1660"]
#[inline(always)]
#[must_use]
pub fn b1660(&mut self) -> B1660_W<MPCBB2_VCTR51_SPEC, 28> {
B1660_W::new(self)
}
#[doc = "Bit 29 - B1661"]
#[inline(always)]
#[must_use]
pub fn b1661(&mut self) -> B1661_W<MPCBB2_VCTR51_SPEC, 29> {
B1661_W::new(self)
}
#[doc = "Bit 30 - B1662"]
#[inline(always)]
#[must_use]
pub fn b1662(&mut self) -> B1662_W<MPCBB2_VCTR51_SPEC, 30> {
B1662_W::new(self)
}
#[doc = "Bit 31 - B1663"]
#[inline(always)]
#[must_use]
pub fn b1663(&mut self) -> B1663_W<MPCBB2_VCTR51_SPEC, 31> {
B1663_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 = "MPCBBx vector register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`mpcbb2_vctr51::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 [`mpcbb2_vctr51::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct MPCBB2_VCTR51_SPEC;
impl crate::RegisterSpec for MPCBB2_VCTR51_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`mpcbb2_vctr51::R`](R) reader structure"]
impl crate::Readable for MPCBB2_VCTR51_SPEC {}
#[doc = "`write(|w| ..)` method takes [`mpcbb2_vctr51::W`](W) writer structure"]
impl crate::Writable for MPCBB2_VCTR51_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets MPCBB2_VCTR51 to value 0"]
impl crate::Resettable for MPCBB2_VCTR51_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
//! A logging implementation that blocks when writing data
//!
//! The logger is simple to set up, and it will accept as much data as you'd like to write. To log data,
//!
//! 1. Configure a UART peripheral with baud rates, parities, inversions, etc.
//! 2. Call [`init`](fn.init.html) with the UART transfer half, and a [`LoggingConfig`](struct.LoggingConfig.html).
//! If the default logging behavior is acceptable, use `Default::default()` to skip logging configuration.
//! 3. Use the macros from the [`log`](https://crates.io/crates/log) crate to write data
//!
//! # Use-cases
//!
//! - Simply debugging programs and libraries
//! - Frequently logging large strings
//! - `panic!()` handlers, and printing-out panic messages
//! - Logging in interrupt and fault handlers
//!
//! # Implementation
//!
//! The implementation blocks, buffering data into the UART transfer FIFO, until the final
//! bytes are enqueued in the FIFO. The implementation logs data **in an interrupt free
//! critical section**. Interrupts **will not** preempt logging, and logging may reduce
//! the system's responsiveness. To evaluate some simple performance measurements, see
//! [Performance](../index.html#performance).
//!
//! Consider using the largest size transfer FIFO to support UART data transfer. See the example
//! for more details.
//!
//! # Example
//!
//! ```no_run
//! use imxrt_hal;
//! use imxrt_uart_log;
//!
//! let mut peripherals = imxrt_hal::Peripherals::take().unwrap();
//!
//! let uarts = peripherals.uart.clock(
//! &mut peripherals.ccm.handle,
//! imxrt_hal::ccm::uart::ClockSelect::OSC,
//! imxrt_hal::ccm::uart::PrescalarSelect::DIVIDE_1,
//! );
//!
//! let mut uart = uarts
//! .uart2
//! .init(
//! peripherals.iomuxc.ad_b1.p02,
//! peripherals.iomuxc.ad_b1.p03,
//! 115_200,
//! )
//! .unwrap();
//!
//! // Consider using a large TX FIFO size
//! uart.set_tx_fifo(core::num::NonZeroU8::new(4));
//! // Set other UART configurations...
//!
//! let (tx, rx) = uart.split();
//! imxrt_uart_log::blocking::init(tx, Default::default()).unwrap();
//!
//! // At this point, you may use log macros to write data.
//! log::info!("Hello world!");
//! ```
mod sink;
use sink::Sink;
use crate::{Filters, LoggingConfig, SetLoggerError};
use core::cell::RefCell;
use cortex_m::interrupt::{self, Mutex};
struct Logger {
/// The peripheral
uart: Mutex<RefCell<Sink>>,
/// A collection of targets that we are expected
/// to filter. If this is empty, we allow everything
filters: Filters,
}
impl log::Log for Logger {
fn enabled(&self, metadata: &::log::Metadata) -> bool {
metadata.level() <= ::log::max_level() // The log level is appropriate
&& self.filters.is_enabled(metadata) // The target is in the filter list
}
fn log(&self, record: &::log::Record) {
if self.enabled(record.metadata()) {
interrupt::free(|cs| {
let uart = self.uart.borrow(cs);
let mut uart = uart.borrow_mut();
use core::fmt::Write;
write!(
uart,
"[{} {}]: {}\r\n",
record.level(),
record.target(),
record.args()
)
.expect("write never fails");
});
}
}
fn flush(&self) {
interrupt::free(|cs| {
let uart = self.uart.borrow(cs);
let mut uart = uart.borrow_mut();
uart.flush();
})
}
}
/// Initialize the blocking logger with a UART's transfer half
///
/// `tx` should be an `imxrt_hal::uart::Tx` half, obtained by calling `split()`
/// on a configured `UART` peripheral. Returns an error if you've already called `init()`, or if
/// you've already specified a logger through another interface.
///
/// See the [module-level documentation](index.html#example) for an example.
pub fn init<S>(tx: S, config: LoggingConfig) -> Result<(), SetLoggerError>
where
S: Into<Sink>,
{
static LOGGER: Mutex<RefCell<Option<Logger>>> = Mutex::new(RefCell::new(None));
interrupt::free(|cs| {
let logger = LOGGER.borrow(cs);
let mut logger = logger.borrow_mut();
if logger.is_none() {
*logger = Some(Logger {
uart: Mutex::new(RefCell::new(tx.into())),
filters: Filters(config.filters),
});
}
// Safety: transmute from limited lifetime 'a to 'static lifetime
// is OK, since the derived memory has 'static lifetime. The need
// for this comes from the `interrupt::free()` and `Mutex::borrow()`
// interplay. The two require any references to be tied to the
// lifetime of the critical section.
let logger: &'static Logger = unsafe { core::mem::transmute(logger.as_ref().unwrap()) };
::log::set_logger(logger)
.map(|_| ::log::set_max_level(config.max_level))
.map_err(From::from)
})
}
|
use std::cmp::min;
/// Solves the Day 07 Part 1 puzzle with respect to the given input.
pub fn part_1(input: String) {
let mut crabs: Vec<i32> = input.split(",").map(str_to_int).collect();
crabs.sort();
let mut best = 0;
for crab in &crabs {
best += crab - crabs[0];
}
// Use a sweeping line algorithm with prefix and postfix components to
// calculate the fuel cost at each crab's position.
let mut fuel = best;
for i in 1..crabs.len() {
let dist = crabs[i] - crabs[i - 1];
let before = i as i32;
let after = crabs.len() as i32 - before;
fuel += dist * before;
fuel -= dist * after;
best = min(best, fuel);
}
println!("{}", best);
}
/// Solves the Day 07 Part 2 puzzle with respect to the given input.
pub fn part_2(input: String) {
let crabs: Vec<i32> = input.split(",").map(str_to_int).collect();
let mut best = i32::MAX;
// The best position lies somewhere between the leftmost and rightmost crabs.
let min_x: i32 = *crabs.iter().min().unwrap();
let max_x: i32 = *crabs.iter().max().unwrap();
for pos in min_x..max_x + 1 {
let mut fuel = 0;
for crab in &crabs {
let diff = (crab - pos).abs() as i32;
fuel += diff * (diff + 1) / 2;
}
best = min(fuel, best);
}
println!("{}", best);
}
/// Parses a string into an integer.
fn str_to_int(token: &str) -> i32 {
return token.parse::<i32>().unwrap();
}
|
use std::ops::Bound;
use std::borrow::Cow;
use std::{marker, mem, ptr};
use std::ops::RangeBounds;
use crate::*;
use crate::mdb::error::mdb_result;
use crate::mdb::ffi;
use crate::types::DecodeIgnore;
/// A typed database that accepts only the types it was created with.
///
/// # Example: Iterate over databases entries
///
/// In this example we store numbers in big endian this way those are ordered.
/// Thanks to their bytes representation, heed is able to iterate over them
/// from the lowest to the highest.
///
/// ```
/// # use std::fs;
/// # use std::path::Path;
/// # use heed::EnvOpenOptions;
/// use heed::Database;
/// use heed::types::*;
/// use heed::byteorder::BigEndian;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # fs::create_dir_all(Path::new("target").join("database.mdb"))?;
/// # let env = EnvOpenOptions::new()
/// # .map_size(10 * 1024 * 1024) // 10MB
/// # .max_dbs(3000)
/// # .open(Path::new("target").join("database.mdb"))?;
/// type BEI64 = I64<BigEndian>;
///
/// let db: Database<OwnedType<BEI64>, Unit> = env.create_database(Some("big-endian-iter"))?;
///
/// let mut wtxn = env.write_txn()?;
/// # db.clear(&mut wtxn)?;
/// db.put(&mut wtxn, &BEI64::new(68), &())?;
/// db.put(&mut wtxn, &BEI64::new(35), &())?;
/// db.put(&mut wtxn, &BEI64::new(0), &())?;
/// db.put(&mut wtxn, &BEI64::new(42), &())?;
///
/// // you can iterate over database entries in order
/// let rets: Result<_, _> = db.iter(&wtxn)?.collect();
/// let rets: Vec<(BEI64, _)> = rets?;
///
/// let expected = vec![
/// (BEI64::new(0), ()),
/// (BEI64::new(35), ()),
/// (BEI64::new(42), ()),
/// (BEI64::new(68), ()),
/// ];
///
/// assert_eq!(rets, expected);
/// wtxn.commit()?;
/// # Ok(()) }
/// ```
///
/// # Example: Iterate over and delete ranges of entries
///
/// Discern also support ranges and ranges deletions.
/// Same configuration as above, numbers are ordered, therefore it is safe to specify
/// a range and be able to iterate over and/or delete it.
///
/// ```
/// # use std::fs;
/// # use std::path::Path;
/// # use heed::EnvOpenOptions;
/// use heed::Database;
/// use heed::types::*;
/// use heed::byteorder::BigEndian;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # fs::create_dir_all(Path::new("target").join("database.mdb"))?;
/// # let env = EnvOpenOptions::new()
/// # .map_size(10 * 1024 * 1024) // 10MB
/// # .max_dbs(3000)
/// # .open(Path::new("target").join("database.mdb"))?;
/// type BEI64 = I64<BigEndian>;
///
/// let db: Database<OwnedType<BEI64>, Unit> = env.create_database(Some("big-endian-iter"))?;
///
/// let mut wtxn = env.write_txn()?;
/// # db.clear(&mut wtxn)?;
/// db.put(&mut wtxn, &BEI64::new(0), &())?;
/// db.put(&mut wtxn, &BEI64::new(68), &())?;
/// db.put(&mut wtxn, &BEI64::new(35), &())?;
/// db.put(&mut wtxn, &BEI64::new(42), &())?;
///
/// // you can iterate over ranges too!!!
/// let range = BEI64::new(35)..=BEI64::new(42);
/// let rets: Result<_, _> = db.range(&wtxn, range)?.collect();
/// let rets: Vec<(BEI64, _)> = rets?;
///
/// let expected = vec![
/// (BEI64::new(35), ()),
/// (BEI64::new(42), ()),
/// ];
///
/// assert_eq!(rets, expected);
///
/// // even delete a range of keys
/// let range = BEI64::new(35)..=BEI64::new(42);
/// let deleted: usize = db.delete_range(&mut wtxn, range)?;
///
/// let rets: Result<_, _> = db.iter(&wtxn)?.collect();
/// let rets: Vec<(BEI64, _)> = rets?;
///
/// let expected = vec![
/// (BEI64::new(0), ()),
/// (BEI64::new(68), ()),
/// ];
///
/// assert_eq!(deleted, 2);
/// assert_eq!(rets, expected);
///
/// wtxn.commit()?;
/// # Ok(()) }
/// ```
pub struct Database<KC, DC> {
env_ident: usize,
dbi: ffi::MDB_dbi,
marker: marker::PhantomData<(KC, DC)>,
}
impl<KC, DC> Database<KC, DC> {
pub(crate) fn new(env_ident: usize, dbi: ffi::MDB_dbi) -> Database<KC, DC> {
Database { env_ident, dbi, marker: std::marker::PhantomData }
}
/// Retrieve the sequence of a database.
///
/// This function allows to retrieve the unique positive integer of this database.
/// You can see an example usage on the `PolyDatabase::sequence` method documentation.
#[cfg(all(feature = "mdbx", not(feature = "lmdb")))]
pub fn sequence<T>(&self, txn: &RoTxn<T>) -> Result<u64> {
assert_eq!(self.env_ident, txn.env.env_mut_ptr() as usize);
let mut value = mem::MaybeUninit::uninit();
let result = unsafe {
mdb_result(ffi::mdbx_dbi_sequence(
txn.txn,
self.dbi,
value.as_mut_ptr(),
0, // increment must be 0 for read-only transactions
))
};
match result {
Ok(()) => unsafe { Ok(value.assume_init()) },
Err(e) => Err(e.into()),
}
}
/// Increment the sequence of a database.
///
/// This function allows to create a linear sequence of a unique positive integer
/// for this database. Sequence changes become visible outside the current write
/// transaction after it is committed, and discarded on abort.
/// You can see an example usage on the `PolyDatabase::increase_sequence` method documentation.
///
/// Returns `Some` with the previous value and `None` if increasing the value
/// resulted in an overflow an therefore cannot be executed.
#[cfg(all(feature = "mdbx", not(feature = "lmdb")))]
pub fn increase_sequence<T>(&self, txn: &mut RwTxn<T>, increment: u64) -> Result<Option<u64>> {
assert_eq!(self.env_ident, txn.txn.env.env_mut_ptr() as usize);
use crate::mdb::error::Error;
let mut value = mem::MaybeUninit::uninit();
let result = unsafe {
mdb_result(ffi::mdbx_dbi_sequence(
txn.txn.txn,
self.dbi,
value.as_mut_ptr(),
increment,
))
};
match result {
Ok(()) => unsafe { Ok(Some(value.assume_init())) },
Err(Error::Other(c)) if c == i32::max_value() => Ok(None), // MDBX_RESULT_TRUE
Err(e) => Err(e.into()),
}
}
/// Retrieves the value associated with a key.
///
/// If the key does not exist, then `None` is returned.
///
/// ```
/// # use std::fs;
/// # use std::path::Path;
/// # use heed::EnvOpenOptions;
/// use heed::Database;
/// use heed::types::*;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # fs::create_dir_all(Path::new("target").join("database.mdb"))?;
/// # let env = EnvOpenOptions::new()
/// # .map_size(10 * 1024 * 1024) // 10MB
/// # .max_dbs(3000)
/// # .open(Path::new("target").join("database.mdb"))?;
/// let db: Database<Str, OwnedType<i32>> = env.create_database(Some("get-i32"))?;
///
/// let mut wtxn = env.write_txn()?;
/// # db.clear(&mut wtxn)?;
/// db.put(&mut wtxn, &"i-am-forty-two", &42)?;
/// db.put(&mut wtxn, &"i-am-twenty-seven", &27)?;
///
/// let ret = db.get(&wtxn, &"i-am-forty-two")?;
/// assert_eq!(ret, Some(42));
///
/// let ret = db.get(&wtxn, &"i-am-twenty-one")?;
/// assert_eq!(ret, None);
///
/// wtxn.commit()?;
/// # Ok(()) }
/// ```
pub fn get<'txn, T>(&self, txn: &'txn RoTxn<T>, key: &KC::EItem) -> Result<Option<DC::DItem>>
where
KC: BytesEncode,
DC: BytesDecode<'txn>,
{
assert_eq!(self.env_ident, txn.env.env_mut_ptr() as usize);
let key_bytes: Cow<[u8]> = KC::bytes_encode(&key).map_err(Error::Encoding)?;
let mut key_val = unsafe { crate::into_val(&key_bytes) };
let mut data_val = mem::MaybeUninit::uninit();
let result = unsafe {
mdb_result(ffi::mdb_get(
txn.txn,
self.dbi,
&mut key_val,
data_val.as_mut_ptr(),
))
};
match result {
Ok(()) => {
let data = unsafe { crate::from_val(data_val.assume_init()) };
let data = DC::bytes_decode(data).map_err(Error::Decoding)?;
Ok(Some(data))
}
Err(e) if e.not_found() => Ok(None),
Err(e) => Err(e.into()),
}
}
/// Retrieves the key/value pair lower than the given one in this database.
///
/// If the database if empty or there is no key lower than the given one,
/// then `None` is returned.
///
/// Comparisons are made by using the bytes representation of the key.
///
/// ```
/// # use std::fs;
/// # use std::path::Path;
/// # use heed::EnvOpenOptions;
/// use heed::Database;
/// use heed::types::*;
/// use heed::byteorder::BigEndian;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # fs::create_dir_all(Path::new("target").join("database.mdb"))?;
/// # let env = EnvOpenOptions::new()
/// # .map_size(10 * 1024 * 1024) // 10MB
/// # .max_dbs(3000)
/// # .open(Path::new("target").join("database.mdb"))?;
/// type BEU32 = U32<BigEndian>;
///
/// let db = env.create_database::<OwnedType<BEU32>, Unit>(Some("get-lt-u32"))?;
///
/// let mut wtxn = env.write_txn()?;
/// # db.clear(&mut wtxn)?;
/// db.put(&mut wtxn, &BEU32::new(27), &())?;
/// db.put(&mut wtxn, &BEU32::new(42), &())?;
/// db.put(&mut wtxn, &BEU32::new(43), &())?;
///
/// let ret = db.get_lower_than(&wtxn, &BEU32::new(4404))?;
/// assert_eq!(ret, Some((BEU32::new(43), ())));
///
/// let ret = db.get_lower_than(&wtxn, &BEU32::new(43))?;
/// assert_eq!(ret, Some((BEU32::new(42), ())));
///
/// let ret = db.get_lower_than(&wtxn, &BEU32::new(27))?;
/// assert_eq!(ret, None);
///
/// wtxn.commit()?;
/// # Ok(()) }
/// ```
pub fn get_lower_than<'txn, T>(
&self,
txn: &'txn RoTxn<T>,
key: &KC::EItem,
) -> Result<Option<(KC::DItem, DC::DItem)>>
where
KC: BytesEncode + BytesDecode<'txn>,
DC: BytesDecode<'txn>,
{
assert_eq!(self.env_ident, txn.env.env_mut_ptr() as usize);
let mut cursor = RoCursor::new(txn, self.dbi)?;
let key_bytes: Cow<[u8]> = KC::bytes_encode(&key).map_err(Error::Encoding)?;
cursor.move_on_key_greater_than_or_equal_to(&key_bytes)?;
match cursor.move_on_prev() {
Ok(Some((key, data))) => match (KC::bytes_decode(key), DC::bytes_decode(data)) {
(Ok(key), Ok(data)) => Ok(Some((key, data))),
(Err(e), _) | (_, Err(e)) => Err(Error::Decoding(e)),
},
Ok(None) => Ok(None),
Err(e) => Err(e),
}
}
/// Retrieves the key/value pair lower than or equal to the given one in this database.
///
/// If the database if empty or there is no key lower than or equal to the given one,
/// then `None` is returned.
///
/// Comparisons are made by using the bytes representation of the key.
///
/// ```
/// # use std::fs;
/// # use std::path::Path;
/// # use heed::EnvOpenOptions;
/// use heed::Database;
/// use heed::types::*;
/// use heed::byteorder::BigEndian;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # fs::create_dir_all(Path::new("target").join("database.mdb"))?;
/// # let env = EnvOpenOptions::new()
/// # .map_size(10 * 1024 * 1024) // 10MB
/// # .max_dbs(3000)
/// # .open(Path::new("target").join("database.mdb"))?;
/// type BEU32 = U32<BigEndian>;
///
/// let db = env.create_database::<OwnedType<BEU32>, Unit>(Some("get-lt-u32"))?;
///
/// let mut wtxn = env.write_txn()?;
/// # db.clear(&mut wtxn)?;
/// db.put(&mut wtxn, &BEU32::new(27), &())?;
/// db.put(&mut wtxn, &BEU32::new(42), &())?;
/// db.put(&mut wtxn, &BEU32::new(43), &())?;
///
/// let ret = db.get_lower_than_or_equal_to(&wtxn, &BEU32::new(4404))?;
/// assert_eq!(ret, Some((BEU32::new(43), ())));
///
/// let ret = db.get_lower_than_or_equal_to(&wtxn, &BEU32::new(43))?;
/// assert_eq!(ret, Some((BEU32::new(43), ())));
///
/// let ret = db.get_lower_than_or_equal_to(&wtxn, &BEU32::new(26))?;
/// assert_eq!(ret, None);
///
/// wtxn.commit()?;
/// # Ok(()) }
/// ```
pub fn get_lower_than_or_equal_to<'txn, T>(
&self,
txn: &'txn RoTxn<T>,
key: &KC::EItem,
) -> Result<Option<(KC::DItem, DC::DItem)>>
where
KC: BytesEncode + BytesDecode<'txn>,
DC: BytesDecode<'txn>,
{
assert_eq!(self.env_ident, txn.env.env_mut_ptr() as usize);
let mut cursor = RoCursor::new(txn, self.dbi)?;
let key_bytes: Cow<[u8]> = KC::bytes_encode(&key).map_err(Error::Encoding)?;
let result = match cursor.move_on_key_greater_than_or_equal_to(&key_bytes) {
Ok(Some((key, data))) if key == &key_bytes[..] => Ok(Some((key, data))),
Ok(_) => cursor.move_on_prev(),
Err(e) => Err(e),
};
match result {
Ok(Some((key, data))) => match (KC::bytes_decode(key), DC::bytes_decode(data)) {
(Ok(key), Ok(data)) => Ok(Some((key, data))),
(Err(e), _) | (_, Err(e)) => Err(Error::Decoding(e)),
},
Ok(None) => Ok(None),
Err(e) => Err(e),
}
}
/// Retrieves the key/value pair greater than the given one in this database.
///
/// If the database if empty or there is no key greater than the given one,
/// then `None` is returned.
///
/// Comparisons are made by using the bytes representation of the key.
///
/// ```
/// # use std::fs;
/// # use std::path::Path;
/// # use heed::EnvOpenOptions;
/// use heed::Database;
/// use heed::types::*;
/// use heed::byteorder::BigEndian;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # fs::create_dir_all(Path::new("target").join("database.mdb"))?;
/// # let env = EnvOpenOptions::new()
/// # .map_size(10 * 1024 * 1024) // 10MB
/// # .max_dbs(3000)
/// # .open(Path::new("target").join("database.mdb"))?;
/// type BEU32 = U32<BigEndian>;
///
/// let db = env.create_database::<OwnedType<BEU32>, Unit>(Some("get-lt-u32"))?;
///
/// let mut wtxn = env.write_txn()?;
/// # db.clear(&mut wtxn)?;
/// db.put(&mut wtxn, &BEU32::new(27), &())?;
/// db.put(&mut wtxn, &BEU32::new(42), &())?;
/// db.put(&mut wtxn, &BEU32::new(43), &())?;
///
/// let ret = db.get_greater_than(&wtxn, &BEU32::new(0))?;
/// assert_eq!(ret, Some((BEU32::new(27), ())));
///
/// let ret = db.get_greater_than(&wtxn, &BEU32::new(42))?;
/// assert_eq!(ret, Some((BEU32::new(43), ())));
///
/// let ret = db.get_greater_than(&wtxn, &BEU32::new(43))?;
/// assert_eq!(ret, None);
///
/// wtxn.commit()?;
/// # Ok(()) }
/// ```
pub fn get_greater_than<'txn, T>(
&self,
txn: &'txn RoTxn<T>,
key: &KC::EItem,
) -> Result<Option<(KC::DItem, DC::DItem)>>
where
KC: BytesEncode + BytesDecode<'txn>,
DC: BytesDecode<'txn>,
{
assert_eq!(self.env_ident, txn.env.env_mut_ptr() as usize);
let mut cursor = RoCursor::new(txn, self.dbi)?;
let key_bytes: Cow<[u8]> = KC::bytes_encode(&key).map_err(Error::Encoding)?;
let entry = match cursor.move_on_key_greater_than_or_equal_to(&key_bytes)? {
Some((key, data)) if key > &key_bytes[..] => Some((key, data)),
Some((_key, _data)) => cursor.move_on_next()?,
None => None,
};
match entry {
Some((key, data)) => match (KC::bytes_decode(key), DC::bytes_decode(data)) {
(Ok(key), Ok(data)) => Ok(Some((key, data))),
(Err(e), _) | (_, Err(e)) => Err(Error::Decoding(e)),
},
None => Ok(None),
}
}
/// Retrieves the key/value pair greater than or equal to the given one in this database.
///
/// If the database if empty or there is no key greater than or equal to the given one,
/// then `None` is returned.
///
/// Comparisons are made by using the bytes representation of the key.
///
/// ```
/// # use std::fs;
/// # use std::path::Path;
/// # use heed::EnvOpenOptions;
/// use heed::Database;
/// use heed::types::*;
/// use heed::byteorder::BigEndian;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # fs::create_dir_all(Path::new("target").join("database.mdb"))?;
/// # let env = EnvOpenOptions::new()
/// # .map_size(10 * 1024 * 1024) // 10MB
/// # .max_dbs(3000)
/// # .open(Path::new("target").join("database.mdb"))?;
/// type BEU32 = U32<BigEndian>;
///
/// let db = env.create_database::<OwnedType<BEU32>, Unit>(Some("get-lt-u32"))?;
///
/// let mut wtxn = env.write_txn()?;
/// # db.clear(&mut wtxn)?;
/// db.put(&mut wtxn, &BEU32::new(27), &())?;
/// db.put(&mut wtxn, &BEU32::new(42), &())?;
/// db.put(&mut wtxn, &BEU32::new(43), &())?;
///
/// let ret = db.get_greater_than_or_equal_to(&wtxn, &BEU32::new(0))?;
/// assert_eq!(ret, Some((BEU32::new(27), ())));
///
/// let ret = db.get_greater_than_or_equal_to(&wtxn, &BEU32::new(42))?;
/// assert_eq!(ret, Some((BEU32::new(42), ())));
///
/// let ret = db.get_greater_than_or_equal_to(&wtxn, &BEU32::new(44))?;
/// assert_eq!(ret, None);
///
/// wtxn.commit()?;
/// # Ok(()) }
/// ```
pub fn get_greater_than_or_equal_to<'txn, T>(
&self,
txn: &'txn RoTxn<T>,
key: &KC::EItem,
) -> Result<Option<(KC::DItem, DC::DItem)>>
where
KC: BytesEncode + BytesDecode<'txn>,
DC: BytesDecode<'txn>,
{
assert_eq!(self.env_ident, txn.env.env_mut_ptr() as usize);
let mut cursor = RoCursor::new(txn, self.dbi)?;
let key_bytes: Cow<[u8]> = KC::bytes_encode(&key).map_err(Error::Encoding)?;
match cursor.move_on_key_greater_than_or_equal_to(&key_bytes) {
Ok(Some((key, data))) => match (KC::bytes_decode(key), DC::bytes_decode(data)) {
(Ok(key), Ok(data)) => Ok(Some((key, data))),
(Err(e), _) | (_, Err(e)) => Err(Error::Decoding(e)),
},
Ok(None) => Ok(None),
Err(e) => Err(e),
}
}
/// Retrieves the first key/value pair of this database.
///
/// If the database if empty, then `None` is returned.
///
/// Comparisons are made by using the bytes representation of the key.
///
/// ```
/// # use std::fs;
/// # use std::path::Path;
/// # use heed::EnvOpenOptions;
/// use heed::Database;
/// use heed::types::*;
/// use heed::byteorder::BigEndian;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # fs::create_dir_all(Path::new("target").join("database.mdb"))?;
/// # let env = EnvOpenOptions::new()
/// # .map_size(10 * 1024 * 1024) // 10MB
/// # .max_dbs(3000)
/// # .open(Path::new("target").join("database.mdb"))?;
/// type BEI32 = I32<BigEndian>;
///
/// let db: Database<OwnedType<BEI32>, Str> = env.create_database(Some("first-i32"))?;
///
/// let mut wtxn = env.write_txn()?;
/// # db.clear(&mut wtxn)?;
/// db.put(&mut wtxn, &BEI32::new(42), &"i-am-forty-two")?;
/// db.put(&mut wtxn, &BEI32::new(27), &"i-am-twenty-seven")?;
///
/// let ret = db.first(&wtxn)?;
/// assert_eq!(ret, Some((BEI32::new(27), "i-am-twenty-seven")));
///
/// wtxn.commit()?;
/// # Ok(()) }
/// ```
pub fn first<'txn, T>(&self, txn: &'txn RoTxn<T>) -> Result<Option<(KC::DItem, DC::DItem)>>
where
KC: BytesDecode<'txn>,
DC: BytesDecode<'txn>,
{
assert_eq!(self.env_ident, txn.env.env_mut_ptr() as usize);
let mut cursor = RoCursor::new(txn, self.dbi)?;
match cursor.move_on_first() {
Ok(Some((key, data))) => match (KC::bytes_decode(key), DC::bytes_decode(data)) {
(Ok(key), Ok(data)) => Ok(Some((key, data))),
(Err(e), _) | (_, Err(e)) => Err(Error::Decoding(e)),
},
Ok(None) => Ok(None),
Err(e) => Err(e),
}
}
/// Retrieves the last key/value pair of this database.
///
/// If the database if empty, then `None` is returned.
///
/// Comparisons are made by using the bytes representation of the key.
///
/// ```
/// # use std::fs;
/// # use std::path::Path;
/// # use heed::EnvOpenOptions;
/// use heed::Database;
/// use heed::types::*;
/// use heed::byteorder::BigEndian;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # fs::create_dir_all(Path::new("target").join("database.mdb"))?;
/// # let env = EnvOpenOptions::new()
/// # .map_size(10 * 1024 * 1024) // 10MB
/// # .max_dbs(3000)
/// # .open(Path::new("target").join("database.mdb"))?;
/// type BEI32 = I32<BigEndian>;
///
/// let db: Database<OwnedType<BEI32>, Str> = env.create_database(Some("last-i32"))?;
///
/// let mut wtxn = env.write_txn()?;
/// # db.clear(&mut wtxn)?;
/// db.put(&mut wtxn, &BEI32::new(42), &"i-am-forty-two")?;
/// db.put(&mut wtxn, &BEI32::new(27), &"i-am-twenty-seven")?;
///
/// let ret = db.last(&wtxn)?;
/// assert_eq!(ret, Some((BEI32::new(42), "i-am-forty-two")));
///
/// wtxn.commit()?;
/// # Ok(()) }
/// ```
pub fn last<'txn, T>(&self, txn: &'txn RoTxn<T>) -> Result<Option<(KC::DItem, DC::DItem)>>
where
KC: BytesDecode<'txn>,
DC: BytesDecode<'txn>,
{
assert_eq!(self.env_ident, txn.env.env_mut_ptr() as usize);
let mut cursor = RoCursor::new(txn, self.dbi)?;
match cursor.move_on_last() {
Ok(Some((key, data))) => match (KC::bytes_decode(key), DC::bytes_decode(data)) {
(Ok(key), Ok(data)) => Ok(Some((key, data))),
(Err(e), _) | (_, Err(e)) => Err(Error::Decoding(e)),
},
Ok(None) => Ok(None),
Err(e) => Err(e),
}
}
/// Returns the number of elements in this database.
///
/// ```
/// # use std::fs;
/// # use std::path::Path;
/// # use heed::EnvOpenOptions;
/// use heed::Database;
/// use heed::types::*;
/// use heed::byteorder::BigEndian;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # fs::create_dir_all(Path::new("target").join("database.mdb"))?;
/// # let env = EnvOpenOptions::new()
/// # .map_size(10 * 1024 * 1024) // 10MB
/// # .max_dbs(3000)
/// # .open(Path::new("target").join("database.mdb"))?;
/// type BEI32 = I32<BigEndian>;
///
/// let db: Database<OwnedType<BEI32>, Str> = env.create_database(Some("iter-i32"))?;
///
/// let mut wtxn = env.write_txn()?;
/// # db.clear(&mut wtxn)?;
/// db.put(&mut wtxn, &BEI32::new(42), &"i-am-forty-two")?;
/// db.put(&mut wtxn, &BEI32::new(27), &"i-am-twenty-seven")?;
/// db.put(&mut wtxn, &BEI32::new(13), &"i-am-thirteen")?;
/// db.put(&mut wtxn, &BEI32::new(521), &"i-am-five-hundred-and-twenty-one")?;
///
/// let ret = db.len(&wtxn)?;
/// assert_eq!(ret, 4);
///
/// db.delete(&mut wtxn, &BEI32::new(27))?;
///
/// let ret = db.len(&wtxn)?;
/// assert_eq!(ret, 3);
///
/// wtxn.commit()?;
///
/// # Ok(()) }
/// ```
pub fn len<'txn, T>(&self, txn: &'txn RoTxn<T>) -> Result<u64> {
assert_eq!(self.env_ident, txn.env.env_mut_ptr() as usize);
let mut db_stat = mem::MaybeUninit::uninit();
#[cfg(all(feature = "mdbx", not(feature = "lmdb")))]
let result = unsafe {
mdb_result(ffi::mdb_stat(
txn.txn,
self.dbi,
db_stat.as_mut_ptr(),
std::mem::size_of::<ffi::MDB_Stat>(),
))
};
#[cfg(all(feature = "lmdb", not(feature = "mdbx")))]
let result = unsafe {
mdb_result(ffi::mdb_stat(
txn.txn,
self.dbi,
db_stat.as_mut_ptr(),
))
};
match result {
Ok(()) => {
let stats = unsafe { db_stat.assume_init() };
Ok(stats.ms_entries as u64)
}
Err(e) => Err(e.into()),
}
}
/// Returns `true` if and only if this database is empty.
///
/// ```
/// # use std::fs;
/// # use std::path::Path;
/// # use heed::EnvOpenOptions;
/// use heed::Database;
/// use heed::types::*;
/// use heed::byteorder::BigEndian;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # fs::create_dir_all(Path::new("target").join("database.mdb"))?;
/// # let env = EnvOpenOptions::new()
/// # .map_size(10 * 1024 * 1024) // 10MB
/// # .max_dbs(3000)
/// # .open(Path::new("target").join("database.mdb"))?;
/// type BEI32 = I32<BigEndian>;
///
/// let db: Database<OwnedType<BEI32>, Str> = env.create_database(Some("iter-i32"))?;
///
/// let mut wtxn = env.write_txn()?;
/// # db.clear(&mut wtxn)?;
/// db.put(&mut wtxn, &BEI32::new(42), &"i-am-forty-two")?;
/// db.put(&mut wtxn, &BEI32::new(27), &"i-am-twenty-seven")?;
/// db.put(&mut wtxn, &BEI32::new(13), &"i-am-thirteen")?;
/// db.put(&mut wtxn, &BEI32::new(521), &"i-am-five-hundred-and-twenty-one")?;
///
/// let ret = db.is_empty(&wtxn)?;
/// assert_eq!(ret, false);
///
/// db.clear(&mut wtxn)?;
///
/// let ret = db.is_empty(&wtxn)?;
/// assert_eq!(ret, true);
///
/// wtxn.commit()?;
/// # Ok(()) }
/// ```
pub fn is_empty<'txn, T>(&self, txn: &'txn RoTxn<T>) -> Result<bool> {
assert_eq!(self.env_ident, txn.env.env_mut_ptr() as usize);
let mut cursor = RoCursor::new(txn, self.dbi)?;
match cursor.move_on_first()? {
Some(_) => Ok(false),
None => Ok(true),
}
}
/// Return a lexicographically ordered iterator of all key-value pairs in this database.
///
/// ```
/// # use std::fs;
/// # use std::path::Path;
/// # use heed::EnvOpenOptions;
/// use heed::Database;
/// use heed::types::*;
/// use heed::byteorder::BigEndian;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # fs::create_dir_all(Path::new("target").join("database.mdb"))?;
/// # let env = EnvOpenOptions::new()
/// # .map_size(10 * 1024 * 1024) // 10MB
/// # .max_dbs(3000)
/// # .open(Path::new("target").join("database.mdb"))?;
/// type BEI32 = I32<BigEndian>;
///
/// let db: Database<OwnedType<BEI32>, Str> = env.create_database(Some("iter-i32"))?;
///
/// let mut wtxn = env.write_txn()?;
/// # db.clear(&mut wtxn)?;
/// db.put(&mut wtxn, &BEI32::new(42), &"i-am-forty-two")?;
/// db.put(&mut wtxn, &BEI32::new(27), &"i-am-twenty-seven")?;
/// db.put(&mut wtxn, &BEI32::new(13), &"i-am-thirteen")?;
///
/// let mut iter = db.iter(&wtxn)?;
/// assert_eq!(iter.next().transpose()?, Some((BEI32::new(13), "i-am-thirteen")));
/// assert_eq!(iter.next().transpose()?, Some((BEI32::new(27), "i-am-twenty-seven")));
/// assert_eq!(iter.next().transpose()?, Some((BEI32::new(42), "i-am-forty-two")));
/// assert_eq!(iter.next().transpose()?, None);
///
/// drop(iter);
/// wtxn.commit()?;
/// # Ok(()) }
/// ```
pub fn iter<'txn, T>(&self, txn: &'txn RoTxn<T>) -> Result<RoIter<'txn, KC, DC>> {
assert_eq!(self.env_ident, txn.env.env_mut_ptr() as usize);
RoCursor::new(txn, self.dbi).map(|cursor| RoIter::new(cursor))
}
/// Return a mutable lexicographically ordered iterator of all key-value pairs in this database.
///
/// ```
/// # use std::fs;
/// # use std::path::Path;
/// # use heed::EnvOpenOptions;
/// use heed::Database;
/// use heed::types::*;
/// use heed::byteorder::BigEndian;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # fs::create_dir_all(Path::new("target").join("database.mdb"))?;
/// # let env = EnvOpenOptions::new()
/// # .map_size(10 * 1024 * 1024) // 10MB
/// # .max_dbs(3000)
/// # .open(Path::new("target").join("database.mdb"))?;
/// type BEI32 = I32<BigEndian>;
///
/// let db: Database<OwnedType<BEI32>, Str> = env.create_database(Some("iter-i32"))?;
///
/// let mut wtxn = env.write_txn()?;
/// # db.clear(&mut wtxn)?;
/// db.put(&mut wtxn, &BEI32::new(42), &"i-am-forty-two")?;
/// db.put(&mut wtxn, &BEI32::new(27), &"i-am-twenty-seven")?;
/// db.put(&mut wtxn, &BEI32::new(13), &"i-am-thirteen")?;
///
/// let mut iter = db.iter_mut(&mut wtxn)?;
/// assert_eq!(iter.next().transpose()?, Some((BEI32::new(13), "i-am-thirteen")));
/// let ret = iter.del_current()?;
/// assert!(ret);
///
/// assert_eq!(iter.next().transpose()?, Some((BEI32::new(27), "i-am-twenty-seven")));
/// assert_eq!(iter.next().transpose()?, Some((BEI32::new(42), "i-am-forty-two")));
/// let ret = iter.put_current(&BEI32::new(42), &"i-am-the-new-forty-two")?;
/// assert!(ret);
///
/// assert_eq!(iter.next().transpose()?, None);
///
/// drop(iter);
///
/// let ret = db.get(&wtxn, &BEI32::new(13))?;
/// assert_eq!(ret, None);
///
/// let ret = db.get(&wtxn, &BEI32::new(42))?;
/// assert_eq!(ret, Some("i-am-the-new-forty-two"));
///
/// wtxn.commit()?;
/// # Ok(()) }
/// ```
pub fn iter_mut<'txn, T>(&self, txn: &'txn mut RwTxn<T>) -> Result<RwIter<'txn, KC, DC>> {
assert_eq!(self.env_ident, txn.txn.env.env_mut_ptr() as usize);
RwCursor::new(txn, self.dbi).map(|cursor| RwIter::new(cursor))
}
/// Return a reversed lexicographically ordered iterator of all key-value pairs in this database.
///
/// ```
/// # use std::fs;
/// # use std::path::Path;
/// # use heed::EnvOpenOptions;
/// use heed::Database;
/// use heed::types::*;
/// use heed::byteorder::BigEndian;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # fs::create_dir_all(Path::new("target").join("database.mdb"))?;
/// # let env = EnvOpenOptions::new()
/// # .map_size(10 * 1024 * 1024) // 10MB
/// # .max_dbs(3000)
/// # .open(Path::new("target").join("database.mdb"))?;
/// type BEI32 = I32<BigEndian>;
///
/// let db: Database<OwnedType<BEI32>, Str> = env.create_database(Some("iter-i32"))?;
///
/// let mut wtxn = env.write_txn()?;
/// # db.clear(&mut wtxn)?;
/// db.put(&mut wtxn, &BEI32::new(42), &"i-am-forty-two")?;
/// db.put(&mut wtxn, &BEI32::new(27), &"i-am-twenty-seven")?;
/// db.put(&mut wtxn, &BEI32::new(13), &"i-am-thirteen")?;
///
/// let mut iter = db.rev_iter(&wtxn)?;
/// assert_eq!(iter.next().transpose()?, Some((BEI32::new(42), "i-am-forty-two")));
/// assert_eq!(iter.next().transpose()?, Some((BEI32::new(27), "i-am-twenty-seven")));
/// assert_eq!(iter.next().transpose()?, Some((BEI32::new(13), "i-am-thirteen")));
/// assert_eq!(iter.next().transpose()?, None);
///
/// drop(iter);
/// wtxn.commit()?;
/// # Ok(()) }
/// ```
pub fn rev_iter<'txn, T>(&self, txn: &'txn RoTxn<T>) -> Result<RoRevIter<'txn, KC, DC>> {
assert_eq!(self.env_ident, txn.env.env_mut_ptr() as usize);
RoCursor::new(txn, self.dbi).map(|cursor| RoRevIter::new(cursor))
}
/// Return a mutable reversed lexicographically ordered iterator of all key-value\
/// pairs in this database.
///
/// ```
/// # use std::fs;
/// # use std::path::Path;
/// # use heed::EnvOpenOptions;
/// use heed::Database;
/// use heed::types::*;
/// use heed::byteorder::BigEndian;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # fs::create_dir_all(Path::new("target").join("database.mdb"))?;
/// # let env = EnvOpenOptions::new()
/// # .map_size(10 * 1024 * 1024) // 10MB
/// # .max_dbs(3000)
/// # .open(Path::new("target").join("database.mdb"))?;
/// type BEI32 = I32<BigEndian>;
///
/// let db: Database<OwnedType<BEI32>, Str> = env.create_database(Some("iter-i32"))?;
///
/// let mut wtxn = env.write_txn()?;
/// # db.clear(&mut wtxn)?;
/// db.put(&mut wtxn, &BEI32::new(42), &"i-am-forty-two")?;
/// db.put(&mut wtxn, &BEI32::new(27), &"i-am-twenty-seven")?;
/// db.put(&mut wtxn, &BEI32::new(13), &"i-am-thirteen")?;
///
/// let mut iter = db.rev_iter_mut(&mut wtxn)?;
/// assert_eq!(iter.next().transpose()?, Some((BEI32::new(42), "i-am-forty-two")));
/// let ret = iter.del_current()?;
/// assert!(ret);
///
/// assert_eq!(iter.next().transpose()?, Some((BEI32::new(27), "i-am-twenty-seven")));
/// assert_eq!(iter.next().transpose()?, Some((BEI32::new(13), "i-am-thirteen")));
/// let ret = iter.put_current(&BEI32::new(13), &"i-am-the-new-thirteen")?;
/// assert!(ret);
///
/// assert_eq!(iter.next().transpose()?, None);
///
/// drop(iter);
///
/// let ret = db.get(&wtxn, &BEI32::new(42))?;
/// assert_eq!(ret, None);
///
/// let ret = db.get(&wtxn, &BEI32::new(13))?;
/// assert_eq!(ret, Some("i-am-the-new-thirteen"));
///
/// wtxn.commit()?;
/// # Ok(()) }
/// ```
pub fn rev_iter_mut<'txn, T>(&self, txn: &'txn mut RwTxn<T>) -> Result<RwRevIter<'txn, KC, DC>> {
assert_eq!(self.env_ident, txn.env.env_mut_ptr() as usize);
RwCursor::new(txn, self.dbi).map(|cursor| RwRevIter::new(cursor))
}
/// Return a lexicographically ordered iterator of a range of key-value pairs in this database.
///
/// Comparisons are made by using the bytes representation of the key.
///
/// ```
/// # use std::fs;
/// # use std::path::Path;
/// # use heed::EnvOpenOptions;
/// use heed::Database;
/// use heed::types::*;
/// use heed::byteorder::BigEndian;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # fs::create_dir_all(Path::new("target").join("database.mdb"))?;
/// # let env = EnvOpenOptions::new()
/// # .map_size(10 * 1024 * 1024) // 10MB
/// # .max_dbs(3000)
/// # .open(Path::new("target").join("database.mdb"))?;
/// type BEI32 = I32<BigEndian>;
///
/// let db: Database<OwnedType<BEI32>, Str> = env.create_database(Some("iter-i32"))?;
///
/// let mut wtxn = env.write_txn()?;
/// # db.clear(&mut wtxn)?;
/// db.put(&mut wtxn, &BEI32::new(42), &"i-am-forty-two")?;
/// db.put(&mut wtxn, &BEI32::new(27), &"i-am-twenty-seven")?;
/// db.put(&mut wtxn, &BEI32::new(13), &"i-am-thirteen")?;
/// db.put(&mut wtxn, &BEI32::new(521), &"i-am-five-hundred-and-twenty-one")?;
///
/// let range = BEI32::new(27)..=BEI32::new(42);
/// let mut iter = db.range(&wtxn, range)?;
/// assert_eq!(iter.next().transpose()?, Some((BEI32::new(27), "i-am-twenty-seven")));
/// assert_eq!(iter.next().transpose()?, Some((BEI32::new(42), "i-am-forty-two")));
/// assert_eq!(iter.next().transpose()?, None);
///
/// drop(iter);
/// wtxn.commit()?;
/// # Ok(()) }
/// ```
pub fn range<'txn, T, R>(
&self,
txn: &'txn RoTxn<T>,
range: R,
) -> Result<RoRange<'txn, KC, DC>>
where
KC: BytesEncode,
R: RangeBounds<KC::EItem>,
{
assert_eq!(self.env_ident, txn.env.env_mut_ptr() as usize);
let start_bound = match range.start_bound() {
Bound::Included(bound) => {
let bytes = KC::bytes_encode(bound).map_err(Error::Encoding)?;
Bound::Included(bytes.into_owned())
}
Bound::Excluded(bound) => {
let bytes = KC::bytes_encode(bound).map_err(Error::Encoding)?;
Bound::Excluded(bytes.into_owned())
}
Bound::Unbounded => Bound::Unbounded,
};
let end_bound = match range.end_bound() {
Bound::Included(bound) => {
let bytes = KC::bytes_encode(bound).map_err(Error::Encoding)?;
Bound::Included(bytes.into_owned())
}
Bound::Excluded(bound) => {
let bytes = KC::bytes_encode(bound).map_err(Error::Encoding)?;
Bound::Excluded(bytes.into_owned())
}
Bound::Unbounded => Bound::Unbounded,
};
RoCursor::new(txn, self.dbi).map(|cursor| RoRange::new(cursor, start_bound, end_bound))
}
/// Return a mutable lexicographically ordered iterator of a range of
/// key-value pairs in this database.
///
/// Comparisons are made by using the bytes representation of the key.
///
/// ```
/// # use std::fs;
/// # use std::path::Path;
/// # use heed::EnvOpenOptions;
/// use heed::Database;
/// use heed::types::*;
/// use heed::byteorder::BigEndian;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # fs::create_dir_all(Path::new("target").join("database.mdb"))?;
/// # let env = EnvOpenOptions::new()
/// # .map_size(10 * 1024 * 1024) // 10MB
/// # .max_dbs(3000)
/// # .open(Path::new("target").join("database.mdb"))?;
/// type BEI32 = I32<BigEndian>;
///
/// let db: Database<OwnedType<BEI32>, Str> = env.create_database(Some("iter-i32"))?;
///
/// let mut wtxn = env.write_txn()?;
/// # db.clear(&mut wtxn)?;
/// db.put(&mut wtxn, &BEI32::new(42), &"i-am-forty-two")?;
/// db.put(&mut wtxn, &BEI32::new(27), &"i-am-twenty-seven")?;
/// db.put(&mut wtxn, &BEI32::new(13), &"i-am-thirteen")?;
/// db.put(&mut wtxn, &BEI32::new(521), &"i-am-five-hundred-and-twenty-one")?;
///
/// let range = BEI32::new(27)..=BEI32::new(42);
/// let mut range = db.range_mut(&mut wtxn, range)?;
/// assert_eq!(range.next().transpose()?, Some((BEI32::new(27), "i-am-twenty-seven")));
/// let ret = range.del_current()?;
/// assert!(ret);
/// assert_eq!(range.next().transpose()?, Some((BEI32::new(42), "i-am-forty-two")));
/// let ret = range.put_current(&BEI32::new(42), &"i-am-the-new-forty-two")?;
/// assert!(ret);
///
/// assert_eq!(range.next().transpose()?, None);
/// drop(range);
///
///
/// let mut iter = db.iter(&wtxn)?;
/// assert_eq!(iter.next().transpose()?, Some((BEI32::new(13), "i-am-thirteen")));
/// assert_eq!(iter.next().transpose()?, Some((BEI32::new(42), "i-am-the-new-forty-two")));
/// assert_eq!(iter.next().transpose()?, Some((BEI32::new(521), "i-am-five-hundred-and-twenty-one")));
/// assert_eq!(iter.next().transpose()?, None);
///
/// drop(iter);
/// wtxn.commit()?;
/// # Ok(()) }
/// ```
pub fn range_mut<'txn, T, R>(
&self,
txn: &'txn mut RwTxn<T>,
range: R,
) -> Result<RwRange<'txn, KC, DC>>
where
KC: BytesEncode,
R: RangeBounds<KC::EItem>,
{
assert_eq!(self.env_ident, txn.txn.env.env_mut_ptr() as usize);
let start_bound = match range.start_bound() {
Bound::Included(bound) => {
let bytes = KC::bytes_encode(bound).map_err(Error::Encoding)?;
Bound::Included(bytes.into_owned())
}
Bound::Excluded(bound) => {
let bytes = KC::bytes_encode(bound).map_err(Error::Encoding)?;
Bound::Excluded(bytes.into_owned())
}
Bound::Unbounded => Bound::Unbounded,
};
let end_bound = match range.end_bound() {
Bound::Included(bound) => {
let bytes = KC::bytes_encode(bound).map_err(Error::Encoding)?;
Bound::Included(bytes.into_owned())
}
Bound::Excluded(bound) => {
let bytes = KC::bytes_encode(bound).map_err(Error::Encoding)?;
Bound::Excluded(bytes.into_owned())
}
Bound::Unbounded => Bound::Unbounded,
};
RwCursor::new(txn, self.dbi).map(|cursor| RwRange::new(cursor, start_bound, end_bound))
}
/// Return a reversed lexicographically ordered iterator of a range of key-value
/// pairs in this database.
///
/// Comparisons are made by using the bytes representation of the key.
///
/// ```
/// # use std::fs;
/// # use std::path::Path;
/// # use heed::EnvOpenOptions;
/// use heed::Database;
/// use heed::types::*;
/// use heed::byteorder::BigEndian;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # fs::create_dir_all(Path::new("target").join("database.mdb"))?;
/// # let env = EnvOpenOptions::new()
/// # .map_size(10 * 1024 * 1024) // 10MB
/// # .max_dbs(3000)
/// # .open(Path::new("target").join("database.mdb"))?;
/// type BEI32 = I32<BigEndian>;
///
/// let db: Database<OwnedType<BEI32>, Str> = env.create_database(Some("iter-i32"))?;
///
/// let mut wtxn = env.write_txn()?;
/// # db.clear(&mut wtxn)?;
/// db.put(&mut wtxn, &BEI32::new(42), &"i-am-forty-two")?;
/// db.put(&mut wtxn, &BEI32::new(27), &"i-am-twenty-seven")?;
/// db.put(&mut wtxn, &BEI32::new(13), &"i-am-thirteen")?;
/// db.put(&mut wtxn, &BEI32::new(521), &"i-am-five-hundred-and-twenty-one")?;
///
/// let range = BEI32::new(27)..=BEI32::new(43);
/// let mut iter = db.rev_range(&wtxn, range)?;
/// assert_eq!(iter.next().transpose()?, Some((BEI32::new(42), "i-am-forty-two")));
/// assert_eq!(iter.next().transpose()?, Some((BEI32::new(27), "i-am-twenty-seven")));
/// assert_eq!(iter.next().transpose()?, None);
///
/// drop(iter);
/// wtxn.commit()?;
/// # Ok(()) }
/// ```
pub fn rev_range<'txn, T, R>(
&self,
txn: &'txn RoTxn<T>,
range: R,
) -> Result<RoRevRange<'txn, KC, DC>>
where
KC: BytesEncode,
R: RangeBounds<KC::EItem>,
{
assert_eq!(self.env_ident, txn.env.env_mut_ptr() as usize);
let start_bound = match range.start_bound() {
Bound::Included(bound) => {
let bytes = KC::bytes_encode(bound).map_err(Error::Encoding)?;
Bound::Included(bytes.into_owned())
}
Bound::Excluded(bound) => {
let bytes = KC::bytes_encode(bound).map_err(Error::Encoding)?;
Bound::Excluded(bytes.into_owned())
}
Bound::Unbounded => Bound::Unbounded,
};
let end_bound = match range.end_bound() {
Bound::Included(bound) => {
let bytes = KC::bytes_encode(bound).map_err(Error::Encoding)?;
Bound::Included(bytes.into_owned())
}
Bound::Excluded(bound) => {
let bytes = KC::bytes_encode(bound).map_err(Error::Encoding)?;
Bound::Excluded(bytes.into_owned())
}
Bound::Unbounded => Bound::Unbounded,
};
RoCursor::new(txn, self.dbi).map(|cursor| RoRevRange::new(cursor, start_bound, end_bound))
}
/// Return a mutable reversed lexicographically ordered iterator of a range of
/// key-value pairs in this database.
///
/// Comparisons are made by using the bytes representation of the key.
///
/// ```
/// # use std::fs;
/// # use std::path::Path;
/// # use heed::EnvOpenOptions;
/// use heed::Database;
/// use heed::types::*;
/// use heed::byteorder::BigEndian;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # fs::create_dir_all(Path::new("target").join("database.mdb"))?;
/// # let env = EnvOpenOptions::new()
/// # .map_size(10 * 1024 * 1024) // 10MB
/// # .max_dbs(3000)
/// # .open(Path::new("target").join("database.mdb"))?;
/// type BEI32 = I32<BigEndian>;
///
/// let db: Database<OwnedType<BEI32>, Str> = env.create_database(Some("iter-i32"))?;
///
/// let mut wtxn = env.write_txn()?;
/// # db.clear(&mut wtxn)?;
/// db.put(&mut wtxn, &BEI32::new(42), &"i-am-forty-two")?;
/// db.put(&mut wtxn, &BEI32::new(27), &"i-am-twenty-seven")?;
/// db.put(&mut wtxn, &BEI32::new(13), &"i-am-thirteen")?;
/// db.put(&mut wtxn, &BEI32::new(521), &"i-am-five-hundred-and-twenty-one")?;
///
/// let range = BEI32::new(27)..=BEI32::new(42);
/// let mut range = db.rev_range_mut(&mut wtxn, range)?;
/// assert_eq!(range.next().transpose()?, Some((BEI32::new(42), "i-am-forty-two")));
/// let ret = range.del_current()?;
/// assert!(ret);
/// assert_eq!(range.next().transpose()?, Some((BEI32::new(27), "i-am-twenty-seven")));
/// let ret = range.put_current(&BEI32::new(27), &"i-am-the-new-twenty-seven")?;
/// assert!(ret);
///
/// assert_eq!(range.next().transpose()?, None);
/// drop(range);
///
///
/// let mut iter = db.iter(&wtxn)?;
/// assert_eq!(iter.next().transpose()?, Some((BEI32::new(13), "i-am-thirteen")));
/// assert_eq!(iter.next().transpose()?, Some((BEI32::new(27), "i-am-the-new-twenty-seven")));
/// assert_eq!(iter.next().transpose()?, Some((BEI32::new(521), "i-am-five-hundred-and-twenty-one")));
/// assert_eq!(iter.next().transpose()?, None);
///
/// drop(iter);
/// wtxn.commit()?;
/// # Ok(()) }
/// ```
pub fn rev_range_mut<'txn, T, R>(
&self,
txn: &'txn mut RwTxn<T>,
range: R,
) -> Result<RwRevRange<'txn, KC, DC>>
where
KC: BytesEncode,
R: RangeBounds<KC::EItem>,
{
assert_eq!(self.env_ident, txn.txn.env.env_mut_ptr() as usize);
let start_bound = match range.start_bound() {
Bound::Included(bound) => {
let bytes = KC::bytes_encode(bound).map_err(Error::Encoding)?;
Bound::Included(bytes.into_owned())
}
Bound::Excluded(bound) => {
let bytes = KC::bytes_encode(bound).map_err(Error::Encoding)?;
Bound::Excluded(bytes.into_owned())
}
Bound::Unbounded => Bound::Unbounded,
};
let end_bound = match range.end_bound() {
Bound::Included(bound) => {
let bytes = KC::bytes_encode(bound).map_err(Error::Encoding)?;
Bound::Included(bytes.into_owned())
}
Bound::Excluded(bound) => {
let bytes = KC::bytes_encode(bound).map_err(Error::Encoding)?;
Bound::Excluded(bytes.into_owned())
}
Bound::Unbounded => Bound::Unbounded,
};
RwCursor::new(txn, self.dbi).map(|cursor| RwRevRange::new(cursor, start_bound, end_bound))
}
/// Return a lexicographically ordered iterator of all key-value pairs
/// in this database that starts with the given prefix.
///
/// Comparisons are made by using the bytes representation of the key.
///
/// ```
/// # use std::fs;
/// # use std::path::Path;
/// # use heed::EnvOpenOptions;
/// use heed::Database;
/// use heed::types::*;
/// use heed::byteorder::BigEndian;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # fs::create_dir_all(Path::new("target").join("database.mdb"))?;
/// # let env = EnvOpenOptions::new()
/// # .map_size(10 * 1024 * 1024) // 10MB
/// # .max_dbs(3000)
/// # .open(Path::new("target").join("database.mdb"))?;
/// type BEI32 = I32<BigEndian>;
///
/// let db: Database<Str, OwnedType<BEI32>> = env.create_database(Some("iter-i32"))?;
///
/// let mut wtxn = env.write_txn()?;
/// # db.clear(&mut wtxn)?;
/// db.put(&mut wtxn, &"i-am-twenty-eight", &BEI32::new(28))?;
/// db.put(&mut wtxn, &"i-am-twenty-seven", &BEI32::new(27))?;
/// db.put(&mut wtxn, &"i-am-twenty-nine", &BEI32::new(29))?;
/// db.put(&mut wtxn, &"i-am-forty-one", &BEI32::new(41))?;
/// db.put(&mut wtxn, &"i-am-forty-two", &BEI32::new(42))?;
///
/// let mut iter = db.prefix_iter(&mut wtxn, &"i-am-twenty")?;
/// assert_eq!(iter.next().transpose()?, Some(("i-am-twenty-eight", BEI32::new(28))));
/// assert_eq!(iter.next().transpose()?, Some(("i-am-twenty-nine", BEI32::new(29))));
/// assert_eq!(iter.next().transpose()?, Some(("i-am-twenty-seven", BEI32::new(27))));
/// assert_eq!(iter.next().transpose()?, None);
///
/// drop(iter);
/// wtxn.commit()?;
/// # Ok(()) }
/// ```
pub fn prefix_iter<'txn, T>(
&self,
txn: &'txn RoTxn<T>,
prefix: &KC::EItem,
) -> Result<RoPrefix<'txn, KC, DC>>
where
KC: BytesEncode,
{
assert_eq!(self.env_ident, txn.env.env_mut_ptr() as usize);
let prefix_bytes = KC::bytes_encode(prefix).map_err(Error::Encoding)?;
let prefix_bytes = prefix_bytes.into_owned();
RoCursor::new(txn, self.dbi).map(|cursor| RoPrefix::new(cursor, prefix_bytes))
}
/// Return a mutable lexicographically ordered iterator of all key-value pairs
/// in this database that starts with the given prefix.
///
/// Comparisons are made by using the bytes representation of the key.
///
/// ```
/// # use std::fs;
/// # use std::path::Path;
/// # use heed::EnvOpenOptions;
/// use heed::Database;
/// use heed::types::*;
/// use heed::byteorder::BigEndian;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # fs::create_dir_all(Path::new("target").join("database.mdb"))?;
/// # let env = EnvOpenOptions::new()
/// # .map_size(10 * 1024 * 1024) // 10MB
/// # .max_dbs(3000)
/// # .open(Path::new("target").join("database.mdb"))?;
/// type BEI32 = I32<BigEndian>;
///
/// let db: Database<Str, OwnedType<BEI32>> = env.create_database(Some("iter-i32"))?;
///
/// let mut wtxn = env.write_txn()?;
/// # db.clear(&mut wtxn)?;
/// db.put(&mut wtxn, &"i-am-twenty-eight", &BEI32::new(28))?;
/// db.put(&mut wtxn, &"i-am-twenty-seven", &BEI32::new(27))?;
/// db.put(&mut wtxn, &"i-am-twenty-nine", &BEI32::new(29))?;
/// db.put(&mut wtxn, &"i-am-forty-one", &BEI32::new(41))?;
/// db.put(&mut wtxn, &"i-am-forty-two", &BEI32::new(42))?;
///
/// let mut iter = db.prefix_iter_mut(&mut wtxn, &"i-am-twenty")?;
/// assert_eq!(iter.next().transpose()?, Some(("i-am-twenty-eight", BEI32::new(28))));
/// let ret = iter.del_current()?;
/// assert!(ret);
///
/// assert_eq!(iter.next().transpose()?, Some(("i-am-twenty-nine", BEI32::new(29))));
/// assert_eq!(iter.next().transpose()?, Some(("i-am-twenty-seven", BEI32::new(27))));
/// let ret = iter.put_current(&"i-am-twenty-seven", &BEI32::new(27000))?;
/// assert!(ret);
///
/// assert_eq!(iter.next().transpose()?, None);
///
/// drop(iter);
///
/// let ret = db.get(&wtxn, &"i-am-twenty-eight")?;
/// assert_eq!(ret, None);
///
/// let ret = db.get(&wtxn, &"i-am-twenty-seven")?;
/// assert_eq!(ret, Some(BEI32::new(27000)));
///
/// wtxn.commit()?;
/// # Ok(()) }
/// ```
pub fn prefix_iter_mut<'txn, T>(
&self,
txn: &'txn mut RwTxn<T>,
prefix: &KC::EItem,
) -> Result<RwPrefix<'txn, KC, DC>>
where
KC: BytesEncode,
{
assert_eq!(self.env_ident, txn.env.env_mut_ptr() as usize);
let prefix_bytes = KC::bytes_encode(prefix).map_err(Error::Encoding)?;
let prefix_bytes = prefix_bytes.into_owned();
RwCursor::new(txn, self.dbi).map(|cursor| RwPrefix::new(cursor, prefix_bytes))
}
/// Return a reversed lexicographically ordered iterator of all key-value pairs
/// in this database that starts with the given prefix.
///
/// Comparisons are made by using the bytes representation of the key.
///
/// ```
/// # use std::fs;
/// # use std::path::Path;
/// # use heed::EnvOpenOptions;
/// use heed::Database;
/// use heed::types::*;
/// use heed::byteorder::BigEndian;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # fs::create_dir_all(Path::new("target").join("database.mdb"))?;
/// # let env = EnvOpenOptions::new()
/// # .map_size(10 * 1024 * 1024) // 10MB
/// # .max_dbs(3000)
/// # .open(Path::new("target").join("database.mdb"))?;
/// type BEI32 = I32<BigEndian>;
///
/// let db: Database<Str, OwnedType<BEI32>> = env.create_database(Some("iter-i32"))?;
///
/// let mut wtxn = env.write_txn()?;
/// # db.clear(&mut wtxn)?;
/// db.put(&mut wtxn, &"i-am-twenty-eight", &BEI32::new(28))?;
/// db.put(&mut wtxn, &"i-am-twenty-seven", &BEI32::new(27))?;
/// db.put(&mut wtxn, &"i-am-twenty-nine", &BEI32::new(29))?;
/// db.put(&mut wtxn, &"i-am-forty-one", &BEI32::new(41))?;
/// db.put(&mut wtxn, &"i-am-forty-two", &BEI32::new(42))?;
///
/// let mut iter = db.rev_prefix_iter(&mut wtxn, &"i-am-twenty")?;
/// assert_eq!(iter.next().transpose()?, Some(("i-am-twenty-seven", BEI32::new(27))));
/// assert_eq!(iter.next().transpose()?, Some(("i-am-twenty-nine", BEI32::new(29))));
/// assert_eq!(iter.next().transpose()?, Some(("i-am-twenty-eight", BEI32::new(28))));
/// assert_eq!(iter.next().transpose()?, None);
///
/// drop(iter);
/// wtxn.commit()?;
/// # Ok(()) }
/// ```
pub fn rev_prefix_iter<'txn, T>(
&self,
txn: &'txn RoTxn<T>,
prefix: &KC::EItem,
) -> Result<RoRevPrefix<'txn, KC, DC>>
where
KC: BytesEncode,
{
assert_eq!(self.env_ident, txn.env.env_mut_ptr() as usize);
let prefix_bytes = KC::bytes_encode(prefix).map_err(Error::Encoding)?;
let prefix_bytes = prefix_bytes.into_owned();
RoCursor::new(txn, self.dbi).map(|cursor| RoRevPrefix::new(cursor, prefix_bytes))
}
/// Return a mutable reversed lexicographically ordered iterator of all key-value pairs
/// in this database that starts with the given prefix.
///
/// Comparisons are made by using the bytes representation of the key.
///
/// ```
/// # use std::fs;
/// # use std::path::Path;
/// # use heed::EnvOpenOptions;
/// use heed::Database;
/// use heed::types::*;
/// use heed::byteorder::BigEndian;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # fs::create_dir_all(Path::new("target").join("database.mdb"))?;
/// # let env = EnvOpenOptions::new()
/// # .map_size(10 * 1024 * 1024) // 10MB
/// # .max_dbs(3000)
/// # .open(Path::new("target").join("database.mdb"))?;
/// type BEI32 = I32<BigEndian>;
///
/// let db: Database<Str, OwnedType<BEI32>> = env.create_database(Some("iter-i32"))?;
///
/// let mut wtxn = env.write_txn()?;
/// # db.clear(&mut wtxn)?;
/// db.put(&mut wtxn, &"i-am-twenty-eight", &BEI32::new(28))?;
/// db.put(&mut wtxn, &"i-am-twenty-seven", &BEI32::new(27))?;
/// db.put(&mut wtxn, &"i-am-twenty-nine", &BEI32::new(29))?;
/// db.put(&mut wtxn, &"i-am-forty-one", &BEI32::new(41))?;
/// db.put(&mut wtxn, &"i-am-forty-two", &BEI32::new(42))?;
///
/// let mut iter = db.rev_prefix_iter_mut(&mut wtxn, &"i-am-twenty")?;
/// assert_eq!(iter.next().transpose()?, Some(("i-am-twenty-seven", BEI32::new(27))));
/// let ret = iter.del_current()?;
/// assert!(ret);
///
/// assert_eq!(iter.next().transpose()?, Some(("i-am-twenty-nine", BEI32::new(29))));
/// assert_eq!(iter.next().transpose()?, Some(("i-am-twenty-eight", BEI32::new(28))));
/// let ret = iter.put_current(&"i-am-twenty-eight", &BEI32::new(28000))?;
/// assert!(ret);
///
/// assert_eq!(iter.next().transpose()?, None);
///
/// drop(iter);
///
/// let ret = db.get(&wtxn, &"i-am-twenty-seven")?;
/// assert_eq!(ret, None);
///
/// let ret = db.get(&wtxn, &"i-am-twenty-eight")?;
/// assert_eq!(ret, Some(BEI32::new(28000)));
///
/// wtxn.commit()?;
/// # Ok(()) }
/// ```
pub fn rev_prefix_iter_mut<'txn, T>(
&self,
txn: &'txn mut RwTxn<T>,
prefix: &KC::EItem,
) -> Result<RwRevPrefix<'txn, KC, DC>>
where
KC: BytesEncode,
{
assert_eq!(self.env_ident, txn.txn.env.env_mut_ptr() as usize);
let prefix_bytes = KC::bytes_encode(prefix).map_err(Error::Encoding)?;
let prefix_bytes = prefix_bytes.into_owned();
RwCursor::new(txn, self.dbi).map(|cursor| RwRevPrefix::new(cursor, prefix_bytes))
}
/// Insert a key-value pairs in this database.
///
/// ```
/// # use std::fs;
/// # use std::path::Path;
/// # use heed::EnvOpenOptions;
/// use heed::Database;
/// use heed::types::*;
/// use heed::byteorder::BigEndian;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # fs::create_dir_all(Path::new("target").join("database.mdb"))?;
/// # let env = EnvOpenOptions::new()
/// # .map_size(10 * 1024 * 1024) // 10MB
/// # .max_dbs(3000)
/// # .open(Path::new("target").join("database.mdb"))?;
/// type BEI32 = I32<BigEndian>;
///
/// let db: Database<OwnedType<BEI32>, Str> = env.create_database(Some("iter-i32"))?;
///
/// let mut wtxn = env.write_txn()?;
/// # db.clear(&mut wtxn)?;
/// db.put(&mut wtxn, &BEI32::new(42), &"i-am-forty-two")?;
/// db.put(&mut wtxn, &BEI32::new(27), &"i-am-twenty-seven")?;
/// db.put(&mut wtxn, &BEI32::new(13), &"i-am-thirteen")?;
/// db.put(&mut wtxn, &BEI32::new(521), &"i-am-five-hundred-and-twenty-one")?;
///
/// let ret = db.get(&mut wtxn, &BEI32::new(27))?;
/// assert_eq!(ret, Some("i-am-twenty-seven"));
///
/// wtxn.commit()?;
/// # Ok(()) }
/// ```
pub fn put<T>(&self, txn: &mut RwTxn<T>, key: &KC::EItem, data: &DC::EItem) -> Result<()>
where
KC: BytesEncode,
DC: BytesEncode,
{
assert_eq!(self.env_ident, txn.txn.env.env_mut_ptr() as usize);
let key_bytes: Cow<[u8]> = KC::bytes_encode(&key).map_err(Error::Encoding)?;
let data_bytes: Cow<[u8]> = DC::bytes_encode(&data).map_err(Error::Encoding)?;
let mut key_val = unsafe { crate::into_val(&key_bytes) };
let mut data_val = unsafe { crate::into_val(&data_bytes) };
let flags = 0;
unsafe {
mdb_result(ffi::mdb_put(
txn.txn.txn,
self.dbi,
&mut key_val,
&mut data_val,
flags,
))?
}
Ok(())
}
/// Append the given key/data pair to the end of the database.
///
/// This option allows fast bulk loading when keys are already known to be in the correct order.
/// Loading unsorted keys will cause a MDB_KEYEXIST error.
///
/// ```
/// # use std::fs;
/// # use std::path::Path;
/// # use heed::EnvOpenOptions;
/// use heed::Database;
/// use heed::types::*;
/// use heed::byteorder::BigEndian;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # fs::create_dir_all(Path::new("target").join("database.mdb"))?;
/// # let env = EnvOpenOptions::new()
/// # .map_size(10 * 1024 * 1024) // 10MB
/// # .max_dbs(3000)
/// # .open(Path::new("target").join("database.mdb"))?;
/// type BEI32 = I32<BigEndian>;
///
/// let db: Database<OwnedType<BEI32>, Str> = env.create_database(Some("iter-i32"))?;
///
/// let mut wtxn = env.write_txn()?;
/// # db.clear(&mut wtxn)?;
/// db.put(&mut wtxn, &BEI32::new(13), &"i-am-thirteen")?;
/// db.put(&mut wtxn, &BEI32::new(27), &"i-am-twenty-seven")?;
/// db.put(&mut wtxn, &BEI32::new(42), &"i-am-forty-two")?;
/// db.put(&mut wtxn, &BEI32::new(521), &"i-am-five-hundred-and-twenty-one")?;
///
/// let ret = db.get(&mut wtxn, &BEI32::new(27))?;
/// assert_eq!(ret, Some("i-am-twenty-seven"));
///
/// wtxn.commit()?;
/// # Ok(()) }
/// ```
pub fn append<T>(&self, txn: &mut RwTxn<T>, key: &KC::EItem, data: &DC::EItem) -> Result<()>
where
KC: BytesEncode,
DC: BytesEncode,
{
assert_eq!(self.env_ident, txn.txn.env.env_mut_ptr() as usize);
let key_bytes: Cow<[u8]> = KC::bytes_encode(&key).map_err(Error::Encoding)?;
let data_bytes: Cow<[u8]> = DC::bytes_encode(&data).map_err(Error::Encoding)?;
let mut key_val = unsafe { crate::into_val(&key_bytes) };
let mut data_val = unsafe { crate::into_val(&data_bytes) };
let flags = ffi::MDB_APPEND;
unsafe {
mdb_result(ffi::mdb_put(
txn.txn.txn,
self.dbi,
&mut key_val,
&mut data_val,
flags,
))?
}
Ok(())
}
/// Deletes a key-value pairs in this database.
///
/// If the key does not exist, then `false` is returned.
///
/// ```
/// # use std::fs;
/// # use std::path::Path;
/// # use heed::EnvOpenOptions;
/// use heed::Database;
/// use heed::types::*;
/// use heed::byteorder::BigEndian;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # fs::create_dir_all(Path::new("target").join("database.mdb"))?;
/// # let env = EnvOpenOptions::new()
/// # .map_size(10 * 1024 * 1024) // 10MB
/// # .max_dbs(3000)
/// # .open(Path::new("target").join("database.mdb"))?;
/// type BEI32 = I32<BigEndian>;
///
/// let db: Database<OwnedType<BEI32>, Str> = env.create_database(Some("iter-i32"))?;
///
/// let mut wtxn = env.write_txn()?;
/// # db.clear(&mut wtxn)?;
/// db.put(&mut wtxn, &BEI32::new(42), &"i-am-forty-two")?;
/// db.put(&mut wtxn, &BEI32::new(27), &"i-am-twenty-seven")?;
/// db.put(&mut wtxn, &BEI32::new(13), &"i-am-thirteen")?;
/// db.put(&mut wtxn, &BEI32::new(521), &"i-am-five-hundred-and-twenty-one")?;
///
/// let ret = db.delete(&mut wtxn, &BEI32::new(27))?;
/// assert_eq!(ret, true);
///
/// let ret = db.get(&mut wtxn, &BEI32::new(27))?;
/// assert_eq!(ret, None);
///
/// let ret = db.delete(&mut wtxn, &BEI32::new(467))?;
/// assert_eq!(ret, false);
///
/// wtxn.commit()?;
/// # Ok(()) }
/// ```
pub fn delete<T>(&self, txn: &mut RwTxn<T>, key: &KC::EItem) -> Result<bool>
where
KC: BytesEncode,
{
assert_eq!(self.env_ident, txn.txn.env.env_mut_ptr() as usize);
let key_bytes: Cow<[u8]> = KC::bytes_encode(&key).map_err(Error::Encoding)?;
let mut key_val = unsafe { crate::into_val(&key_bytes) };
let result = unsafe {
mdb_result(ffi::mdb_del(
txn.txn.txn,
self.dbi,
&mut key_val,
ptr::null_mut(),
))
};
match result {
Ok(()) => Ok(true),
Err(e) if e.not_found() => Ok(false),
Err(e) => Err(e.into()),
}
}
/// Deletes a range of key-value pairs in this database.
///
/// Perfer using [`clear`] instead of a call to this method with a full range ([`..`]).
///
/// Comparisons are made by using the bytes representation of the key.
///
/// [`clear`]: crate::Database::clear
/// [`..`]: std::ops::RangeFull
///
/// ```
/// # use std::fs;
/// # use std::path::Path;
/// # use heed::EnvOpenOptions;
/// use heed::Database;
/// use heed::types::*;
/// use heed::byteorder::BigEndian;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # fs::create_dir_all(Path::new("target").join("database.mdb"))?;
/// # let env = EnvOpenOptions::new()
/// # .map_size(10 * 1024 * 1024) // 10MB
/// # .max_dbs(3000)
/// # .open(Path::new("target").join("database.mdb"))?;
/// type BEI32 = I32<BigEndian>;
///
/// let db: Database<OwnedType<BEI32>, Str> = env.create_database(Some("iter-i32"))?;
///
/// let mut wtxn = env.write_txn()?;
/// # db.clear(&mut wtxn)?;
/// db.put(&mut wtxn, &BEI32::new(42), &"i-am-forty-two")?;
/// db.put(&mut wtxn, &BEI32::new(27), &"i-am-twenty-seven")?;
/// db.put(&mut wtxn, &BEI32::new(13), &"i-am-thirteen")?;
/// db.put(&mut wtxn, &BEI32::new(521), &"i-am-five-hundred-and-twenty-one")?;
///
/// let range = BEI32::new(27)..=BEI32::new(42);
/// let ret = db.delete_range(&mut wtxn, range)?;
/// assert_eq!(ret, 2);
///
///
/// let mut iter = db.iter(&wtxn)?;
/// assert_eq!(iter.next().transpose()?, Some((BEI32::new(13), "i-am-thirteen")));
/// assert_eq!(iter.next().transpose()?, Some((BEI32::new(521), "i-am-five-hundred-and-twenty-one")));
/// assert_eq!(iter.next().transpose()?, None);
///
/// drop(iter);
/// wtxn.commit()?;
/// # Ok(()) }
/// ```
pub fn delete_range<'txn, T, R>(&self, txn: &'txn mut RwTxn<T>, range: R) -> Result<usize>
where
KC: BytesEncode + BytesDecode<'txn>,
R: RangeBounds<KC::EItem>,
{
assert_eq!(self.env_ident, txn.txn.env.env_mut_ptr() as usize);
let mut count = 0;
let mut iter = self.remap_data_type::<DecodeIgnore>().range_mut(txn, range)?;
while let Some(_) = iter.next() {
iter.del_current()?;
count += 1;
}
Ok(count)
}
/// Deletes all key/value pairs in this database.
///
/// Perfer using this method instead of a call to [`delete_range`] with a full range ([`..`]).
///
/// [`delete_range`]: crate::Database::delete_range
/// [`..`]: std::ops::RangeFull
///
/// ```
/// # use std::fs;
/// # use std::path::Path;
/// # use heed::EnvOpenOptions;
/// use heed::Database;
/// use heed::types::*;
/// use heed::byteorder::BigEndian;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # fs::create_dir_all(Path::new("target").join("database.mdb"))?;
/// # let env = EnvOpenOptions::new()
/// # .map_size(10 * 1024 * 1024) // 10MB
/// # .max_dbs(3000)
/// # .open(Path::new("target").join("database.mdb"))?;
/// type BEI32 = I32<BigEndian>;
///
/// let db: Database<OwnedType<BEI32>, Str> = env.create_database(Some("iter-i32"))?;
///
/// let mut wtxn = env.write_txn()?;
/// # db.clear(&mut wtxn)?;
/// db.put(&mut wtxn, &BEI32::new(42), &"i-am-forty-two")?;
/// db.put(&mut wtxn, &BEI32::new(27), &"i-am-twenty-seven")?;
/// db.put(&mut wtxn, &BEI32::new(13), &"i-am-thirteen")?;
/// db.put(&mut wtxn, &BEI32::new(521), &"i-am-five-hundred-and-twenty-one")?;
///
/// db.clear(&mut wtxn)?;
///
/// let ret = db.is_empty(&wtxn)?;
/// assert!(ret);
///
/// wtxn.commit()?;
/// # Ok(()) }
/// ```
pub fn clear<T>(&self, txn: &mut RwTxn<T>) -> Result<()> {
assert_eq!(self.env_ident, txn.txn.env.env_mut_ptr() as usize);
unsafe { mdb_result(ffi::mdb_drop(txn.txn.txn, self.dbi, 0)).map_err(Into::into) }
}
/// Change the codec types of this uniform database, specifying the codecs.
///
/// # Safety
///
/// It is up to you to ensure that the data read and written using the polymorphic
/// handle correspond to the the typed, uniform one. If an invalid write is made,
/// it can corrupt the database from the eyes of heed.
///
/// # Example
///
/// ```
/// # use std::fs;
/// # use std::path::Path;
/// # use heed::EnvOpenOptions;
/// use heed::Database;
/// use heed::types::*;
/// use heed::byteorder::BigEndian;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # fs::create_dir_all(Path::new("target").join("database.mdb"))?;
/// # let env = EnvOpenOptions::new()
/// # .map_size(10 * 1024 * 1024) // 10MB
/// # .max_dbs(3000)
/// # .open(Path::new("target").join("database.mdb"))?;
/// type BEI32 = I32<BigEndian>;
///
/// let db: Database<Unit, Unit> = env.create_database(Some("iter-i32"))?;
///
/// let mut wtxn = env.write_txn()?;
/// # db.clear(&mut wtxn)?;
/// // We remap the types for ease of use.
/// let db = db.remap_types::<OwnedType<BEI32>, Str>();
/// db.put(&mut wtxn, &BEI32::new(42), &"i-am-forty-two")?;
/// db.put(&mut wtxn, &BEI32::new(27), &"i-am-twenty-seven")?;
/// db.put(&mut wtxn, &BEI32::new(13), &"i-am-thirteen")?;
/// db.put(&mut wtxn, &BEI32::new(521), &"i-am-five-hundred-and-twenty-one")?;
///
/// wtxn.commit()?;
/// # Ok(()) }
/// ```
pub fn remap_types<KC2, DC2>(&self) -> Database<KC2, DC2> {
Database::new(self.env_ident, self.dbi)
}
/// Change the key codec type of this uniform database, specifying the new codec.
pub fn remap_key_type<KC2>(&self) -> Database<KC2, DC> {
self.remap_types::<KC2, DC>()
}
/// Change the data codec type of this uniform database, specifying the new codec.
pub fn remap_data_type<DC2>(&self) -> Database<KC, DC2> {
self.remap_types::<KC, DC2>()
}
/// Wrap the data bytes into a lazy decoder.
pub fn lazily_decode_data(&self) -> Database<KC, LazyDecode<DC>> {
self.remap_types::<KC, LazyDecode<DC>>()
}
}
impl<KC, DC> Clone for Database<KC, DC> {
fn clone(&self) -> Database<KC, DC> {
Database {
env_ident: self.env_ident,
dbi: self.dbi,
marker: marker::PhantomData,
}
}
}
impl<KC, DC> Copy for Database<KC, DC> {}
|
use fltk::{enums::*, prelude::*, *};
use std::cell::RefCell;
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
#[derive(Debug, Clone)]
pub struct MyDial {
main_wid: group::Group,
value: Rc<RefCell<i32>>,
value_frame: frame::Frame,
}
impl MyDial {
pub fn new(x: i32, y: i32, w: i32, h: i32, label: &'static str) -> Self {
let value = Rc::from(RefCell::from(0));
let mut main_wid = group::Group::new(x, y, w, h, label).with_align(Align::Top);
let mut value_frame =
frame::Frame::new(main_wid.x(), main_wid.y() + 80, main_wid.w(), 40, "0");
value_frame.set_label_size(26);
main_wid.end();
let value_c = value.clone();
main_wid.draw(move |w| {
draw::set_draw_rgb_color(230, 230, 230);
draw::draw_pie(w.x(), w.y(), w.w(), w.h(), 0., 180.);
draw::set_draw_hex_color(0xb0bf1a);
draw::draw_pie(
w.x(),
w.y(),
w.w(),
w.h(),
(100 - *value_c.borrow()) as f64 * 1.8,
180.,
);
draw::set_draw_color(Color::White);
draw::draw_pie(
w.x() - 50 + w.w() / 2,
w.y() - 50 + w.h() / 2,
100,
100,
0.,
360.,
);
});
Self {
main_wid,
value,
value_frame,
}
}
pub fn value(&self) -> i32 {
*self.value.borrow()
}
pub fn set_value(&mut self, val: i32) {
*self.value.borrow_mut() = val;
self.value_frame.set_label(&val.to_string());
self.main_wid.redraw();
}
}
impl Deref for MyDial {
type Target = group::Group;
fn deref(&self) -> &Self::Target {
&self.main_wid
}
}
impl DerefMut for MyDial {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.main_wid
}
}
fn main() {
let app = app::App::default();
app::background(255, 255, 255);
let mut win = window::Window::default().with_size(400, 300);
let mut dial = MyDial::new(100, 100, 200, 200, "CPU Load %");
dial.set_label_size(22);
dial.set_label_color(Color::from_u32(0x797979));
win.end();
win.show();
// get the cpu load value from somewhere, then call dial.set_value() in a callback or event loop
dial.set_value(10);
app.run().unwrap();
}
|
mod camera;
mod hitable;
mod hitable_list;
mod material;
mod ray;
mod sphere;
mod vec3;
use camera::Camera;
use hitable::Hitable;
use material::{Dielectric, Lambertian, Metal};
use rand;
use ray::Ray;
use sphere::Sphere;
use std::io::{self, Write};
use vec3::Vec3;
fn color(ray: Ray, world: &dyn Hitable, depth: i32) -> Vec3 {
if let Some(hit) = world.hit(&ray, 0.001, std::f32::MAX) {
if depth < 50 {
if let Some((attenuation, scattered)) = hit.material.scatter(&ray, &hit) {
return attenuation * color(scattered, world, depth + 1);
}
}
return Vec3::zeros();
} else {
let unit_direction = ray.direction().unit_vector();
let t: f32 = 0.5 * (unit_direction.y() + 1.0);
return (1.0 - t) * Vec3::ones() + t * Vec3::new(0.5, 0.7, 1.0);
}
}
fn random_scene() -> Vec<Box<dyn Hitable>> {
let mut list: Vec<Box<dyn Hitable>> = Vec::new();
for a in -11..11 {
for b in -11..11 {
let choose_mat = rand::random::<f32>();
let center = Vec3::new(
a as f32 + 0.9 * rand::random::<f32>(),
0.2,
b as f32 + 0.9 * rand::random::<f32>(),
);
if choose_mat < 0.8 {
list.push(Box::new(Sphere::new(
center,
0.2,
Box::new(Lambertian::new(Vec3::new(
rand::random::<f32>() * rand::random::<f32>(),
rand::random::<f32>() * rand::random::<f32>(),
rand::random::<f32>() * rand::random::<f32>(),
))),
)));
} else if choose_mat < 0.95 {
list.push(Box::new(Sphere::new(
center,
0.2,
Box::new(Metal::new(
Vec3::new(
0.5 * (1.0 + rand::random::<f32>()),
0.5 * (1.0 + rand::random::<f32>()),
0.5 * (1.0 + rand::random::<f32>()),
),
0.5 * rand::random::<f32>(),
)),
)));
} else {
list.push(Box::new(Sphere::new(
center,
0.2,
Box::new(Dielectric::new(1.5)),
)));
}
}
}
return list;
}
fn main() -> io::Result<()> {
let nx = 400;
let ny = 200;
let ns = 100;
io::stdout().write_all(format!("P3\n{} {}\n255\n", nx, ny).as_bytes())?;
let look_from = Vec3::new(3.0, 3.0, 3.0);
let look_at = Vec3::new(0.0, 0.0, -1.0);
let cam: Camera = Camera::new(
look_from,
look_at,
Vec3::new(0.0, 1.0, 0.0),
20.0,
nx as f32 / ny as f32,
2.0,
(look_from - look_at).length(),
);
let mut world: Vec<Box<dyn Hitable>> = Vec::new();
world.push(Box::new(Sphere::new(
Vec3::new(0.0, 0.0, -1.0),
0.5,
Box::new(Lambertian::new(Vec3::new(0.1, 0.2, 0.5))),
)));
world.push(Box::new(Sphere::new(
Vec3::new(0.0, -100.5, -1.0),
100.0,
Box::new(Lambertian::new(Vec3::new(0.8, 0.8, 0.0))),
)));
world.push(Box::new(Sphere::new(
Vec3::new(1.0, 0.0, -1.0),
0.5,
Box::new(Metal::new(Vec3::new(0.8, 0.6, 0.2), 0.1)),
)));
world.push(Box::new(Sphere::new(
Vec3::new(-1.0, 0.0, -1.0),
0.5,
Box::new(Dielectric::new(1.5)),
)));
world.push(Box::new(Sphere::new(
Vec3::new(-1.0, 0.0, -1.0),
-0.45,
Box::new(Dielectric::new(1.5)),
)));
let world2 = random_scene();
for j in (0..ny).rev() {
for i in 0..nx {
let mut col = Vec3::zeros();
for _ in 0..ns {
let u = (i as f32 + rand::random::<f32>()) / nx as f32;
let v = (j as f32 + rand::random::<f32>()) / ny as f32;
let r = cam.get_ray(u, v);
col = col + color(r, &world2, 0);
}
col = col / ns as f32;
io::stdout().write_all(
format!("{} {} {}\n", col.r() as i32, col.g() as i32, col.b() as i32).as_bytes(),
)?;
}
}
Ok(())
}
|
use testutil::*;
use seven_client::sms::{Sms, SmsTextParams, SmsJsonParams};
use seven_client::status::{Status, StatusParams};
mod testutil;
fn init_client() -> Status {
Status::new(get_client())
}
#[test]
fn text() {
assert!(init_client().text(StatusParams {
msg_id: 77136739797,
}).is_ok());
}
|
use std::{slice, iter, cmp, ops, fmt, collections::BTreeSet};
use bit_vec::BitVec;
use crate::{
Polarity, DotId, Port, Link, LinkId, ContextHandle, Contextual, ExclusivelyContextual,
InContextMut, Atomic, AcesError, AcesErrorKind, sat,
};
// FIXME sort rows as a way to fix Eq and, perhaps, to open some
// optimization opportunities.
/// Fuset's frame: a family of dotsets. This also represents a single
/// equivalence class of formal polynomials.
///
/// Internally a `Frame` is represented as a `span` vector of _N_
/// [`Atomic`] identifiers (dots, links, etc.) and a boolean matrix
/// with _N_ columns and _M_ rows. The `span` vector, sorted in
/// strictly increasing order, represents the fuset's span (or the set
/// of dots occuring in the polynomial) and _N_ is the number of dots:
/// the frame's width.
///
/// _M_ is the frame size (number of pits or number of monomials in
/// the canonical representation of a polynomial). The order in which
/// pits (monomial terms) are listed is arbitrary. An element in row
/// _i_ and column _j_ of the matrix determines if a dot in _j_-th
/// position in the `span` vector of identifiers occurs in _i_-th pit
/// (monomial).
///
/// `Frame`s may be compared and added using traits from [`std::cmp`]
/// and [`std::ops`] standard modules, with the obvious exception of
/// [`std::cmp::Ord`]. Note however that, in general, preventing
/// [`Context`] or [`Port`] mismatch between frames is the
/// responsibility of the caller of an operation. Implementation
/// detects some, but not all, cases of mismatch and panics if it does
/// so.
///
/// [`Context`]: crate::Context
#[derive(Clone, Debug)]
pub struct Frame<T: Atomic + fmt::Debug> {
span: Vec<T>,
// FIXME choose a better representation of a boolean matrix.
pits: Vec<BitVec>,
polarity: Option<Polarity>,
}
impl Frame<LinkId> {
/// Creates a frame from a sequence of sequences of [`DotId`]s and
/// in a [`Context`] given by a [`ContextHandle`].
///
/// [`Context`]: crate::Context
pub fn from_dots_in_context<'a, I>(
ctx: &ContextHandle,
polarity: Polarity,
dot_id: DotId,
pit_ids: I,
) -> Self
where
I: IntoIterator + 'a,
I::Item: IntoIterator<Item = &'a DotId>,
{
let mut result = Self::new_oriented(polarity);
let mut port = Port::new(polarity, dot_id);
let pid = ctx.lock().unwrap().share_port(&mut port);
let tip = port.get_dot_id();
let polarity = port.get_polarity();
let mut ctx = ctx.lock().unwrap();
for dot_ids in pit_ids.into_iter() {
let mut out_ids = BTreeSet::new();
for cotip in dot_ids.into_iter().copied() {
let mut coport = Port::new(!polarity, cotip);
let copid = ctx.share_port(&mut coport);
let mut link = match polarity {
Polarity::Tx => Link::new(pid, tip, copid, cotip),
Polarity::Rx => Link::new(copid, cotip, pid, tip),
};
let id = ctx.share_link(&mut link);
out_ids.insert(id);
}
result.add_pit_sorted(out_ids.into_iter()).unwrap();
}
result
}
}
impl<T: Atomic + fmt::Debug> Frame<T> {
/// Creates an empty frame, _θ_.
#[allow(clippy::new_without_default)]
pub fn new() -> Self {
Self { span: Default::default(), pits: Default::default(), polarity: None }
}
/// Creates an empty frame, _θ_, oriented according to a
/// given [`Polarity`].
#[allow(clippy::new_without_default)]
pub fn new_oriented(polarity: Polarity) -> Self {
Self {
span: Default::default(),
pits: Default::default(),
polarity: Some(polarity),
}
}
/// Resets this frame into _θ_, preserving polarity, if any.
pub fn clear(&mut self) {
self.span.clear();
self.pits.clear();
}
/// Multiplies this frame (all its pits) by a singleton pit.
pub fn atomic_multiply(&mut self, atomic: T) {
if self.is_empty() {
self.span.push(atomic);
let mut row = BitVec::new();
row.push(true);
self.pits.push(row);
} else if atomic > *self.span.last().unwrap() {
self.span.push(atomic);
for row in self.pits.iter_mut() {
row.push(true);
}
} else {
match self.span.binary_search(&atomic) {
Ok(ndx) => {
if !self.is_singular() {
for row in self.pits.iter_mut() {
row.set(ndx, true);
}
}
}
Err(ndx) => {
let old_len = self.span.len();
self.span.insert(ndx, atomic);
for row in self.pits.iter_mut() {
row.push(false);
for i in ndx..old_len {
let bit = row.get(i).unwrap();
row.set(i + 1, bit);
}
row.set(ndx, true);
}
}
}
}
}
/// Adds a sequence of [`Atomic`] identifiers to this frame as
/// another pit (monomial).
///
/// On success, returns `true` if this frame changed or `false` if
/// it didn't, due to idempotency of addition.
///
/// Returns error if `span` isn't given in strictly increasing
/// order, or in case of port mismatch, or if context mismatch was
/// detected.
pub fn add_pit_sorted<I>(&mut self, span: I) -> Result<bool, AcesError>
where
I: IntoIterator<Item = T>,
{
if self.is_empty() {
let mut prev_thing = None;
for thing in span.into_iter() {
trace!("Start {:?} with {:?}", self, thing);
if let Some(prev) = prev_thing {
if thing <= prev {
self.span.clear();
return Err(AcesErrorKind::ArmsNotOrdered.into())
}
}
prev_thing = Some(thing);
self.span.push(thing);
}
if self.span.is_empty() {
return Ok(false)
} else {
let row = BitVec::from_elem(self.span.len(), true);
self.pits.push(row);
return Ok(true)
}
}
let mut new_row = BitVec::with_capacity(2 * self.span.len());
let mut prev_thing = None;
let mut no_new_things = true;
// These are used for error recovery.
let mut old_span = None;
let mut old_pits = None;
let mut ndx = 0;
for thing in span.into_iter() {
trace!("Grow {:?} with {:?}", self, thing);
if let Some(prev) = prev_thing {
if thing <= prev {
// Error recovery.
if let Some(old_span) = old_span {
self.span = old_span;
}
if let Some(old_pits) = old_pits {
self.pits = old_pits;
}
return Err(AcesErrorKind::ArmsNotOrdered.into())
}
}
prev_thing = Some(thing);
match self.span[ndx..].binary_search(&thing) {
Ok(i) => {
if i > 0 {
new_row.grow(i, false);
}
new_row.push(true);
ndx += i + 1;
}
Err(i) => {
ndx += i;
no_new_things = false;
if i > 0 {
new_row.grow(i, false);
}
new_row.push(true);
if old_span.is_none() {
old_span = Some(self.span.clone());
}
self.span.insert(ndx, thing);
let old_rows = self.pits.clone();
for (new_row, old_row) in self.pits.iter_mut().zip(old_rows.iter()) {
new_row.truncate(ndx);
new_row.push(false);
new_row.extend(old_row.iter().skip(ndx));
}
if old_pits.is_none() {
old_pits = Some(old_rows);
}
ndx += 1;
}
}
}
if no_new_things {
for row in self.pits.iter() {
if *row == new_row {
return Ok(false)
}
}
}
self.pits.push(new_row);
Ok(true)
}
/// Adds another `Frame` to this frame.
///
/// On success, returns `true` if this frame changed or `false` if
/// it didn't, due to idempotency of addition.
///
/// Returns error in case of port mismatch, or if context mismatch
/// was detected.
pub(crate) fn add_frame(&mut self, other: &Self) -> Result<bool, AcesError> {
if self.polarity == other.polarity {
// FIXME optimize. There are two special cases: when
// `self` is a superframe, and when it is a subframe of
// `other`. First case is a nop; the second: clear
// followed by clone.
let mut changed = false;
for pit in other.iter() {
if self.add_pit_sorted(pit)? {
changed = true;
}
}
Ok(changed)
} else {
Err(AcesErrorKind::FramePolarityMismatch.into())
}
}
pub fn is_empty(&self) -> bool {
self.pits.is_empty()
}
pub fn is_atomic(&self) -> bool {
self.span.len() == 1
}
// FIXME is_primitive(): test for injection
pub fn is_singular(&self) -> bool {
self.pits.len() == 1
}
pub fn width(&self) -> usize {
self.span.len()
}
pub fn size(&self) -> usize {
self.pits.len()
}
/// Creates a [`FrameIter`] iterator.
pub fn iter(&self) -> FrameIter<T> {
FrameIter { frame: self, ndx: 0 }
}
pub fn get_span(&self) -> slice::Iter<T> {
self.span.iter()
}
/// Constructs the firing rule of this frame, the logical
/// constraint imposed on firing components, if the frame is
/// attached to the oriented (with polarity) dot represented by
/// `port_lit`. The rule is transformed into a CNF formula, a
/// conjunction of disjunctions of [`sat::Literal`]s (a sequence
/// of clauses).
///
/// Returns a sequence of clauses in the form of vector of vectors
/// of [`sat::Literal`]s.
pub fn as_sat_clauses(&self, port_lit: sat::Literal) -> Vec<sat::Clause> {
if self.is_atomic() {
// Consequence is a single positive link literal. The
// rule is a single two-literal port-link clause.
vec![sat::Clause::from_pair(self.span[0].into_sat_literal(false), port_lit, "atomic")]
} else if self.is_singular() {
// Consequence is a conjunction of _N_ >= 2 positive link
// literals. The rule is a sequence of _N_ two-literal
// port-link clauses.
self.span
.iter()
.map(|id| sat::Clause::from_pair(id.into_sat_literal(false), port_lit, "singular"))
.collect()
} else {
// Consequence is a disjunction of _M_ >= 2 statements,
// each being a conjunction of _N_ >= 2 positive and
// negative (at least one of each) link literals. The
// rule (after being expanded to CNF by distribution) is a
// sequence of _N_^_M_ port-link clauses, each consisting
// of the `port_lit` and _M_ link literals.
let mut clauses = Vec::new();
let num_pits = self.pits.len();
let num_dots = self.span.len();
let clause_table_row = self.span.iter().map(|id| id.into_sat_literal(false));
let mut clause_table: Vec<_> = self
.pits
.iter()
.map(|pit| {
pit.iter()
.zip(clause_table_row.clone())
.map(|(bit, lit)| if bit { lit } else { !lit })
.collect()
})
.collect();
clause_table.push(vec![port_lit]);
let mut cursors = vec![0; num_pits + 1];
let mut pit_ndx = 0;
let mut num_tautologies = 0;
let mut num_repeated_literals = 0;
'outer: loop {
let lits = cursors.iter().enumerate().map(|(row, &col)| clause_table[row][col]);
if let Some(clause) = sat::Clause::from_literals_checked(lits, "frame pit") {
num_repeated_literals += num_pits + 1 - clause.len();
clauses.push(clause);
} else {
num_tautologies += 1;
}
'inner: loop {
if cursors[pit_ndx] < num_dots - 1 {
cursors[pit_ndx] += 1;
for cursor in cursors.iter_mut().take(pit_ndx) {
*cursor = 0;
}
pit_ndx = 0;
break 'inner
} else if pit_ndx < num_pits - 1 {
cursors[pit_ndx] = 0;
pit_ndx += 1;
} else {
break 'outer
}
}
}
info!(
"Pushing {} frame subterm clauses (removed {} tautologies and {} repeated \
literals)",
clauses.len(),
num_tautologies,
num_repeated_literals,
);
clauses
}
}
}
impl<T: Atomic + fmt::Debug> PartialEq for Frame<T> {
fn eq(&self, other: &Self) -> bool {
self.span == other.span && self.pits == other.pits
}
}
impl<T: Atomic + fmt::Debug> Eq for Frame<T> {}
impl<T: Atomic + fmt::Debug> PartialOrd for Frame<T> {
#[allow(clippy::collapsible_if)]
fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
// FIXME optimize, handle errors
if self.clone().add_frame(other).unwrap() {
if other.clone().add_frame(self).unwrap() {
None
} else {
Some(cmp::Ordering::Less)
}
} else {
if other.clone().add_frame(self).unwrap() {
Some(cmp::Ordering::Less)
} else {
Some(cmp::Ordering::Equal)
}
}
}
}
impl Contextual for Frame<LinkId> {
fn format(&self, ctx: &ContextHandle) -> Result<String, AcesError> {
let mut result = String::new();
let mut first_pit = true;
for pit in self.iter() {
if first_pit {
first_pit = false;
} else {
result.push_str(" + ");
}
let mut first_id = true;
for id in pit {
if first_id {
first_id = false;
} else {
result.push('·');
}
let s = if let Some(polarity) = self.polarity {
let ctx = ctx.lock().unwrap();
let link = ctx
.get_link(id)
.ok_or_else(|| AcesError::from(AcesErrorKind::LinkMissingForId(id)))?;
match polarity {
Polarity::Tx => link.get_rx_dot_id().format_locked(&ctx),
Polarity::Rx => link.get_tx_dot_id().format_locked(&ctx),
}
} else {
id.format(ctx)
}?;
result.push_str(&s);
}
}
Ok(result)
}
}
impl<'a> InContextMut<'a, Frame<LinkId>> {
pub(crate) fn add_frame(&mut self, other: &Self) -> Result<bool, AcesError> {
if self.same_context(other) {
self.get_thing_mut().add_frame(other.get_thing())
} else {
Err(AcesErrorKind::ContextMismatch.with_context(self.get_context()))
}
}
}
impl<'a> ops::AddAssign<&Self> for InContextMut<'a, Frame<LinkId>> {
fn add_assign(&mut self, other: &Self) {
self.add_frame(other).unwrap();
}
}
/// An iterator yielding pits (monomials) of a [`Frame`] as ordered
/// sequences of [`Atomic`] identifiers.
///
/// This is a two-level iterator: the yielded items are themselves
/// iterators. It borrows the [`Frame`] being iterated over and
/// traverses its data in place, without allocating extra space for
/// inner iteration.
pub struct FrameIter<'a, T: Atomic + fmt::Debug> {
frame: &'a Frame<T>,
ndx: usize,
}
impl<'a, T: Atomic + fmt::Debug> Iterator for FrameIter<'a, T> {
#[allow(clippy::type_complexity)]
type Item = iter::FilterMap<
iter::Zip<slice::Iter<'a, T>, bit_vec::Iter<'a>>,
fn((&T, bool)) -> Option<T>,
>;
fn next(&mut self) -> Option<Self::Item> {
if let Some(row) = self.frame.pits.get(self.ndx) {
fn doit<T: Atomic>((l, b): (&T, bool)) -> Option<T> {
if b {
Some(*l)
} else {
None
}
}
let pit = self
.frame
.span
.iter()
.zip(row.iter())
.filter_map(doit as fn((&T, bool)) -> Option<T>);
self.ndx += 1;
Some(pit)
} else {
None
}
}
}
|
/*
chapter 4
syntax and semantics
*/
fn main() {
let a = 1;
let b = 'c';
match a {
b => println!("a: {} b: {}", a, b),
}
match b {
a => println!("a: {} b: {}", a, b),
}
println!("a: {}", a);
println!("b: {}", b);
}
// output should be:
/*
*/
|
use crate::parse::{
Chunk, ChunkIter, Chunks, Expr, ExprApplication, ExprBinary, ExprNot, ExprValue, Fancy,
GenericArg, PathComponent, ValueBit, ValuePath, ValueUnsigned,
};
pub struct Translator<Output: std::io::Write> {
output: Output,
}
impl<Output: std::io::Write> Translator<Output> {
pub fn new(output: Output) -> Self {
Self { output }
}
pub fn translate(mut self, input: impl AsRef<[u8]>) {
let mut chunks = Chunks::new(input.as_ref());
let mut buffer = Vec::new();
while let Some((chunk, rest)) = chunks.next() {
chunks = rest;
match chunk {
Chunk::Unparsed(c) => {
buffer.push(c);
}
Chunk::Parsed(expr) => {
self.output.write_all(buffer.as_ref()).unwrap();
self.output.write_all(&Into::<Vec<u8>>::into(expr)).unwrap();
buffer = Vec::new();
}
}
}
self.output.write_all(&buffer).unwrap();
}
}
macro_rules! tokens {
($h:expr, $($t:expr),*) => {
$h.into_iter()$(.chain(Into::<Vec<u8>>::into($t)))*.collect()
}
}
impl<Item: Into<Vec<u8>>> From<Fancy<Item>> for Vec<u8> {
fn from(Fancy { code, item }: Fancy<Item>) -> Self {
code.into_iter().chain(item.into()).collect()
}
}
impl From<ValueBit> for usize {
fn from(bit: ValueBit) -> Self {
match bit {
ValueBit::B0 => 0,
ValueBit::B1 => 1,
}
}
}
impl From<ValueUnsigned> for usize {
fn from(unsigned: ValueUnsigned) -> Self {
match unsigned {
ValueUnsigned::UInt { msb, lsb } => {
2 * Into::<Self>::into(*msb) + Into::<Self>::into(lsb)
}
ValueUnsigned::UTerm => 0,
}
}
}
impl From<ValueUnsigned> for Vec<u8> {
fn from(unsigned: ValueUnsigned) -> Self {
let val: usize = unsigned.into();
val.to_string().into()
}
}
impl From<ValueBit> for bool {
fn from(bit: ValueBit) -> Self {
match bit {
ValueBit::B0 => false,
ValueBit::B1 => true,
}
}
}
impl From<ValueBit> for Vec<u8> {
fn from(bit: ValueBit) -> Self {
let val: bool = bit.into();
val.to_string().into()
}
}
impl From<GenericArg> for Vec<u8> {
fn from(arg: GenericArg) -> Self {
match arg {
GenericArg::Expr(expr) => expr.into(),
GenericArg::AssociatedType { name, ty } => {
let mut v: Vec<_> = name.into();
v.extend(b" = ");
v.extend(Into::<Vec<u8>>::into(ty));
v
}
}
}
}
impl From<PathComponent> for Vec<u8> {
fn from(component: PathComponent) -> Self {
let mut comma = vec![];
match component {
PathComponent::Args(args) => tokens![
"<".bytes(),
args.into_iter()
.map(Into::<Vec<u8>>::into)
.map(|arg| {
let delimitted = comma.clone().into_iter().chain(arg.into_iter());
comma = ", ".into();
delimitted
})
.flatten()
.collect::<Vec<_>>(),
">"
],
PathComponent::Ident(item) => item.into(),
PathComponent::Colon => "::".into(),
}
}
}
impl From<ValuePath> for Vec<u8> {
fn from(ValuePath(value): ValuePath) -> Self {
value
.into_iter()
.map(Into::<Vec<u8>>::into)
.flatten()
.collect()
}
}
impl From<ExprValue> for Vec<u8> {
fn from(expr: ExprValue) -> Self {
match expr {
ExprValue::Bit(expr) => expr.into(),
ExprValue::Unsigned(expr) => expr.into(),
ExprValue::Path(expr) => expr.into(),
}
}
}
impl From<ExprApplication> for Vec<u8> {
fn from(ExprApplication { lhs, application }: ExprApplication) -> Self {
match *application {
Expr::Binary(Fancy {
code,
item:
ExprBinary {
op,
expr,
result: Some(result),
},
}) => tokens![code, "{ ", *lhs, " ", op, " ", *expr, " == ", *result, " }"],
Expr::Binary(Fancy {
code,
item:
ExprBinary {
op,
expr,
result: None,
},
}) => tokens![code, "{ ", *lhs, " ", op, " ", *expr, " }"],
Expr::Unary(Fancy {
code,
item: ExprNot { result: None },
}) => tokens![code, "!", *lhs],
Expr::Unary(Fancy {
code,
item: ExprNot {
result: Some(result),
},
}) => tokens![code, "{ ", "!", *lhs, " == ", *result, " }"],
Expr::Value(expr) => expr.into(),
Expr::Application(expr) => expr.into(),
}
}
}
macro_rules! fancy_expr {
($ty:ident { $code:ident, $item:ident }) => {
Fancy {
$code,
$item: ExprApplication {
lhs: Box::new(Expr::Value(Fancy {
$code: "".into(),
$item: ExprValue::Path(ValuePath(vec![PathComponent::Ident(Fancy {
$code: "".into(),
$item: "_".into(),
})])),
})),
application: Box::new(Expr::$ty(Fancy {
$item,
$code: "".into(),
})),
},
}
};
}
impl From<Expr> for Vec<u8> {
fn from(expr: Expr) -> Self {
match expr {
Expr::Application(expr) => expr.into(),
Expr::Unary(Fancy { code, item }) => fancy_expr! { Unary { code, item } }.into(),
Expr::Binary(Fancy { code, item }) => fancy_expr! { Binary { code, item } }.into(),
Expr::Value(Fancy { code, item }) => fancy_expr! { Value { code, item } }.into(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use textwrap::dedent;
macro_rules! translate {
(parse: $input:literal, expect: $expected:literal $(,)?) => {
let mut output = Vec::new();
let translator = Translator::new(&mut output);
let input = dedent($input);
translator.translate(input.as_bytes());
let expected = dedent($expected);
let output = std::str::from_utf8(&output).unwrap();
assert_eq!(
output, expected,
"\nactual: {}\nexpected: {}",
output, expected
);
};
}
#[test]
fn translator_replaces_unsigned() {
translate! {
parse: "\
xxx typenum::uint::UTerm
xxx typenum::uint::UInt<typenum::uint::UInt<typenum::uint::UTerm, typenum::bit::B1>, typenum::bit::B1>
xxx",
expect: "\
xxx 0
xxx 3
xxx",
}
}
#[test]
fn unsigned_to_bytes_yields_decimal_encoding() {
translate! {
parse: "\
typenum::uint::UInt<typenum::uint::UInt<typenum::uint::UTerm, typenum::bit::B1>, typenum::bit::B0>
",
expect: "\
2
",
}
}
#[test]
fn bit_to_bytes_yields_bool_encoding() {
translate! {
parse: "typenum::bit::B0",
expect: "false",
}
translate! {
parse: "typenum::bit::B1",
expect: "true",
}
}
#[test]
fn unary_expr_to_bytes_yields_operator_and_translated_expr() {
translate! {
parse: "<typenum::bit::B0 as std::ops::Not>::Output",
expect: "!false",
}
}
#[test]
fn unary_expr_with_result_to_bytes_yields_operator_and_translated_expr_with_result() {
translate! {
parse: "<typenum::bit::B0 as std::ops::Not<Output = typenum::bit::B1>>",
expect: "{ !false == true }",
}
}
#[test]
fn binary_expr_to_bytes_yields_operator_and_translated_expr() {
translate! {
parse: "std::ops::Add<typenum::uint::UInt<typenum::uint::UTerm, typenum::bit::B1>>",
expect: "{ _ + 1 }",
}
}
#[test]
fn binary_expr_with_result_to_bytes_yields_operator_and_translated_expr_with_result() {
translate! {
parse: "std::ops::Add<typenum::uint::UInt<typenum::uint::UTerm, typenum::bit::B1>, Output = typenum::uint::UInt<typenum::uint::UTerm, typenum::bit::B1>>",
expect: "{ _ + 1 == 1 }",
}
}
#[test]
fn expressions_in_path_types_are_translated() {
translate! {
parse: "std::ops::Add<typenum::uint::UInt<typenum::uint::UTerm, typenum::bit::B1>, Output = mod::Type<typenum::uint::UTerm, AssociatedType = typenum::bit::B1>>",
expect: "{ _ + 1 == mod::Type<0, AssociatedType = true> }",
}
}
#[test]
fn app() {
translate! {
parse: "<Self as std::ops::Add<typenum::uint::UInt<typenum::uint::UTerm, typenum::bit::B1>>>::Output",
expect: "{ Self + 1 }",
}
}
#[test]
fn translator_replaces_missing_implementation() {
translate! {
parse: "\
error[E0277]: cannot subtract `typenum::uint::UInt<typenum::uint::UTerm, typenum::bit::B1>` from `Size`
--> verified/src/vec.rs:40:14
|
40 | self.into()
| ^^^^ no implementation for `Size - typenum::uint::UInt<typenum::uint::UTerm, typenum::bit::B1>`
|
= help: the trait `std::ops::Sub<typenum::uint::UInt<typenum::uint::UTerm, typenum::bit::B1>>` is not implemented for `Size`
help: consider further restricting this bound with `+ std::ops::Sub<typenum::uint::UInt<typenum::uint::UTerm, typenum::bit::B1>>`
--> verified/src/vec.rs:28:12
|
28 | impl<Size: Unsigned, Element> Vec<Size, Element> {
| ^^^^^^^^
= note: required because of the requirements on the impl of `std::convert::From<vec::Vec<Size, Element>>` for `(vec::Vec<<Size as std::ops::Sub<typenum::uint::UInt<typenum::uint::UInt<typenum::uint::UTerm, typenum::bit::B1>, typenum::bit::B0>>>::Output, Element>, Element)`
= note: required because of the requirements on the impl of `std::convert::Into<(vec::Vec<<Size as std::ops::Sub<typenum::uint::UInt<typenum::uint::UInt<typenum::uint::UTerm, typenum::bit::B1>, typenum::bit::B0>>>::Output, Element>, Element)>` for `vec::Vec<Size, Element>`",
expect: "\
error[E0277]: cannot subtract `1` from `Size`
--> verified/src/vec.rs:40:14
|
40 | self.into()
| ^^^^ no implementation for `Size - 1`
|
= help: the trait `{ _ - 1 }` is not implemented for `Size`
help: consider further restricting this bound with `+ { _ - 1 }`
--> verified/src/vec.rs:28:12
|
28 | impl<Size: Unsigned, Element> Vec<Size, Element> {
| ^^^^^^^^
= note: required because of the requirements on the impl of `std::convert::From<vec::Vec<Size, Element>>` for `(vec::Vec<{ Size - 2 }, Element>, Element)`
= note: required because of the requirements on the impl of `std::convert::Into<(vec::Vec<{ Size - 2 }, Element>, Element)>` for `vec::Vec<Size, Element>`",
}
}
#[test]
fn translator_replaces_unsigned_type_expectation() {
translate! {
parse: "\
error[E0308]: mismatched types
--> verified/src/vec.rs:59:18
|
59 | (Vec(s - U2::new(), v), e)
| ^^^^^^^^^ expected struct `typenum::uint::UTerm`, found struct `typenum::uint::UInt`
|
= note: expected struct `typenum::uint::UInt<typenum::uint::UTerm, typenum::bit::B1>`
found struct `typenum::uint::UInt<typenum::uint::UInt<typenum::uint::UTerm, typenum::bit::B1>, typenum::bit::B0>`",
expect: "\
error[E0308]: mismatched types
--> verified/src/vec.rs:59:18
|
59 | (Vec(s - U2::new(), v), e)
| ^^^^^^^^^ expected struct `0`, found struct `typenum::uint::UInt`
|
= note: expected struct `1`
found struct `2`",
}
}
#[test]
fn translator_parses_and_retains_control_chars() {
translate! {
parse: "\
\u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[32m Compiling\u{1b}[0m verified v0.2.3 (/home/bob/verified/verified)
\u{1b}[0m\u{1b}[1m\u{1b}[38;5;9merror[E0277]\u{1b}[0m\u{1b}[0m\u{1b}[1m: cannot subtract `typenum::uint::UInt<typenum::uint::UTerm, typenum::bit::B1>` from `Size`\u{1b}[0m
\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m--> \u{1b}[0m\u{1b}[0mverified/src/vec.rs:40:14\u{1b}[0m
\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m|\u{1b}[0m
\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m40\u{1b}[0m\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m| \u{1b}[0m\u{1b}[0m self.into()\u{1b}[0m
\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m| \u{1b}[0m\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;9m^^^^\u{1b}[0m\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;9mno implementation for `Size - typenum::uint::UInt<typenum::uint::UTerm, typenum::bit::B1>`\u{1b}[0m
\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m|\u{1b}[0m
\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m= \u{1b}[0m\u{1b}[0m\u{1b}[1mhelp\u{1b}[0m\u{1b}[0m: the trait `std::ops::Sub<typenum::uint::UInt<typenum::uint::UTerm, typenum::bit::B1>>` is not implemented for `Size`\u{1b}[0m
\u{1b}[0m\u{1b}[1m\u{1b}[38;5;14mhelp\u{1b}[0m\u{1b}[0m: consider further restricting this bound with `+ std::ops::Sub<typenum::uint::UInt<typenum::uint::UTerm, typenum::bit::B1>>`\u{1b}[0m
\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m--> \u{1b}[0m\u{1b}[0mverified/src/vec.rs:28:12\u{1b}[0m
\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m|\u{1b}[0m
\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m28\u{1b}[0m\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m| \u{1b}[0m\u{1b}[0mimpl<Size: Unsigned, Element> Vec<Size, Element> {\u{1b}[0m
\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m| \u{1b}[0m\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;14m^^^^^^^^\u{1b}[0m
\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m= \u{1b}[0m\u{1b}[0m\u{1b}[1mnote\u{1b}[0m\u{1b}[0m: required because of the requirements on the impl of `std::convert::From<vec::Vec<Size, Element>>` for `(vec::Vec<<Size as std::ops::Sub<typenum::uint::UInt<typenum::uint::UInt<typenum::uint::UTerm, typenum::bit::B1>, typenum::bit::B0>>>::Output, Element>, Element)`\u{1b}[0m
\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m= \u{1b}[0m\u{1b}[0m\u{1b}[1mnote\u{1b}[0m\u{1b}[0m: required because of the requirements on the impl of `std::convert::Into<(vec::Vec<<Size as std::ops::Sub<typenum::uint::UInt<typenum::uint::UInt<typenum::uint::UTerm, typenum::bit::B1>, typenum::bit::B0>>>::Output, Element>, Element)>` for `vec::Vec<Size, Element>`",
expect: "\
\u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[32m Compiling\u{1b}[0m verified v0.2.3 (/home/bob/verified/verified)
\u{1b}[0m\u{1b}[1m\u{1b}[38;5;9merror[E0277]\u{1b}[0m\u{1b}[0m\u{1b}[1m: cannot subtract `1` from `Size`\u{1b}[0m
\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m--> \u{1b}[0m\u{1b}[0mverified/src/vec.rs:40:14\u{1b}[0m
\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m|\u{1b}[0m
\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m40\u{1b}[0m\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m| \u{1b}[0m\u{1b}[0m self.into()\u{1b}[0m
\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m| \u{1b}[0m\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;9m^^^^\u{1b}[0m\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;9mno implementation for `Size - 1`\u{1b}[0m
\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m|\u{1b}[0m
\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m= \u{1b}[0m\u{1b}[0m\u{1b}[1mhelp\u{1b}[0m\u{1b}[0m: the trait `{ _ - 1 }` is not implemented for `Size`\u{1b}[0m
\u{1b}[0m\u{1b}[1m\u{1b}[38;5;14mhelp\u{1b}[0m\u{1b}[0m: consider further restricting this bound with `+ { _ - 1 }`\u{1b}[0m
\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m--> \u{1b}[0m\u{1b}[0mverified/src/vec.rs:28:12\u{1b}[0m
\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m|\u{1b}[0m
\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m28\u{1b}[0m\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m| \u{1b}[0m\u{1b}[0mimpl<Size: Unsigned, Element> Vec<Size, Element> {\u{1b}[0m
\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m| \u{1b}[0m\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;14m^^^^^^^^\u{1b}[0m
\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m= \u{1b}[0m\u{1b}[0m\u{1b}[1mnote\u{1b}[0m\u{1b}[0m: required because of the requirements on the impl of `std::convert::From<vec::Vec<Size, Element>>` for `(vec::Vec<{ Size - 2 }, Element>, Element)`\u{1b}[0m
\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m= \u{1b}[0m\u{1b}[0m\u{1b}[1mnote\u{1b}[0m\u{1b}[0m: required because of the requirements on the impl of `std::convert::Into<(vec::Vec<{ Size - 2 }, Element>, Element)>` for `vec::Vec<Size, Element>`",
}
translate! {
parse: "\
\u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[32m Compiling\u{1b}[0m verified v0.2.3 (/home/bob/verified/verified)
\u{1b}[0m\u{1b}[1m\u{1b}[38;5;9merror[E0308]\u{1b}[0m\u{1b}[0m\u{1b}[1m: mismatched types\u{1b}[0m
\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m--> \u{1b}[0m\u{1b}[0mverified/src/vec.rs:59:18\u{1b}[0m
\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m|\u{1b}[0m
\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m59\u{1b}[0m\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m| \u{1b}[0m\u{1b}[0m (Vec(s - U2::new(), v), e)\u{1b}[0m
\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m| \u{1b}[0m\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;9m^^^^^^^^^\u{1b}[0m\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;9mexpected struct `typenum::uint::UTerm`, found struct `typenum::uint::UInt`\u{1b}[0m
\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m|\u{1b}[0m
\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m= \u{1b}[0m\u{1b}[0m\u{1b}[1mnote\u{1b}[0m\u{1b}[0m: expected struct `typenum::uint::UInt<typenum::uint::UTerm, typenum::bit::\u{1b}[0m\u{1b}[0m\u{1b}[1mB1\u{1b}[0m\u{1b}[0m>`\u{1b}[0m
\u{1b}[0m found struct `typenum::uint::UInt<\u{1b}[0m\u{1b}[0m\u{1b}[1mtypenum::uint::UInt<\u{1b}[0m\u{1b}[0mtypenum::uint::UTerm, \u{1b}[0m\u{1b}[0m\u{1b}[1mtypenum::bit::B1>\u{1b}[0m\u{1b}[0m, typenum::bit::\u{1b}[0m\u{1b}[0m\u{1b}[1mB0\u{1b}[0m\u{1b}[0m>`",
expect: "\
\u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[32m Compiling\u{1b}[0m verified v0.2.3 (/home/bob/verified/verified)
\u{1b}[0m\u{1b}[1m\u{1b}[38;5;9merror[E0308]\u{1b}[0m\u{1b}[0m\u{1b}[1m: mismatched types\u{1b}[0m
\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m--> \u{1b}[0m\u{1b}[0mverified/src/vec.rs:59:18\u{1b}[0m
\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m|\u{1b}[0m
\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m59\u{1b}[0m\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m| \u{1b}[0m\u{1b}[0m (Vec(s - U2::new(), v), e)\u{1b}[0m
\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m| \u{1b}[0m\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;9m^^^^^^^^^\u{1b}[0m\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;9mexpected struct `0`, found struct `typenum::uint::UInt`\u{1b}[0m
\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m|\u{1b}[0m
\u{1b}[0m \u{1b}[0m\u{1b}[0m\u{1b}[1m\u{1b}[38;5;12m= \u{1b}[0m\u{1b}[0m\u{1b}[1mnote\u{1b}[0m\u{1b}[0m: expected struct `1`\u{1b}[0m
\u{1b}[0m found struct `2`",
}
}
}
|
/// This tests are ignored by default. Run them manually to check for possible differences between
/// local fixtures and actual public REST API returns. All methods/live_test calls MUST pass.
/// Run manually with: `$>cargo test --features network_test`
use arkecosystem_client::Connection;
use rand::seq::SliceRandom;
use std::collections::HashMap;
#[tokio::test]
#[cfg_attr(not(feature = "network_test"), ignore)]
async fn test_live_peers_all() {
let mut client = Connection::new(&get_random_seed());
client.peers.all().await.unwrap();
let params = [("limit", "20")].iter();
let peers = client.peers.all_params(params).await.unwrap();
client.peers.show(peers.data[0].ip.as_str()).await.unwrap();
}
#[tokio::test]
#[cfg_attr(not(feature = "network_test"), ignore)]
async fn test_live_blocks_all() {
let mut client = Connection::new(&get_random_seed());
let blocks = client.blocks.all().await.unwrap();
client
.blocks
.show(blocks.data[0].id.as_str())
.await
.unwrap();
client
.blocks
.transactions(blocks.data[0].id.as_str())
.await
.unwrap();
}
#[tokio::test]
#[cfg_attr(not(feature = "network_test"), ignore)]
async fn test_live_bridgechain_all() {
let mut client = Connection::new(&get_random_seed());
client.bridgechains.all().await.unwrap();
// TODO add more - when implemented
}
#[tokio::test]
#[cfg_attr(not(feature = "network_test"), ignore)]
async fn test_live_business() {
let mut client = Connection::new(&get_random_seed());
let businesses = client.businesses.all().await.unwrap();
client
.businesses
.bridgechains(businesses.data[0].public_key.as_str())
.await
.unwrap();
// TODO add more - when implemented
}
#[tokio::test]
#[cfg_attr(not(feature = "network_test"), ignore)]
async fn test_live_delegates_all() {
let mut client = Connection::new(&get_random_seed());
let actual = client.delegates.all().await.unwrap();
let params = [("limit", "20")].iter();
client.delegates.all_params(params).await.unwrap();
let delegate = client
.delegates
.show(actual.data[0].username.as_str())
.await
.unwrap();
client
.delegates
.blocks(delegate.data.address.as_str())
.await
.unwrap();
let params = [("limit", "10")].iter();
client
.delegates
.blocks_params(delegate.data.address.as_str(), params)
.await
.unwrap();
client
.delegates
.voters(delegate.data.address.as_str())
.await
.unwrap();
let params = [("limit", "4")].iter();
client
.delegates
.voters_params(delegate.data.address.as_str(), params)
.await
.unwrap();
let mut payload = HashMap::new();
payload.insert("username", "ale");
client
.delegates
.search(payload, [("limit", "20")].iter())
.await
.unwrap();
}
#[tokio::test]
#[cfg_attr(not(feature = "network_test"), ignore)]
async fn test_live_transactions_all() {
let mut client = Connection::new(&get_random_seed());
let actual = client.transactions.all().await.unwrap();
client
.transactions
.all_params([("limit", "20")].iter())
.await
.unwrap();
client
.transactions
.show(actual.data[0].id.as_str())
.await
.unwrap();
client.transactions.all_unconfirmed().await.unwrap();
client
.transactions
.all_unconfirmed_params([("limit", "20")].iter())
.await
.unwrap();
// client
// .transactions
// .show_unconfirmed(actual.data[0].id.as_str())
// .unwrap();
let mut query = HashMap::new();
query.insert("senderId", actual.data[0].sender.as_str());
client
.transactions
.search(query, [("limit", "20")].iter())
.await
.unwrap();
client.transactions.types().await.unwrap();
client.transactions.fees().await.unwrap();
}
#[tokio::test]
#[cfg_attr(not(feature = "network_test"), ignore)]
async fn test_live_wallets_all() {
let mut client = Connection::new(&get_random_seed());
let wallet = client.wallets.all().await.unwrap().data[0].clone();
client.wallets.show(wallet.address.as_str()).await.unwrap();
client
.wallets
.transactions(wallet.address.as_str())
.await
.unwrap();
client
.wallets
.sent_transactions(wallet.address.as_str())
.await
.unwrap();
client
.wallets
.received_transactions(wallet.address.as_str())
.await
.unwrap();
client.wallets.votes(wallet.address.as_str()).await.unwrap();
let mut query = HashMap::new();
query.insert("address", wallet.address.as_str());
client
.wallets
.search(query, [("limit", "20")].iter())
.await
.unwrap();
client.wallets.top().await.unwrap();
client.wallets.locks(wallet.address.as_str()).await.unwrap();
}
#[tokio::test]
#[cfg_attr(not(feature = "network_test"), ignore)]
async fn test_live_votes_all() {
let mut client = Connection::new(&get_random_seed());
let transaction = client.votes.all().await.unwrap().data[0].clone();
client
.votes
.all_params([("limit", "20")].iter())
.await
.unwrap();
client.votes.show(transaction.id.as_str()).await.unwrap();
}
#[tokio::test]
#[cfg_attr(not(feature = "network_test"), ignore)]
async fn test_live_locks_all() {
let mut client = Connection::new(&get_random_seed());
if !client.locks.all().await.unwrap().data.is_empty() {
let lock_data = client.locks.all().await.unwrap().data[0].clone();
client
.locks
.all_params([("senderPublicKey", lock_data.sender_public_key.as_str())].iter())
.await
.unwrap();
client.locks.show(&lock_data.lock_id).await.unwrap();
let mut query = HashMap::new();
query.insert("recipientId", lock_data.recipient_id.as_str());
client
.locks
.search(query, [("limit", "20")].iter())
.await
.unwrap();
let mut trx_ids = Vec::new();
trx_ids.push(lock_data.lock_id.as_str());
client.locks.unlocked(trx_ids).await.unwrap();
}
}
#[tokio::test]
#[cfg_attr(not(feature = "network_test"), ignore)]
async fn test_live_node_all() {
let mut client = Connection::new(&get_random_seed());
client.node.status().await.unwrap();
client.node.syncing().await.unwrap();
client.node.configuration().await.unwrap();
client.node.fees([("days", "20")].iter()).await.unwrap();
}
fn get_random_seed() -> String {
let seeds = vec![
"167.114.29.51",
"167.114.29.52",
"167.114.29.53",
"167.114.29.54",
"167.114.29.55",
];
format!(
"http://{}:4003/api/",
seeds.choose(&mut rand::thread_rng()).unwrap(),
)
}
|
#![no_std]
#![feature(start)]
#![no_main]
extern crate alloc;
use ferr_os_librust::syscall;
use ferr_os_librust::io;
use alloc::string::String;
#[no_mangle]
pub extern "C" fn _start(heap_address: u64, heap_size: u64) {
unsafe {
syscall::debug(1, 0);
syscall::set_screen_size(19, 79);
syscall::set_screen_pos(1, 1);
}
ferr_os_librust::allocator::init(heap_address, heap_size);
let a = String::from("User/root/test_io");
unsafe {
if syscall::fork() == 0 {
syscall::exec(a);
}
}
main();
}
#[inline(never)]
fn main() {
let mut read_buffer = [0_u8; 256];
let mut buffer = [0_u8; 256];
loop {
let length = unsafe { syscall::read(0, read_buffer.as_mut_ptr(), 256) };
let write_length = ferr_os_librust::interfaces::keyboard::decode_buffer(
&read_buffer[..],
&mut buffer[..],
length,
);
io::print_buffer(&buffer[..], write_length);
unsafe {
syscall::sleep()
};
}
}
|
impl Solution {
pub fn build_array(nums: Vec<i32>) -> Vec<i32> {
let ans = nums.iter().map(|&x| nums[x as usize]).collect();
return ans
}
} |
//! The *httptypes* crate is a collection of useful abstractions for
//! building HTTP clients and servers.
//!
//! It contains types for
//!
//! * [request method](enum.Method.html),
//! * [response status](struct.Status.html),
//! * [header fields](header/index.html) and
//! * the [protocol version](enum.Version.html).
//!
//! Each type has useful methods that help to implement HTTP.
#![feature(associated_consts)]
// Allow setting flags for clippy lints unknown to the compiler.
#![allow(unknown_lints)]
#![deny(missing_docs)]
#[cfg(feature="negotiation")]
extern crate charsets;
extern crate httpdate;
extern crate language_tags;
#[macro_use]
extern crate matches;
extern crate media_types;
extern crate url;
pub mod header;
mod method;
mod status;
mod util;
mod version;
pub use header::Header;
pub use method::Method;
pub use status::{Status, StatusClass};
pub use version::Version;
|
use crate::{cmd::*, result::Result};
mod add;
mod assert;
mod list;
mod transfer;
#[derive(Debug, StructOpt)]
/// Display list of hotspots associated with wallet
/// or transfer a hotspot to another wallet
pub enum Cmd {
Add(add::Cmd),
Assert(assert::Cmd),
List(list::Cmd),
Transfer(Box<transfer::Cmd>),
}
impl Cmd {
pub async fn run(self, opts: Opts) -> Result {
match self {
Self::Add(cmd) => cmd.run(opts).await,
Self::Assert(cmd) => cmd.run(opts).await,
Self::List(cmd) => cmd.run(opts).await,
Self::Transfer(cmd) => cmd.run(opts).await,
}
}
}
|
use log::{error, info, trace, warn};
mod config;
mod server;
mod stackvec;
mod tracker;
mod webserver;
use config::Configuration;
use std::process::exit;
fn setup_logging(cfg: &Configuration) {
let log_level = match cfg.get_log_level() {
None => log::LevelFilter::Info,
Some(level) => {
match level.as_str() {
"off" => log::LevelFilter::Off,
"trace" => log::LevelFilter::Trace,
"debug" => log::LevelFilter::Debug,
"info" => log::LevelFilter::Info,
"warn" => log::LevelFilter::Warn,
"error" => log::LevelFilter::Error,
_ => {
eprintln!("udpt: unknown log level encountered '{}'", level.as_str());
exit(-1);
}
}
}
};
if let Err(err) = fern::Dispatch::new()
.format(|out, message, record| {
out.finish(format_args!(
"{} [{}][{}] {}",
chrono::Local::now().format("%+"),
record.target(),
record.level(),
message
))
})
.level(log_level)
.chain(std::io::stdout())
.apply()
{
eprintln!("udpt: failed to initialize logging. {}", err);
std::process::exit(-1);
}
info!("logging initialized.");
}
#[tokio::main]
async fn main() {
let parser = clap::App::new(env!("CARGO_PKG_NAME"))
.about(env!("CARGO_PKG_DESCRIPTION"))
.author(env!("CARGO_PKG_AUTHORS"))
.version(env!("CARGO_PKG_VERSION"))
.arg(
clap::Arg::new("config")
.takes_value(true)
.short('c')
.help("Configuration file to load.")
.required(true),
);
let matches = parser.get_matches();
let cfg_path = matches.value_of("config").unwrap();
let cfg = match Configuration::load_file(cfg_path) {
Ok(v) => std::sync::Arc::new(v),
Err(e) => {
eprintln!("udpt: failed to open configuration: {}", e);
return;
}
};
setup_logging(&cfg);
let tracker_obj = match cfg.get_db_path() {
Some(path) => {
let file_path = std::path::Path::new(path);
if !file_path.exists() {
warn!("database file \"{}\" doesn't exist.", path);
tracker::TorrentTracker::new(cfg.get_mode().clone())
} else {
let mut input_file = match tokio::fs::File::open(file_path).await {
Ok(v) => v,
Err(err) => {
error!("failed to open \"{}\". error: {}", path.as_str(), err);
panic!("error opening file. check logs.");
}
};
match tracker::TorrentTracker::load_database(cfg.get_mode().clone(), &mut input_file).await {
Ok(v) => {
info!("database loaded.");
v
}
Err(err) => {
error!("failed to load database. error: {}", err);
panic!("failed to load database. check logs.");
}
}
}
}
None => tracker::TorrentTracker::new(cfg.get_mode().clone()),
};
let tracker = std::sync::Arc::new(tracker_obj);
if cfg.get_http_config().is_some() {
let https_tracker = tracker.clone();
let http_cfg = cfg.clone();
info!("Starting http server");
tokio::spawn(async move {
let http_cfg = http_cfg.get_http_config().unwrap();
let bind_addr = http_cfg.get_address();
let tokens = http_cfg.get_access_tokens();
let server = webserver::build_server(https_tracker, tokens.clone());
server.bind(bind_addr.parse::<std::net::SocketAddr>().unwrap()).await;
});
}
let udp_server = server::UDPTracker::new(cfg.clone(), tracker.clone())
.await
.expect("failed to bind udp socket");
trace!("Waiting for UDP packets");
let udp_server = tokio::spawn(async move {
if let Err(err) = udp_server.accept_packets().await {
eprintln!("error: {}", err);
}
});
let weak_tracker = std::sync::Arc::downgrade(&tracker);
if let Some(db_path) = cfg.get_db_path() {
let db_path = db_path.clone();
let interval = cfg.get_cleanup_interval().unwrap_or(600);
tokio::spawn(async move {
let interval = std::time::Duration::from_secs(interval);
let mut interval = tokio::time::interval(interval);
interval.tick().await; // first tick is immediate...
loop {
interval.tick().await;
if let Some(tracker) = weak_tracker.upgrade() {
tracker.periodic_task(&db_path).await;
} else {
break;
}
}
});
}
let ctrl_c = tokio::signal::ctrl_c();
tokio::select! {
_ = udp_server => { warn!("udp server exited.") },
_ = ctrl_c => { info!("CTRL-C, exiting...") },
}
if let Some(path) = cfg.get_db_path() {
info!("saving database...");
tracker.periodic_task(path).await;
}
info!("goodbye.");
}
|
pub mod d1;
pub mod d2;
pub mod d3;
pub mod d4;
pub mod d6;
pub mod d7;
pub mod d8;
pub mod d10;
|
use std::error::Error;
use std::cmp::Ordering;
#[derive(Copy, Clone, Eq)]
pub struct Version {
versionBytes:[u8;4],
versionHash:u32,
}
impl Version {
pub fn parse( string:&String ) -> Result< Version, String >{
let mut v=[0u32;4];
let mut c=0;
for ns in string.split('.'){
match ns.parse::<u32>(){
Ok( n ) => {
if n>255 {
return Err( format!("Max value of part of version must be less then 256"));
}
if c>=4 {
return Err( format!("Version is too long, version should have 4 parts like *.*.*.*"));
}
v[c]=n;
c+=1;
},
Err( e )=>return Err( format!("Can not parse version: {}", e.description())),
}
}
if c!=4 {
return Err( format!("Version is too short, version should have 4 parts like *.*.*.*"));
}
let versionHash=v[0] * 16777216+
v[1] * 65536+
v[2] * 256+
v[3];
Ok(Version{
versionBytes:[v[0] as u8, v[1] as u8, v[2] as u8, v[3] as u8],
versionHash:versionHash,
})
}
pub fn print(&self) -> String{
let v=&self.versionBytes;
format!("{}.{}.{}.{}",v[0],v[1],v[2],v[3])
}
}
impl PartialOrd for Version{
fn partial_cmp(&self, other: &Version) -> Option<Ordering> {
Some(self.cmp(other))
}
/*
fn lt(&self, other: &Self) -> bool { self.versionHash<other.versionHash }
fn le(&self, other: &Self) -> bool { self.versionHash<=other.versionHash }
fn gt(&self, other: &Self) -> bool { self.versionHash>other.versionHash }
fn ge(&self, other: &Self) -> bool { self.versionHash>=other.versionHash }
*/
}
impl Ord for Version {
fn cmp(&self, other: &Self) -> Ordering {
self.versionHash.cmp(&other.versionHash)
}
}
impl PartialEq for Version{
fn eq(&self, other: &Self) -> bool { self.versionHash==other.versionHash }
fn ne(&self, other: &Self) -> bool { self.versionHash!=other.versionHash }
}
|
#![feature(proc_macro_hygiene)]
#![feature(exclusive_range_pattern)]
#![feature(option_result_contains)]
#![warn(anonymous_parameters)]
#![warn(bare_trait_objects)]
#![warn(elided_lifetimes_in_paths)]
#![warn(missing_debug_implementations)]
#![warn(single_use_lifetimes)]
#![warn(trivial_casts)]
#![warn(unreachable_pub)]
#![warn(unsafe_code)]
#![warn(unused_extern_crates)]
#![warn(unused_import_braces)]
#![warn(unused_qualifications)]
#![warn(unused_results)]
#![warn(variant_size_differences)]
#![warn(clippy::cargo_common_metadata)]
#![warn(clippy::cast_lossless)]
#![warn(clippy::clone_on_ref_ptr)]
#![warn(clippy::copy_iterator)]
#![warn(clippy::default_trait_access)]
#![warn(clippy::else_if_without_else)]
#![warn(clippy::empty_line_after_outer_attr)]
#![warn(clippy::exit)]
#![warn(clippy::expl_impl_clone_on_copy)]
#![warn(clippy::explicit_into_iter_loop)]
#![warn(clippy::explicit_iter_loop)]
#![warn(clippy::fallible_impl_from)]
#![warn(clippy::filter_map)]
#![warn(clippy::filter_map_next)]
#![warn(clippy::find_map)]
#![warn(clippy::get_unwrap)]
#![warn(clippy::if_not_else)]
#![warn(clippy::invalid_upcast_comparisons)]
#![warn(clippy::items_after_statements)]
#![warn(clippy::large_digit_groups)]
#![warn(clippy::large_stack_arrays)]
#![warn(clippy::linkedlist)]
#![warn(clippy::map_flatten)]
#![warn(clippy::match_same_arms)]
#![warn(clippy::maybe_infinite_iter)]
#![warn(clippy::mem_forget)]
#![warn(clippy::missing_const_for_fn)]
// #![warn(clippy::multiple_inherent_impl)]
#![warn(clippy::mut_mut)]
#![warn(clippy::mutex_integer)]
#![warn(clippy::needless_borrow)]
#![warn(clippy::needless_continue)]
// #![warn(clippy::needless_pass_by_value)]
#![warn(clippy::option_map_unwrap_or)]
#![warn(clippy::option_map_unwrap_or_else)]
#![warn(clippy::option_unwrap_used)]
// #![warn(clippy::panic)]
#![warn(clippy::path_buf_push_overwrite)]
#![warn(clippy::print_stdout)]
#![warn(clippy::pub_enum_variant_names)]
#![warn(clippy::redundant_closure_for_method_calls)]
#![warn(clippy::replace_consts)]
#![warn(clippy::result_map_unwrap_or_else)]
#![warn(clippy::result_unwrap_used)]
#![warn(clippy::same_functions_in_if_condition)]
#![warn(clippy::similar_names)]
#![warn(clippy::todo)]
#![warn(clippy::too_many_lines)]
#![warn(clippy::type_repetition_in_bounds)]
#![warn(clippy::unimplemented)]
#![warn(clippy::unreachable)]
#![warn(clippy::unused_self)]
#![warn(clippy::use_debug)]
#![warn(clippy::use_self)]
#![warn(clippy::used_underscore_binding)]
#![warn(clippy::wildcard_dependencies)]
#![doc(html_favicon_url = "https://raw.githubusercontent.com/kyleu/rustimate/master/crates/assets/embed/favicon.ico")]
#![doc(html_logo_url = "https://raw.githubusercontent.com/kyleu/rustimate/master/crates/assets/embed/favicon.png")]
#![doc(issue_tracker_base_url = "https://github.com/kyleu/rustimate/issues/")]
//! `rustimate-client` is run in the client's browser as a WebAssembly package.
#[macro_use]
pub(crate) mod logging;
mod ctx;
mod event_handler;
mod html;
mod js;
mod members;
mod message_handler;
mod poll_result;
mod polls;
mod session_ctx;
pub(crate) mod socket {
pub(crate) mod ws;
pub(crate) mod ws_events;
pub(crate) mod ws_handlers;
}
pub(crate) mod templates {
pub(crate) mod card;
pub(crate) mod member;
pub(crate) mod poll;
}
pub(crate) mod votes;
|
use std::collections::HashSet;
use std::default::Default;
use std::path::{Path, PathBuf};
use array_tool::vec::Uniq;
use diesel::connection::Connection;
use diesel::sqlite::SqliteConnection;
use if_let_return::if_let_some;
use indexmap::indexset;
use lazy_init::Lazy;
use regex::Regex;
use serde_derive::{Serialize, Deserialize};
use crate::correction::Corrector;
use crate::db::model::{Definition as ModelDef};
use crate::errors::{AppError, AppResult, AppResultU};
use crate::str_utils::{fix_word, shorten, uncase};
pub struct Dictionary {
corrector: Lazy<AppResult<Corrector>>,
path: PathBuf,
}
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub enum Text {
Annot(String),
Class(String),
Countability(char),
Definition(String),
Error(String),
Etymology(String),
Example(String),
Information(String),
Note(String),
Tag(String),
Word(String),
}
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub struct Definition {
pub key: String,
pub content: Vec<Text>,
}
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub struct Entry {
pub key: String,
pub definitions: Vec<Definition>,
}
#[derive(Clone)]
pub struct DictionaryWriter<'a> {
connection: &'a SqliteConnection,
source: Option<&'a str>,
}
pub struct Stat {
pub aliases: usize,
pub words: usize,
}
impl Dictionary {
pub fn new<T: AsRef<Path>>(dictionary_path: &T) -> Self {
Dictionary {
corrector: Lazy::new(),
path: dictionary_path.as_ref().to_path_buf()
}
}
pub fn correct(&mut self, word: &str) -> Vec<String> {
println!("Correcting...");
let corrector = self.corrector.get_or_create(|| {
let connection = self.connect_db()?;
let keys = diesel_query!(definitions [Q R] {
d::definitions
.select(d::term)
.load::<String>(&connection)?
});
Ok(Corrector { keys: keys.into_iter().collect() })
});
match corrector {
Ok(corrector) => {
corrector.correct(word)
}
Err(error) => {
eprintln!("{}", error);
vec![]
}
}
}
pub fn get_word<T: AsRef<Path>>(dictionary_path: &T, word: &str) -> Result<Option<Vec<Entry>>, AppError> {
let mut dic = Dictionary::new(dictionary_path);
Ok(dic.get_smart(&word)?)
}
pub fn get(&mut self, word: &str) -> AppResult<Option<Vec<Entry>>> {
fn opt(result: Vec<Entry>) -> Option<Vec<Entry>> {
if result.is_empty() {
return None;
}
Some(result)
}
let connection = self.connect_db()?;
let mut candidates = indexset!(word.to_owned());
let mut result = vec![];
for stemmed in stem(&word) {
candidates.insert(stemmed);
}
if let Some(aliases) = lookup_unaliased(&connection, word)? {
for alias in aliases.split('\n') {
candidates.insert(alias.to_owned());
}
}
for candidate in &candidates {
if let Some(entry) = lookup_entry(&connection, candidate)? {
result.push(entry);
}
}
Ok(opt(result))
}
pub fn get_level(&mut self, word: &str) -> AppResult<Option<u8>> {
fn get_level(connection: &SqliteConnection, word: &str) -> AppResult<Option<u8>> {
diesel_query!(levels [Q E R O] {
let found = d::levels
.filter(d::term.eq(word))
.select(d::level)
.first::<i32>(connection)
.optional()?;
Ok(found.map(|it| it as u8))
})
}
let connection = self.connect_db()?;
let found = get_level(&connection, word)?;
if found.is_some() {
return Ok(found)
}
let lemmed = lemmatize(&connection, word)?;
get_level(&connection, &lemmed)
}
pub fn get_smart(&mut self, word: &str) -> Result<Option<Vec<Entry>>, AppError> {
if_let_some!(fixed = fix_word(word), Ok(None));
for shortened in shorten(&fixed) {
let mut result = self.get_similars(&shortened)?;
if let Some(result) = result.as_mut() {
return Ok(Some(result.unique()))
}
}
let uncased = uncase(&word);
if uncased != word {
if let Some(result) = self.get_smart(&uncased)? {
return Ok(Some(result))
}
}
let splitter = Regex::new(r"[-#'=\s]+")?;
let mut candidates: Vec<&str> = splitter.split(&fixed).collect();
candidates.sort_by(|a, b| a.len().cmp(&b.len()).reverse());
for candidate in candidates {
let result = self.get(candidate)?;
if result.is_some() {
return Ok(result);
}
}
Ok(None)
}
pub fn keys(&mut self) -> AppResult<Vec<String>> {
let connection = self.connect_db()?;
let keys = diesel_query!(definitions [Q R] {
d::definitions
.select(d::term)
.load::<String>(&connection)?
});
Ok(keys)
}
pub fn lemmatize(&mut self, word: &str) -> AppResult<String> {
let connection = self.connect_db()?;
lemmatize(&connection, word)
}
pub fn like(&self, query: &str) -> AppResult<Option<Vec<Entry>>> {
let connection = self.connect_db()?;
let found: Vec<ModelDef> = diesel_query!(definitions, Definition [Q R T] {
d::definitions.
filter(d::term.like(query))
.order((d::term, d::id))
.load::<Definition>(&connection)?
});
if found.is_empty() {
return Ok(None)
}
Ok(Some(compact_definitions(found)?))
}
pub fn search(&self, query: &str) -> AppResult<Option<Vec<Entry>>> {
let connection = self.connect_db()?;
let found = diesel_query!(definitions, Definition [B E Q R T] {
use diesel::BoxableExpression;
use diesel::sql_types::Bool;
let truee = Box::new(d::term.eq(d::term));
let q: Box<dyn BoxableExpression<d::definitions, _, SqlType = Bool>> =
query.split_ascii_whitespace()
.map(|it| d::text.like(format!("%{}%", it)))
.fold(truee, |q, it| Box::new(q.and(it)));
d::definitions.
filter(q)
.order((d::term, d::id))
.load::<Definition>(&connection)?
});
Ok(Some(compact_definitions(found)?))
}
pub fn write<F>(&mut self, mut f: F) -> AppResult<Stat> where F: FnMut(&mut DictionaryWriter) -> AppResultU {
if self.path.exists() {
std::fs::remove_file(&self.path)?;
}
let connection = self.connect_db()?;
diesel_query!([R] {
for sql in include_str!("../migrations.sql").split(';') {
diesel::sql_query(sql).execute(&connection)?;
}
});
connection.transaction::<_, AppError, _>(|| {
use crate::db::schema;
use diesel::RunQueryDsl;
diesel::delete(schema::aliases::dsl::aliases).execute(&connection)?;
diesel::delete(schema::definitions::dsl::definitions).execute(&connection)?;
diesel::delete(schema::lemmatizations::dsl::lemmatizations).execute(&connection)?;
diesel::delete(schema::levels::dsl::levels).execute(&connection)?;
let mut writer = DictionaryWriter::new(&connection, None);
f(&mut writer)?;
stat(&connection)
})
}
fn connect_db(&self) -> AppResult<SqliteConnection> {
let path = self.path.to_str().ok_or(AppError::Unexpect("WTF: connection"))?;
Ok(SqliteConnection::establish(path)?)
}
fn get_similars(&mut self, word: &str) -> AppResult<Option<Vec<Entry>>> {
let mut result = self.get(word)?;
{
let mut mutated = vec![];
let chars = [',', '\'', '=', ' '];
for from in &chars {
for to in &["-", " ", ""] {
let replaced = word.replace(*from, to);
if replaced != word {
if let Some(result) = self.get(&replaced)? {
mutated.extend_from_slice(&result);
}
}
}
}
if !mutated.is_empty() {
if result.is_none() {
result = Some(mutated);
} else if let Some(content) = result.as_mut() {
content.extend_from_slice(&mutated);
}
}
}
Ok(result)
}
pub fn wordle_words(&self, min: u8, max: u8) -> AppResult<Vec<String>> {
let connection = self.connect_db()?;
let found = diesel_query!(levels [E Q R T] {
d::levels
.filter(d::level.ge(i32::from(min)))
.filter(d::level.le(i32::from(max)))
.filter(d::term.like("_____"))
.select(d::term)
.load::<String>(&connection)?
});
Ok(found)
}
}
fn compact_definitions(defs: Vec<ModelDef>) -> AppResult<Vec<Entry>> {
let defs: serde_json::Result<Vec<(String, Definition)>> =
defs.into_iter().map(|it| serde_json::from_str::<Definition>(&it.definition).map(|d| (it.term, d))).collect();
let defs = defs?;
let mut result = vec![];
let mut buffer = vec![];
let mut last_key = defs[0].0.clone();
for (key, def) in defs {
if key == last_key {
buffer.push(def);
} else {
let mut definitions = vec![def];
let mut key = key;
std::mem::swap(&mut buffer, &mut definitions);
std::mem::swap(&mut key, &mut last_key);
result.push(Entry { key, definitions });
}
}
if !buffer.is_empty() {
result.push(Entry { key: last_key, definitions: buffer });
}
Ok(result)
}
fn lemmatize(connection: &SqliteConnection, word: &str) -> AppResult<String> {
let mut lemmed = word.to_owned();
let mut path = HashSet::<String>::new();
while let Some(found) = lookup_lemmatized(connection, &lemmed)? {
if !path.insert(found.clone()) {
return Ok(lemmed)
}
lemmed = found;
}
if lookup_entry(connection, &lemmed)?.is_some() {
return Ok(lemmed.to_owned());
}
for stemmed in stem(&lemmed) {
if lookup_entry(connection, &stemmed)?.is_some() {
return Ok(stemmed);
}
}
Ok(lemmed.to_owned())
}
fn lookup_entry(connection: &SqliteConnection, word: &str) -> AppResult<Option<Entry>> {
let found = diesel_query!(definitions, Definition [Q E R] {
d::definitions
.filter(d::term.eq(word))
.load::<Definition>(connection)?
});
if found.is_empty() {
return Ok(None)
}
let defs: serde_json::Result<Vec<Definition>> = found.iter().map(|it| serde_json::from_str::<Definition>(&it.definition)).collect();
Ok(Some(Entry {
key: word.to_owned(),
definitions: defs?,
}))
}
fn lookup_lemmatized(connection: &SqliteConnection, word: &str) -> AppResult<Option<String>> {
diesel_query!(lemmatizations, Lemmatization [Q E R] {
let found = d::lemmatizations
.filter(d::source.eq(word))
.limit(1)
.load::<Lemmatization>(connection)?;
Ok(found.get(0).map(|it| it.target.to_owned()))
})
}
fn lookup_unaliased(connection: &SqliteConnection, word: &str) -> AppResult<Option<String>> {
diesel_query!(aliases, Alias [Q E R] {
let found = d::aliases
.filter(d::source.eq(word))
.limit(1)
.load::<Alias>(connection)?;
Ok(found.get(0).map(|it| it.target.to_owned()))
})
}
fn stat(connection: &SqliteConnection) -> AppResult<Stat> {
// FIXME
let words = diesel_query!(definitions [Q R] {
d::definitions
.select(d::term)
.distinct()
.load::<String>(connection)
})?.len();
let aliases = diesel_query!(aliases [Q R] {
use diesel::dsl::count;
d::aliases
.select(count(d::id))
.first::<i64>(connection)
})? as usize;
Ok(Stat { aliases, words })
}
fn stem(word: &str) -> Vec<String> {
let pairs = [
("ied", "y"),
("ier", "y"),
("ies", "y"),
("iest", "y"),
("nning", "n"),
("est", ""),
("ing", ""),
("'s", ""),
("ed", ""),
("ed", "e"),
("er", ""),
("es", ""),
("s", ""),
];
let mut result = vec![];
let wlen = word.len();
for (suffix, to) in &pairs {
if wlen < suffix.len() + 2 {
break;
}
if word.ends_with(suffix) {
result.push(format!("{}{}", &word[0 .. wlen - suffix.len()], to));
}
}
result
}
impl<'a> DictionaryWriter<'a> {
fn new(connection: &'a SqliteConnection, source: Option<&'a str>) -> Self {
DictionaryWriter {
connection,
source
}
}
pub fn with_source(self, source: Option<&'a str>) -> Self {
DictionaryWriter {
connection: self.connection,
source,
}
}
pub fn alias(&mut self, from: &str, to: &str, for_lemmatization: bool) -> AppResultU {
if let (Some(from), Some(to)) = (fix_word(from), fix_word(to)) {
if from == to {
return Ok(());
}
if for_lemmatization {
diesel_query!(lemmatizations [E R] {
diesel::insert_into(d::lemmatizations)
.values((d::source.eq(&from), d::target.eq(&to)))
.execute(self.connection)?;
});
}
diesel_query!(aliases [E R] {
diesel::insert_into(d::aliases)
.values((d::source.eq(&from), d::target.eq(&to)))
.execute(self.connection)?;
});
}
Ok(())
}
pub fn define(&mut self, key: &str, content: Vec<Text>) -> AppResultU {
let lkey = key.to_lowercase();
let mut buffer = "".to_owned();
for it in &content {
if let Some(s) = it.text_for_search() {
if !buffer.is_empty() {
buffer.push(' ');
}
buffer.push_str(s);
}
}
let def = Definition { key: key.to_owned(), content };
diesel_query!(definitions [E R] {
let serialized = serde_json::to_string(&def).unwrap();
diesel::insert_into(d::definitions)
.values((d::term.eq(lkey), d::definition.eq(serialized), d::text.eq(&buffer), d::source.eq(self.source)))
.execute(self.connection)?;
});
Ok(())
}
pub fn tag(&mut self, term: &str, tag: &str) -> AppResultU {
diesel_query!(tags [E R] {
diesel::insert_into(d::tags)
.values((d::term.eq(&term), d::tag.eq(&tag)))
.execute(self.connection)?;
});
Ok(())
}
pub fn levelize(&mut self, level: u8, key: &str) -> AppResultU {
diesel_query!(levels [E R] {
diesel::replace_into(d::levels)
.values((d::term.eq(&key), d::level.eq(i32::from(level))))
.execute(self.connection)?;
});
Ok(())
}
}
// TODO REMOVE ME
impl Default for Definition {
fn default() -> Self {
Definition { key: "dummy-key".to_owned(), content: vec![Text::Note("dummy-content".to_owned())] }
}
}
impl Text {
fn text_for_search(&self) -> Option<&str> {
use self::Text::*;
match self {
Annot(s) | Definition(s) | Example(s) | Information(s) | Note(s) =>
Some(s),
Class(_) | Countability(_) | Error(_) | Etymology(_) | Tag(_) | Word(_) =>
None,
}
}
}
|
use capstone_rust::capstone;
use capstone_rust::capstone::{cs_x86_op};
use capstone_rust::capstone_sys::{x86_op_type, x86_reg};
use error::*;
use il::*;
use il::Expression as Expr;
const MEM_SIZE: u64 = (1 << 48);
/// Struct for dealing with x86 registers
pub struct X86Register {
name: &'static str,
// The capstone enum value for this register.
capstone_reg: x86_reg,
/// The full register. For example, eax is the full register for al.
full_reg: x86_reg,
/// The offset of this register. For example, ah is offset 8 bit into eax.
offset: usize,
/// The size of this register in bits
bits: usize,
}
impl X86Register {
pub fn bits(&self) -> usize {
self.bits
}
/// Returns true if this is a full-width register (i.e. eax, ebx, etc)
pub fn is_full(&self) -> bool {
if self.capstone_reg == self.full_reg {
true
}
else {
false
}
}
/// Returns the full-width register for this register
pub fn get_full(&self) -> Result<&'static X86Register> {
get_register(self.full_reg)
}
/// Returns an expression which evaluates to the value of the register.
///
/// This handles things like al/ah/ax/eax
pub fn get(&self) -> Result<Expression> {
if self.is_full() {
Ok(expr_scalar(self.name, self.bits))
}
else if self.offset == 0 {
Expr::trun(self.bits, self.get_full()?.get()?)
}
else {
let full_reg = self.get_full()?;
let expr = Expr::shr(full_reg.get()?, expr_const(self.offset as u64, full_reg.bits))?;
Expr::trun(self.bits, expr)
}
}
/// Sets the value of this register.
///
/// This handles things like al/ah/ax/eax
pub fn set(&self, block: &mut Block, value: Expression) -> Result<()> {
if self.is_full() {
block.assign(scalar(self.name, self.bits), value);
Ok(())
}
else if self.offset == 0 {
let full_reg = self.get_full()?;
let mask = !0 << self.bits;
let expr = Expr::and(full_reg.get()?, expr_const(mask, full_reg.bits))?;
let expr = Expr::or(expr, Expr::zext(full_reg.bits, value)?)?;
full_reg.set(block, expr)
}
else {
let full_reg = self.get_full()?;
let mask = ((1 << self.bits) - 1) << self.offset;
let expr = Expr::and(full_reg.get()?, expr_const(mask, full_reg.bits))?;
let value = Expr::zext(full_reg.bits, value)?;
let expr = Expr::or(expr, Expr::shl(value, expr_const(self.offset as u64, full_reg.bits))?)?;
full_reg.set(block, expr)
}
}
}
const X86REGISTERS : &'static [X86Register] = &[
X86Register { name: "ah", capstone_reg: x86_reg::X86_REG_AH, full_reg: x86_reg::X86_REG_EAX, offset: 8, bits: 8 },
X86Register { name: "al", capstone_reg: x86_reg::X86_REG_AL, full_reg: x86_reg::X86_REG_EAX, offset: 0, bits: 8 },
X86Register { name: "ax", capstone_reg: x86_reg::X86_REG_AX, full_reg: x86_reg::X86_REG_EAX, offset: 0, bits: 16 },
X86Register { name: "eax", capstone_reg: x86_reg::X86_REG_EAX, full_reg: x86_reg::X86_REG_EAX, offset: 0, bits: 32 },
X86Register { name: "bh", capstone_reg: x86_reg::X86_REG_BH, full_reg: x86_reg::X86_REG_EBX, offset: 8, bits: 8 },
X86Register { name: "bl", capstone_reg: x86_reg::X86_REG_BL, full_reg: x86_reg::X86_REG_EBX, offset: 0, bits: 8 },
X86Register { name: "bx", capstone_reg: x86_reg::X86_REG_BX, full_reg: x86_reg::X86_REG_EBX, offset: 0, bits: 16 },
X86Register { name: "ebx", capstone_reg: x86_reg::X86_REG_EBX, full_reg: x86_reg::X86_REG_EBX, offset: 0, bits: 32 },
X86Register { name: "ch", capstone_reg: x86_reg::X86_REG_CH, full_reg: x86_reg::X86_REG_ECX, offset: 8, bits: 8 },
X86Register { name: "cl", capstone_reg: x86_reg::X86_REG_CL, full_reg: x86_reg::X86_REG_ECX, offset: 0, bits: 8 },
X86Register { name: "cx", capstone_reg: x86_reg::X86_REG_CX, full_reg: x86_reg::X86_REG_ECX, offset: 0, bits: 16 },
X86Register { name: "ecx", capstone_reg: x86_reg::X86_REG_ECX, full_reg: x86_reg::X86_REG_ECX, offset: 0, bits: 32 },
X86Register { name: "dh", capstone_reg: x86_reg::X86_REG_DH, full_reg: x86_reg::X86_REG_EDX, offset: 8, bits: 8 },
X86Register { name: "dl", capstone_reg: x86_reg::X86_REG_DL, full_reg: x86_reg::X86_REG_EDX, offset: 0, bits: 8 },
X86Register { name: "dx", capstone_reg: x86_reg::X86_REG_DX, full_reg: x86_reg::X86_REG_EDX, offset: 0, bits: 16 },
X86Register { name: "edx", capstone_reg: x86_reg::X86_REG_EDX, full_reg: x86_reg::X86_REG_EDX, offset: 0, bits: 32 },
X86Register { name: "si", capstone_reg: x86_reg::X86_REG_SI, full_reg: x86_reg::X86_REG_ESI, offset: 0, bits: 16 },
X86Register { name: "esi", capstone_reg: x86_reg::X86_REG_ESI, full_reg: x86_reg::X86_REG_ESI, offset: 0, bits: 32 },
X86Register { name: "di", capstone_reg: x86_reg::X86_REG_DI, full_reg: x86_reg::X86_REG_EDI, offset: 0, bits: 16 },
X86Register { name: "edi", capstone_reg: x86_reg::X86_REG_EDI, full_reg: x86_reg::X86_REG_EDI, offset: 0, bits: 32 },
X86Register { name: "sp", capstone_reg: x86_reg::X86_REG_SP, full_reg: x86_reg::X86_REG_ESP, offset: 0, bits: 16 },
X86Register { name: "esp", capstone_reg: x86_reg::X86_REG_ESP, full_reg: x86_reg::X86_REG_ESP, offset: 0, bits: 32 },
X86Register { name: "bp", capstone_reg: x86_reg::X86_REG_BP, full_reg: x86_reg::X86_REG_EBP, offset: 0, bits: 16 },
X86Register { name: "ebp", capstone_reg: x86_reg::X86_REG_EBP, full_reg: x86_reg::X86_REG_EBP, offset: 0, bits: 32 },
X86Register { name: "fs", capstone_reg: x86_reg::X86_REG_FS, full_reg: x86_reg::X86_REG_FS, offset: 0, bits: 16 },
X86Register { name: "gs", capstone_reg: x86_reg::X86_REG_FS, full_reg: x86_reg::X86_REG_GS, offset: 0, bits: 16 },
X86Register { name: "ds", capstone_reg: x86_reg::X86_REG_FS, full_reg: x86_reg::X86_REG_DS, offset: 0, bits: 16 },
X86Register { name: "es", capstone_reg: x86_reg::X86_REG_FS, full_reg: x86_reg::X86_REG_ES, offset: 0, bits: 16 },
X86Register { name: "cs", capstone_reg: x86_reg::X86_REG_FS, full_reg: x86_reg::X86_REG_CS, offset: 0, bits: 16 },
X86Register { name: "ss", capstone_reg: x86_reg::X86_REG_FS, full_reg: x86_reg::X86_REG_SS, offset: 0, bits: 16 },
];
/// Takes a capstone register enum and returns an `X86Register`
pub fn get_register(capstone_id: x86_reg) -> Result<&'static X86Register> {
for register in X86REGISTERS.iter() {
if register.capstone_reg == capstone_id {
return Ok(®ister);
}
}
Err("Could not find register".into())
}
/// Returns the details section of an x86 capstone instruction.
pub fn details(instruction: &capstone::Instr) -> Result<capstone::cs_x86> {
let detail = instruction.detail.as_ref().unwrap();
match detail.arch {
capstone::DetailsArch::X86(x) => Ok(x),
_ => Err("Could not get instruction details".into())
}
}
/// Gets the value of an operand as an IL expression
pub fn operand_value(operand: &cs_x86_op) -> Result<Expression> {
match operand.type_ {
x86_op_type::X86_OP_INVALID => Err("Invalid operand".into()),
x86_op_type::X86_OP_REG => {
// Get the register value
get_register(*operand.reg())?.get()
}
x86_op_type::X86_OP_MEM => {
let mem = operand.mem();
let base_capstone_reg = capstone::x86_reg::from(mem.base);
let index_capstone_reg = capstone::x86_reg::from(mem.index);
let base = match base_capstone_reg {
x86_reg::X86_REG_INVALID => None,
reg => Some(get_register(reg)?.get()?)
};
let index = match index_capstone_reg {
x86_reg::X86_REG_INVALID => None,
reg => Some(get_register(reg)?.get()?)
};
let scale = Expr::constant(Constant::new(mem.scale as i64 as u64, 32));
let si = match index {
Some(index) => Some(Expr::mul(index, scale).unwrap()),
None => None
};
// Handle base and scale/index
let op : Option<Expression> = if base.is_some() {
if si.is_some() {
Some(Expr::add(base.unwrap(), si.unwrap()).unwrap())
}
else {
base
}
}
else if si.is_some() {
si
}
else {
None
};
// handle disp
let op = if op.is_some() {
if mem.disp > 0 {
Expr::add(op.unwrap(), expr_const(mem.disp as u64, 32))?
}
else if mem.disp < 0 {
Expr::sub(op.unwrap(), expr_const(mem.disp.abs() as u64, 32))?
}
else {
op.unwrap()
}
}
else {
expr_const(mem.disp as u64, 32)
};
match x86_reg::from(mem.segment) {
x86_reg::X86_REG_INVALID =>
Ok(op),
x86_reg::X86_REG_CS =>
Ok(Expr::add(expr_scalar("cs_base", 32), op)?),
x86_reg::X86_REG_DS =>
Ok(Expr::add(expr_scalar("ds_base", 32), op)?),
x86_reg::X86_REG_ES =>
Ok(Expr::add(expr_scalar("es_base", 32), op)?),
x86_reg::X86_REG_FS =>
Ok(Expr::add(expr_scalar("fs_base", 32), op)?),
x86_reg::X86_REG_GS =>
Ok(Expr::add(expr_scalar("gs_base", 32), op)?),
x86_reg::X86_REG_SS =>
Ok(Expr::add(expr_scalar("ss_base", 32), op)?),
_ => bail!("invalid segment register")
}
},
x86_op_type::X86_OP_IMM => {
Ok(expr_const(operand.imm() as u64, operand.size as usize * 8))
}
x86_op_type::X86_OP_FP => Err("Unhandled operand".into()),
}
}
/// Gets the value of an operand as an IL expression, performing any required loads as needed.
pub fn operand_load(block: &mut Block, operand: &cs_x86_op) -> Result<Expression> {
let op = try!(operand_value(operand));
if operand.type_ == x86_op_type::X86_OP_MEM {
let temp = block.temp(operand.size as usize * 8);
block.load(temp.clone(), op, array("mem", MEM_SIZE));
return Ok(temp.into());
}
Ok(op)
}
/// Stores a value in an operand, performing any stores as necessary.
pub fn operand_store(mut block: &mut Block, operand: &cs_x86_op, value: Expression) -> Result<()> {
match operand.type_ {
x86_op_type::X86_OP_INVALID => Err("operand_store called on invalid operand".into()),
x86_op_type::X86_OP_IMM => Err("operand_store called on immediate operand".into()),
x86_op_type::X86_OP_REG => {
let dst_register = get_register(*operand.reg())?;
dst_register.set(&mut block, value)
},
x86_op_type::X86_OP_MEM => {
let address = operand_value(operand)?;
block.store(array("mem", MEM_SIZE), address, value);
Ok(())
},
x86_op_type::X86_OP_FP => {
Err("operand_store called on fp operand".into())
}
}
}
/// Convenience function to pop a value off the stack
pub fn pop_value(block: &mut Block, bits: usize) -> Result<Expression> {
let temp = block.temp(bits);
block.load(temp.clone(), expr_scalar("esp", 32), array("mem", MEM_SIZE));
block.assign(scalar("esp", 32), Expr::add(expr_scalar("esp", 32), expr_const(bits as u64 / 8, 32))?);
Ok(temp.into())
}
/// Convenience function to push a value onto the stack
pub fn push_value(block: &mut Block, value: Expression) -> Result<()> {
block.assign(scalar("esp", 32), Expr::sub(expr_scalar("esp", 32), expr_const(4, 32))?);
block.store(array("mem", MEM_SIZE), expr_scalar("esp", 32), value);
Ok(())
}
/// Convenience function set set the zf based on result
pub fn set_zf(block: &mut Block, result: Expression) -> Result<()> {
let expr = Expr::cmpeq(result.clone(), expr_const(0, result.bits()))?;
block.assign(scalar("ZF", 1), expr);
Ok(())
}
/// Convenience function to set the sf based on result
pub fn set_sf(block: &mut Block, result: Expression) -> Result<()> {
let expr = Expr::shr(result.clone(), expr_const((result.bits() - 1) as u64, result.bits()))?;
let expr = Expr::trun(1, expr)?;
block.assign(scalar("SF", 1), expr);
Ok(())
}
/// Convenience function to set the of based on result and both operands
pub fn set_of(block: &mut Block, result: Expression, lhs: Expression, rhs: Expression) -> Result<()> {
let expr0 = Expr::xor(lhs.clone().into(), rhs.clone().into())?;
let expr1 = Expr::xor(lhs.clone().into(), result.clone().into())?;
let expr = Expr::and(expr0, expr1)?;
let expr = Expr::shr(expr.clone(), expr_const((expr.bits() - 1) as u64, expr.bits()))?;
block.assign(scalar("OF", 1), Expr::trun(1, expr)?);
Ok(())
}
/// Convenience function to set the cf based on result and lhs operand
pub fn set_cf(block: &mut Block, result: Expression, lhs: Expression) -> Result<()> {
let expr = Expr::cmpltu(lhs.clone().into(), result.clone().into())?;
block.assign(scalar("CF", 1), expr);
Ok(())
}
/// Returns a condition which is true if a conditional instruction should be
/// executed. Used for setcc, jcc and cmovcc.
pub fn cc_condition(instruction: &capstone::Instr) -> Result<Expression> {
if let capstone::InstrIdArch::X86(instruction_id) = instruction.id {
match instruction_id {
capstone::x86_insn::X86_INS_CMOVA |
capstone::x86_insn::X86_INS_JA |
capstone::x86_insn::X86_INS_SETA => {
let cf = Expr::cmpeq(expr_scalar("CF", 1), expr_const(0, 1))?;
let zf = Expr::cmpeq(expr_scalar("ZF", 1), expr_const(0, 1))?;
Expr::and(cf, zf)
},
capstone::x86_insn::X86_INS_CMOVAE |
capstone::x86_insn::X86_INS_JAE |
capstone::x86_insn::X86_INS_SETAE =>
Expr::cmpeq(expr_scalar("CF", 1), expr_const(0, 1)),
capstone::x86_insn::X86_INS_CMOVB |
capstone::x86_insn::X86_INS_JB |
capstone::x86_insn::X86_INS_SETB =>
Expr::cmpeq(expr_scalar("CF", 1), expr_const(1, 1)),
capstone::x86_insn::X86_INS_CMOVBE |
capstone::x86_insn::X86_INS_JBE |
capstone::x86_insn::X86_INS_SETBE => {
let cf = Expr::cmpeq(expr_scalar("CF", 1), expr_const(1, 1))?;
let zf = Expr::cmpeq(expr_scalar("ZF", 1), expr_const(1, 1))?;
Expr::or(cf, zf)
},
capstone::x86_insn::X86_INS_JCXZ => {
let cx = get_register(x86_reg::X86_REG_CX)?.get()?;
Expr::cmpeq(cx, expr_const(0, 16))
},
capstone::x86_insn::X86_INS_JECXZ => {
let cx = get_register(x86_reg::X86_REG_ECX)?.get()?;
Expr::cmpeq(cx, expr_const(0, 32))
},
capstone::x86_insn::X86_INS_CMOVE |
capstone::x86_insn::X86_INS_JE |
capstone::x86_insn::X86_INS_SETE =>
Expr::cmpeq(expr_scalar("ZF", 1), expr_const(1, 1)),
capstone::x86_insn::X86_INS_CMOVG |
capstone::x86_insn::X86_INS_JG |
capstone::x86_insn::X86_INS_SETG => {
let sfof = Expr::cmpeq(expr_scalar("SF", 1), expr_scalar("OF", 1))?;
let zf = Expr::cmpeq(expr_scalar("ZF", 1), expr_const(0, 1))?;
Expr::and(sfof, zf)
},
capstone::x86_insn::X86_INS_CMOVGE |
capstone::x86_insn::X86_INS_JGE |
capstone::x86_insn::X86_INS_SETGE =>
Expr::cmpeq(expr_scalar("SF", 1), expr_scalar("OF", 1)),
capstone::x86_insn::X86_INS_CMOVL |
capstone::x86_insn::X86_INS_JL |
capstone::x86_insn::X86_INS_SETL =>
Expr::cmpneq(expr_scalar("SF", 1), expr_scalar("OF", 1)),
capstone::x86_insn::X86_INS_CMOVLE |
capstone::x86_insn::X86_INS_JLE |
capstone::x86_insn::X86_INS_SETLE => {
let sfof = Expr::cmpneq(expr_scalar("SF", 1), expr_scalar("OF", 1))?;
let zf = Expr::cmpeq(expr_scalar("ZF", 1), expr_const(1, 1))?;
Expr::and(sfof, zf)
},
capstone::x86_insn::X86_INS_CMOVNE |
capstone::x86_insn::X86_INS_JNE |
capstone::x86_insn::X86_INS_SETNE =>
Expr::cmpeq(expr_scalar("ZF", 1), expr_const(0, 1)),
capstone::x86_insn::X86_INS_CMOVNO |
capstone::x86_insn::X86_INS_JNO |
capstone::x86_insn::X86_INS_SETNO =>
Expr::cmpeq(expr_scalar("OF", 1), expr_const(0, 1)),
capstone::x86_insn::X86_INS_CMOVNP |
capstone::x86_insn::X86_INS_JNP |
capstone::x86_insn::X86_INS_SETNP =>
Expr::cmpeq(expr_scalar("PF", 1), expr_const(0, 1)),
capstone::x86_insn::X86_INS_CMOVNS |
capstone::x86_insn::X86_INS_JNS |
capstone::x86_insn::X86_INS_SETNS =>
Expr::cmpeq(expr_scalar("SF", 1), expr_const(0, 1)),
capstone::x86_insn::X86_INS_CMOVO |
capstone::x86_insn::X86_INS_JO |
capstone::x86_insn::X86_INS_SETO =>
Expr::cmpeq(expr_scalar("OF", 1), expr_const(1, 1)),
capstone::x86_insn::X86_INS_CMOVP |
capstone::x86_insn::X86_INS_JP |
capstone::x86_insn::X86_INS_SETP =>
Expr::cmpeq(expr_scalar("PF", 1), expr_const(1, 1)),
capstone::x86_insn::X86_INS_CMOVS |
capstone::x86_insn::X86_INS_JS |
capstone::x86_insn::X86_INS_SETS =>
Expr::cmpeq(expr_scalar("SF", 1), expr_const(1, 1)),
_ => bail!("unhandled jcc")
}
}
else {
bail!("not an x86 instruction")
}
}
/// Returns a condition which is true if a loop should be taken
pub fn loop_condition(instruction: &capstone::Instr) -> Result<Expression> {
let ecx = scalar("ecx", 32);
if let capstone::InstrIdArch::X86(instruction_id) = instruction.id {
match instruction_id {
capstone::x86_insn::X86_INS_LOOP =>
Expr::cmpneq(ecx.clone().into(), expr_const(0, ecx.bits())),
capstone::x86_insn::X86_INS_LOOPE => {
let expr = Expr::cmpneq(ecx.clone().into(), expr_const(0, ecx.bits()))?;
Expr::and(expr, Expr::cmpeq(expr_scalar("ZF", 1), expr_const(1, 1))?)
}
capstone::x86_insn::X86_INS_LOOPNE => {
let expr = Expr::cmpneq(ecx.clone().into(), expr_const(0, ecx.bits()))?;
Expr::and(expr, Expr::cmpeq(expr_scalar("ZF", 1), expr_const(0, 1))?)
}
_ => bail!("unhandled loop")
}
}
else {
bail!("not an x86 instruction")
}
}
/// Wraps the given instruction graph with the rep prefix inplace
pub fn rep_prefix(
control_flow_graph: &mut ControlFlowGraph,
instruction: &capstone::Instr
) -> Result<()> {
if control_flow_graph.entry().is_none() || control_flow_graph.exit().is_none() {
bail!("control_flow_graph entry/exit was none");
}
let head_index = control_flow_graph.new_block()?.index();
let loop_index = {
let mut loop_block = control_flow_graph.new_block()?;
loop_block.assign(
scalar("ecx", 32),
Expr::sub(expr_scalar("ecx", 32), expr_const(1, 32))?
);
loop_block.index()
};
let terminating_index = control_flow_graph.new_block()?.index();
let entry = control_flow_graph.entry().clone().unwrap();
let exit = control_flow_graph.exit().clone().unwrap();
// head -> entry
// head -> terminating
control_flow_graph.conditional_edge(
head_index,
entry,
Expr::cmpneq(expr_scalar("ecx", 32), expr_const(0, 32))?
)?;
control_flow_graph.conditional_edge(
head_index,
terminating_index,
Expr::cmpeq(expr_scalar("ecx", 32), expr_const(0, 32))?
)?;
// exit -> loop
control_flow_graph.unconditional_edge(exit, loop_index)?;
if let capstone::InstrIdArch::X86(instruction_id) = instruction.id {
match instruction_id {
capstone::x86_insn::X86_INS_CMPSB |
capstone::x86_insn::X86_INS_CMPSW |
capstone::x86_insn::X86_INS_CMPSD |
capstone::x86_insn::X86_INS_SCASB |
capstone::x86_insn::X86_INS_SCASW |
capstone::x86_insn::X86_INS_SCASD => {
// loop -> head
control_flow_graph.conditional_edge(
loop_index,
head_index,
Expr::cmpneq(expr_scalar("ZF", 1), expr_const(0, 1))?
)?;
// loop -> terminating
control_flow_graph.conditional_edge(
loop_index,
terminating_index,
Expr::cmpneq(expr_scalar("ZF", 1), expr_const(1, 1))?
)?;
},
capstone::x86_insn::X86_INS_STOSB |
capstone::x86_insn::X86_INS_STOSW |
capstone::x86_insn::X86_INS_STOSD |
capstone::x86_insn::X86_INS_MOVSB |
capstone::x86_insn::X86_INS_MOVSW |
capstone::x86_insn::X86_INS_MOVSD => {
// loop -> head
control_flow_graph.unconditional_edge(loop_index, head_index)?;
},
_ => bail!("unsupported instruction for rep prefix, 0x{:x}", instruction.address)
}
}
control_flow_graph.set_entry(head_index)?;
control_flow_graph.set_exit(terminating_index)?;
Ok(())
}
pub fn adc(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
// create a block for this instruction
let block_index = {
let mut block = control_flow_graph.new_block()?;
// get operands
let lhs = operand_load(&mut block, &detail.operands[0])?;
let rhs = operand_load(&mut block, &detail.operands[1])?;
let result = block.temp(lhs.bits());
// perform addition
let addition = Expr::add(lhs.clone(), rhs.clone())?;
let zext_cf = Expr::zext(lhs.bits(), expr_scalar("CF", 1))?;
block.assign(result.clone(), Expr::add(addition, zext_cf)?);
// calculate flags
set_zf(&mut block, result.clone().into())?;
set_sf(&mut block, result.clone().into())?;
set_of(&mut block, result.clone().into(), lhs.clone(), rhs.clone())?;
set_cf(&mut block, result.clone().into(), lhs.clone())?;
// store result
operand_store(&mut block, &detail.operands[0], result.into())?;
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn add(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let block_index = {
let mut block = control_flow_graph.new_block()?;
// get operands
let lhs = operand_load(&mut block, &detail.operands[0])?;
let rhs = operand_load(&mut block, &detail.operands[1])?;
let result = block.temp(lhs.bits());
// perform addition
block.assign(result.clone(), Expr::add(lhs.clone(), rhs.clone())?);
// calculate flags
set_zf(&mut block, result.clone().into())?;
set_sf(&mut block, result.clone().into())?;
set_of(&mut block, result.clone().into(), lhs.clone(), rhs.clone())?;
set_cf(&mut block, result.clone().into(), lhs.clone())?;
// store result
operand_store(&mut block, &detail.operands[0], result.into())?;
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn and(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let block_index = {
let mut block = control_flow_graph.new_block()?;
// get operands
let lhs = operand_load(&mut block, &detail.operands[0])?;
let mut rhs = operand_load(&mut block, &detail.operands[1])?;
if rhs.bits() != lhs.bits() {
rhs = Expr::sext(lhs.bits(), rhs)?;
}
let result = block.temp(lhs.bits());
// perform addition
block.assign(result.clone(), Expr::and(lhs.clone(), rhs.clone())?);
// calculate flags
set_zf(&mut block, result.clone().into())?;
set_sf(&mut block, result.clone().into())?;
block.assign(scalar("CF", 1), expr_const(0, 1));
block.assign(scalar("OF", 1), expr_const(0, 1));
// store result
operand_store(&mut block, &detail.operands[0], result.into())?;
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn bswap(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let block_index = {
let mut block = control_flow_graph.new_block()?;
// get operands
let src = operand_load(&mut block, &detail.operands[0])?;
if src.bits() != 32 {
bail!("Invalid bit-width for bswap arg {} at 0x{:x}", src, instruction.address);
}
let expr = Expr::or(
Expr::or(
Expr::and(Expr::shl(src.clone(), expr_const(24, 32))?, expr_const(0xff00_0000, 32))?,
Expr::and(Expr::shl(src.clone(), expr_const(8, 32))?, expr_const(0x00ff_0000, 32))?
)?,
Expr::or(
Expr::and(Expr::shr(src.clone(), expr_const(8, 32))?, expr_const(0x0000_ff00, 32))?,
Expr::and(Expr::shr(src, expr_const(24, 32))?, expr_const(0x0000_00ff, 32))?
)?
)?;
operand_store(&mut block, &detail.operands[0], expr)?;
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
/*
BSF scans the bits in the second word or doubleword operand starting with
bit 0. The ZF flag is cleared if the bits are all 0; otherwise, the ZF flag
is set and the destination register is loaded with the bit index of the
first set bit.
*/
pub fn bsf(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
// create our head block
let (head_index, rhs, counter) = {
let (head_index, rhs) = {
let mut head_block = control_flow_graph.new_block()?;
// get started
let rhs = operand_load(&mut head_block, &detail.operands[1])?;
(head_block.index(), rhs)
};
let counter = {
control_flow_graph.temp(rhs.bits())
};
let mut head_block = control_flow_graph.block_mut(head_index)
.ok_or("Could not find block")?;
// This is the loop preamble, and we'll always execute it
head_block.assign(scalar("ZF", 1), expr_const(0, 1));
head_block.assign(counter.clone(), expr_const(0, rhs.bits()));
(head_index, rhs, counter)
};
// if rhs == 0 then ZF = 1 and we are done.
let zero_index = {
let mut zero_block = control_flow_graph.new_block()?;
zero_block.assign(scalar("ZF", 1), expr_const(1, 1));
zero_block.index()
};
// The loop body checks if the bits for our counter is set.
let (bitfield, loop_index) = {
let bitfield = control_flow_graph.temp(rhs.bits());
let mut loop_block = control_flow_graph.new_block()?;
loop_block.assign(bitfield.clone(),
Expr::and(
Expr::shr(rhs.clone(), counter.clone().into())?,
expr_const(1, rhs.bits())
)?
);
(bitfield, loop_block.index())
};
// While our bitfield == 0, we increment counter and keep looping
let iterate_index = {
let mut iterate_block = control_flow_graph.new_block()?;
iterate_block.assign(counter.clone(), Expr::add(counter.clone().into(), expr_const(1, counter.bits()))?);
iterate_block.index()
};
// In our terminating block, we set the result to counter
let terminating_index = {
let mut terminating_block = control_flow_graph.new_block()?;
operand_store(&mut terminating_block, &detail.operands[0], counter.into())?;
terminating_block.index()
};
control_flow_graph.conditional_edge(
head_index,
zero_index,
Expr::cmpeq(rhs.clone(), expr_const(0, rhs.bits()))?
)?;
control_flow_graph.conditional_edge(
head_index,
loop_index,
Expr::cmpneq(rhs.clone(), expr_const(0, rhs.bits()))?
)?;
control_flow_graph.unconditional_edge(zero_index, terminating_index)?;
control_flow_graph.conditional_edge(
loop_index,
iterate_index,
Expr::cmpeq(bitfield.clone().into(), expr_const(0, bitfield.bits()))?
)?;
control_flow_graph.conditional_edge(
loop_index,
terminating_index,
Expr::cmpneq(bitfield.clone().into(), expr_const(0, bitfield.bits()))?
)?;
control_flow_graph.unconditional_edge(iterate_index, loop_index)?;
control_flow_graph.set_entry(head_index)?;
control_flow_graph.set_exit(terminating_index)?;
Ok(())
}
/*
BSR scans the bits in the second word or doubleword operand from the most
significant bit to the least significant bit. The ZF flag is cleared if the
bits are all 0; otherwise, ZF is set and the destination register is loaded
with the bit index of the first set bit found when scanning in the reverse
direction.
*/
pub fn bsr(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let (head_index, rhs, counter) = {
let (head_index, rhs) = {
let mut head_block = control_flow_graph.new_block()?;
// get started
let rhs = operand_load(&mut head_block, &detail.operands[1])?;
(head_block.index(), rhs)
};
let counter = {
control_flow_graph.temp(rhs.bits())
};
let mut head_block = control_flow_graph.block_mut(head_index)
.ok_or("Could not find block")?;
// This is the loop preamble, and we'll always execute it
head_block.assign(scalar("ZF", 1), expr_const(0, 1));
head_block.assign(counter.clone(), expr_const((rhs.bits() - 1) as u64, rhs.bits()));
(head_index, rhs, counter)
};
// if rhs == 0 then ZF = 1 and we are done.
let zero_index = {
let mut zero_block = control_flow_graph.new_block()?;
zero_block.assign(scalar("ZF", 1), expr_const(1, 1));
zero_block.index()
};
// The loop body checks if the bits for our counter is set
let (bitfield, loop_index) = {
let bitfield = control_flow_graph.temp(rhs.bits());
let mut loop_block = control_flow_graph.new_block()?;
loop_block.assign(bitfield.clone(),
Expr::and(
Expr::shr(rhs.clone(), counter.clone().into())?,
expr_const(1, rhs.bits())
)?
);
(bitfield, loop_block.index())
};
// While our bitfield == 0, we decrement counter and keep looping
let iterate_index = {
let mut iterate_block = control_flow_graph.new_block()?;
iterate_block.assign(counter.clone(), Expr::sub(counter.clone().into(), expr_const(1, counter.bits()))?);
iterate_block.index()
};
// In our terminating block, we set the result to counter
let terminating_index = {
let mut terminating_block = control_flow_graph.new_block()?;
operand_store(&mut terminating_block, &detail.operands[0], counter.into())?;
terminating_block.index()
};
control_flow_graph.conditional_edge(
head_index,
zero_index,
Expr::cmpeq(rhs.clone(), expr_const(0, rhs.bits()))?
)?;
control_flow_graph.conditional_edge(
head_index,
loop_index,
Expr::cmpneq(rhs.clone(), expr_const(0, rhs.bits()))?
)?;
control_flow_graph.unconditional_edge(zero_index, terminating_index)?;
control_flow_graph.conditional_edge(
loop_index,
iterate_index,
Expr::cmpeq(bitfield.clone().into(), expr_const(0, bitfield.bits()))?
)?;
control_flow_graph.conditional_edge(
loop_index,
terminating_index,
Expr::cmpneq(bitfield.clone().into(), expr_const(0, bitfield.bits()))?
)?;
control_flow_graph.unconditional_edge(iterate_index, loop_index)?;
control_flow_graph.set_entry(head_index)?;
control_flow_graph.set_exit(terminating_index)?;
Ok(())
}
/*
BT saves the value of the bit indicated by the base (first operand) and the
bit offset (second operand) into the carry flag.
CF ← BIT[LeftSRC, RightSRC];
0F A3 BT r/m16,r16 3/12 Save bit in carry flag
0F A3 BT r/m32,r32 3/12 Save bit in carry flag
0F BA /4 ib BT r/m16,imm8 3/6 Save bit in carry flag
0F BA /4 ib BT r/m32,imm8 3/6 Save bit in carry flag
*/
pub fn bt(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
// create our head block
let block_index = {
let mut block = control_flow_graph.new_block()?;
// get started
let base = operand_load(&mut block, &detail.operands[0])?;
let mut offset = operand_load(&mut block, &detail.operands[1])?;
// let's ensure we have equal sorts
if offset.bits() != base.bits() {
let temp = block.temp(base.bits());
block.assign(temp.clone(), Expr::zext(base.bits(), offset.clone().into())?);
offset = temp.into();
}
let temp = block.temp(base.bits());
block.assign(temp.clone(), Expr::shr(base.into(), offset.into())?);
block.assign(scalar("CF", 1), Expr::trun(1, temp.into())?);
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
/*
BTC saves the value of the bit indicated by the base (first operand) and the
bit offset (second operand) into the carry flag and then complements the
bit.
CF ← BIT[LeftSRC, RightSRC];
BIT[LeftSRC, RightSRC] ← NOT BIT[LeftSRC, RightSRC];
0F BB BTC r/m16,r16 6/13 Save bit in carry flag and complement
0F BB BTC r/m32,r32 6/13 Save bit in carry flag and complement
0F BA /7 ib BTC r/m16,imm8 6/8 Save bit in carry flag and complement
0F BA /7 ib BTC r/m32,imm8 6/8 Save bit in carry flag and complement
*/
pub fn btc(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
// create our head block
let block_index = {
let mut block = control_flow_graph.new_block()?;
// get started
let base = operand_load(&mut block, &detail.operands[0])?;
let mut offset = operand_load(&mut block, &detail.operands[1])?;
// let's ensure we have equal sorts
if offset.bits() != base.bits() {
let temp = block.temp(base.bits());
block.assign(temp.clone(), Expr::zext(base.bits(), offset.clone().into())?);
offset = temp.into();
}
// this handles the assign to CF
let temp = block.temp(base.bits());
block.assign(temp.clone(), Expr::shr(base.into(), offset.clone().into())?);
block.assign(scalar("CF", 1), Expr::trun(1, temp.clone().into())?);
let expr = Expr::xor(temp.clone().into(), expr_const(1, temp.clone().bits()))?;
let expr = Expr::shl(expr, offset.into())?;
operand_store(&mut block, &detail.operands[0], expr)?;
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
/*
BTR saves the value of the bit indicated by the base (first operand) and the
bit offset (second operand) into the carry flag and then stores 0 in the
bit.
CF ← BIT[LeftSRC, RightSRC];
BIT[LeftSRC, RightSRC] ← 0;
0F B3 BTR r/m16,r16 6/13 Save bit in carry flag and reset
0F B3 BTR r/m32,r32 6/13 Save bit in carry flag and reset
0F BA /6 ib BTR r/m16,imm8 6/8 Save bit in carry flag and reset
0F BA /6 ib BTR r/m32,imm8 6/8 Save bit in carry flag and reset
*/
pub fn btr(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
// create our head block
let block_index = {
let mut block = control_flow_graph.new_block()?;
// get started
let base = operand_load(&mut block, &detail.operands[0])?;
let mut offset = operand_load(&mut block, &detail.operands[1])?;
// let's ensure we have equal sorts
if offset.bits() != base.bits() {
let temp = block.temp(base.bits());
block.assign(temp.clone(), Expr::zext(base.bits(), offset.clone().into())?);
offset = temp.into();
}
// this handles the assign to CF
let temp = block.temp(base.bits());
block.assign(temp.clone(), Expr::shr(base.clone().into(), offset.clone().into())?);
block.assign(scalar("CF", 1), Expr::trun(1, temp.clone().into())?);
let expr = Expr::shl(expr_const(1, base.bits()), offset.into())?;
let expr = Expr::xor(expr, expr_const(0xffff_ffff_ffff_ffff, base.bits()))?;
let expr = Expr::and(base.into(), expr)?;
operand_store(&mut block, &detail.operands[0], expr)?;
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
/*
BTS saves the value of the bit indicated by the base (first operand) and the
bit offset (second operand) into the carry flag and then stores 1 in the
bit.
CF ← BIT[LeftSRC, RightSRC];
BIT[LeftSRC, RightSRC] ← 1;
0F AB BTS r/m16,r16 6/13 Save bit in carry flag and set
0F AB BTS r/m32,r32 6/13 Save bit in carry flag and set
0F BA /5 ib BTS r/m16,imm8 6/8 Save bit in carry flag and set
0F BA /5 ib BTS r/m32,imm8 6/8 Save bit in carry flag and set
*/
pub fn bts(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
// create our head block
let block_index = {
let mut block = control_flow_graph.new_block()?;
// get started
let base = operand_load(&mut block, &detail.operands[0])?;
let mut offset = operand_load(&mut block, &detail.operands[1])?;
// let's ensure we have equal sorts
if offset.bits() != base.bits() {
let temp = block.temp(base.bits());
block.assign(temp.clone(), Expr::zext(base.bits(), offset.clone().into())?);
offset = temp.into();
}
// this handles the assign to CF
let temp = block.temp(base.bits());
block.assign(temp.clone(), Expr::shr(base.clone().into(), offset.clone().into())?);
block.assign(scalar("CF", 1), Expr::trun(1, temp.clone().into())?);
let expr = Expr::shl(expr_const(1, base.bits()), offset.into())?;
let expr = Expr::or(base.into(), expr)?;
operand_store(&mut block, &detail.operands[0], expr)?;
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn call(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let block_index = {
let mut block = control_flow_graph.new_block()?;
// get started
let dst = operand_load(&mut block, &detail.operands[0])?;
let ret_addr = instruction.address + instruction.size as u64;
push_value(&mut block, expr_const(ret_addr, 32))?;
block.brc(dst, expr_const(1, 1));
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn cbw(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let block_index = {
let mut block = control_flow_graph.new_block()?;
let dst = operand_load(&mut block, &detail.operands[0])?;
let src = operand_load(&mut block, &detail.operands[1])?;
let expr = Expr::sext(dst.bits(), src.into())?;
operand_store(&mut block, &detail.operands[0], expr)?;
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn cdq(control_flow_graph: &mut ControlFlowGraph, _: &capstone::Instr) -> Result<()> {
let block_index = {
let mut block = control_flow_graph.new_block()?;
// isolate the sign bits of ax
let expr = Expr::shr(expr_scalar("eax", 32), expr_const(31, 32))?;
let expr = Expr::trun(1, expr)?;
let expr = Expr::sext(32, expr)?;
block.assign(scalar("edx", 32), expr);
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn clc(control_flow_graph: &mut ControlFlowGraph, _: &capstone::Instr) -> Result<()> {
let block_index = {
let mut block = control_flow_graph.new_block()?;
block.assign(scalar("CF", 1), expr_const(0, 1));
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn cld(control_flow_graph: &mut ControlFlowGraph, _: &capstone::Instr) -> Result<()> {
let block_index = {
let mut block = control_flow_graph.new_block()?;
block.assign(scalar("DF", 1), expr_const(0, 1));
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn cli(control_flow_graph: &mut ControlFlowGraph, _: &capstone::Instr) -> Result<()> {
let block_index = {
let mut block = control_flow_graph.new_block()?;
block.assign(scalar("IF", 1), expr_const(0, 1));
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn cmc(control_flow_graph: &mut ControlFlowGraph, _: &capstone::Instr) -> Result<()> {
let block_index = {
let mut block = control_flow_graph.new_block()?;
let expr = Expr::xor(expr_scalar("CF", 1), expr_const(1, 1))?;
block.assign(scalar("CF", 1), expr);
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn cmovcc(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let head_index = {
let block = control_flow_graph.new_block()?;
block.index()
};
let tail_index = {
let block = control_flow_graph.new_block()?;
block.index()
};
let block_index = {
let mut block = control_flow_graph.new_block()?;
let src = operand_load(&mut block, &detail.operands[1])?;
operand_store(&mut block, &detail.operands[0], src)?;
block.index()
};
let condition = cc_condition(&instruction)?;
control_flow_graph.conditional_edge(head_index, block_index, condition.clone())?;
control_flow_graph.conditional_edge(
head_index,
tail_index,
Expr::cmpeq(condition, expr_const(0, 1))?
)?;
control_flow_graph.unconditional_edge(block_index, tail_index)?;
control_flow_graph.set_entry(head_index)?;
control_flow_graph.set_exit(tail_index)?;
Ok(())
}
pub fn cmp(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let block_index = {
let mut block = control_flow_graph.new_block()?;
let lhs = operand_load(&mut block, &detail.operands[0])?;
let mut rhs = operand_load(&mut block, &detail.operands[1])?;
if rhs.bits() != lhs.bits() {
rhs = Expr::sext(lhs.bits(), rhs.into())?;
}
let expr = Expr::sub(lhs.clone(), rhs.clone())?;
set_zf(&mut block, expr.clone())?;
set_sf(&mut block, expr.clone())?;
set_of(&mut block, expr.clone(), lhs.clone(), rhs.clone())?;
set_cf(&mut block, expr.clone(), lhs.clone())?;
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn cmpsb(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let head_index = {
let mut block = control_flow_graph.new_block()?;
let lhs = operand_load(&mut block, &detail.operands[0])?;
let mut rhs = operand_load(&mut block, &detail.operands[1])?;
if rhs.bits() != lhs.bits() {
rhs = Expr::sext(lhs.bits(), rhs.into())?;
}
let expr = Expr::sub(lhs.clone(), rhs.clone())?;
set_zf(&mut block, expr.clone())?;
set_sf(&mut block, expr.clone())?;
set_of(&mut block, expr.clone(), lhs.clone(), rhs.clone())?;
set_cf(&mut block, expr.clone(), lhs.clone())?;
block.index()
};
let inc_index = {
let mut block = control_flow_graph.new_block()?;
block.assign(
scalar("esi", 32),
Expr::add(expr_scalar("esi", 32), expr_const(1, 32))?
);
block.assign(
scalar("edi", 32),
Expr::add(expr_scalar("edi", 32), expr_const(1, 32))?
);
block.index()
};
let dec_index = {
let mut block = control_flow_graph.new_block()?;
block.assign(
scalar("esi", 32),
Expr::sub(expr_scalar("esi", 32), expr_const(1, 32))?
);
block.assign(
scalar("edi", 32),
Expr::sub(expr_scalar("edi", 32), expr_const(1, 32))?
);
block.index()
};
let tail_index = {
control_flow_graph.new_block()?.index()
};
control_flow_graph.conditional_edge(
head_index,
inc_index,
Expr::cmpeq(expr_scalar("DF", 1), expr_const(0, 1))?
)?;
control_flow_graph.conditional_edge(
head_index,
dec_index,
Expr::cmpeq(expr_scalar("DF", 1), expr_const(1, 1))?
)?;
control_flow_graph.unconditional_edge(inc_index, tail_index)?;
control_flow_graph.unconditional_edge(dec_index, tail_index)?;
control_flow_graph.set_entry(head_index)?;
control_flow_graph.set_exit(tail_index)?;
Ok(())
}
pub fn cmpxchg(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let (head_index, dest, lhs, rhs) = {
let mut block = control_flow_graph.new_block()?;
let lhs = operand_load(&mut block, &detail.operands[0])?;
let rhs = operand_load(&mut block, &detail.operands[1])?;
let dest = match rhs.bits() {
8 => get_register(x86_reg::X86_REG_AL)?,
16 => get_register(x86_reg::X86_REG_AX)?,
32 => get_register(x86_reg::X86_REG_EAX)?,
_ => bail!("can't figure out dest for xmpxchg, rhs.bits()={}", rhs.bits())
};
(block.index(), dest, lhs, rhs)
};
let taken_index = {
let mut block = control_flow_graph.new_block()?;
block.assign(scalar("ZF", 1), expr_const(1, 1));
operand_store(&mut block, &detail.operands[0], rhs.clone())?;
block.index()
};
let not_taken_index = {
let mut block = control_flow_graph.new_block()?;
block.assign(scalar("ZF", 1), expr_const(0, 1));
dest.set(&mut block, lhs.clone())?;
block.index()
};
let tail_index = {
let mut block = control_flow_graph.new_block()?;
let result = Expr::sub(lhs.clone(), rhs.clone())?;
set_sf(&mut block, result.clone())?;
set_of(&mut block, result.clone(), lhs.clone(), rhs.clone())?;
set_cf(&mut block, result.clone(), lhs.clone())?;
block.index()
};
let condition = Expr::cmpeq(dest.get()?, lhs.clone())?;
control_flow_graph.conditional_edge(head_index, taken_index, condition.clone())?;
control_flow_graph.conditional_edge(
head_index,
not_taken_index,
Expr::cmpeq(condition.clone(), expr_const(0, 1))?
)?;
control_flow_graph.unconditional_edge(taken_index, tail_index)?;
control_flow_graph.unconditional_edge(not_taken_index, tail_index)?;
control_flow_graph.set_entry(head_index)?;
control_flow_graph.set_exit(tail_index)?;
Ok(())
}
pub fn cwd(control_flow_graph: &mut ControlFlowGraph, _: &capstone::Instr) -> Result<()> {
let block_index = {
let mut block = control_flow_graph.new_block()?;
// isolate the sign bits of ax
let expr = Expr::shr(expr_scalar("ax", 16), expr_const(15, 16))?;
let expr = Expr::trun(1, expr)?;
let expr = Expr::sext(16, expr)?;
block.assign(scalar("dx", 16), expr);
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn cwde(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let block_index = {
let mut block = control_flow_graph.new_block()?;
let dst = operand_load(&mut block, &detail.operands[0])?;
let src = operand_load(&mut block, &detail.operands[1])?;
let expr = Expr::sext(dst.bits(), src.into())?;
operand_store(&mut block, &detail.operands[0], expr)?;
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn dec(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let block_index = {
let mut block = control_flow_graph.new_block()?;
let dst = operand_load(&mut block, &detail.operands[0])?;
let expr = Expr::sub(dst.clone().into(), expr_const(1, dst.bits()))?;
set_zf(&mut block, expr.clone())?;
set_sf(&mut block, expr.clone())?;
set_of(&mut block, expr.clone(), dst.clone(), expr_const(1, dst.bits()))?;
set_cf(&mut block, expr.clone(), dst.clone())?;
operand_store(&mut block, &detail.operands[0], expr)?;
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn div(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let block_index = {
let mut block = control_flow_graph.new_block()?;
let divisor = operand_load(&mut block, &detail.operands[0])?;
let divisor = Expr::zext(divisor.bits() * 2, divisor)?;
let dividend: Expr = match divisor.bits() {
16 => get_register(x86_reg::X86_REG_AX)?.get()?,
32 => {
let expr_dx = Expr::zext(32, get_register(x86_reg::X86_REG_DX)?.get()?)?;
let expr_dx = Expr::shl(expr_dx, expr_const(16, 32))?;
Expr::or(expr_dx, Expr::zext(32, get_register(x86_reg::X86_REG_AX)?.get()?)?)?
},
64 => {
let expr_edx = Expr::zext(64, get_register(x86_reg::X86_REG_EDX)?.get()?)?;
let expr_edx = Expr::shl(expr_edx, expr_const(32, 64))?;
Expr::or(expr_edx, Expr::zext(64, get_register(x86_reg::X86_REG_EAX)?.get()?)?)?
},
_ => return Err("invalid bit-width in x86 div".into())
};
let quotient = block.temp(divisor.bits());
let remainder = block.temp(divisor.bits());
block.assign(quotient.clone(), Expr::divu(dividend.clone(), divisor.clone())?);
block.assign(remainder.clone(), Expr::modu(dividend, divisor.clone())?);
match divisor.bits() {
16 => {
let al = get_register(x86_reg::X86_REG_AL)?;
let ah = get_register(x86_reg::X86_REG_AH)?;
al.set(&mut block, Expr::trun(8, quotient.into())?)?;
ah.set(&mut block, Expr::trun(8, remainder.into())?)?;
},
32 => {
let ax = get_register(x86_reg::X86_REG_AX)?;
let dx = get_register(x86_reg::X86_REG_DX)?;
ax.set(&mut block, Expr::trun(16, quotient.into())?)?;
dx.set(&mut block, Expr::trun(16, remainder.into())?)?;
},
64 => {
let eax = get_register(x86_reg::X86_REG_EAX)?;
let edx = get_register(x86_reg::X86_REG_EDX)?;
eax.set(&mut block, Expr::trun(32, quotient.into())?)?;
edx.set(&mut block, Expr::trun(32, remainder.into())?)?;
},
_ => return Err("invalid bit-width in x86 div".into())
}
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
// This is essentially the exact same as div with the signs of the arith ops
// reversed.
pub fn idiv(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let block_index = {
let mut block = control_flow_graph.new_block()?;
let divisor = operand_load(&mut block, &detail.operands[0])?;
let divisor = Expr::zext(divisor.bits() * 2, divisor)?;
let dividend: Expr = match divisor.bits() {
16 => get_register(x86_reg::X86_REG_AX)?.get()?,
32 => {
let expr_dx = Expr::zext(32, get_register(x86_reg::X86_REG_DX)?.get()?)?;
let expr_dx = Expr::shl(expr_dx, expr_const(16, 32))?;
Expr::or(expr_dx, Expr::zext(32, get_register(x86_reg::X86_REG_AX)?.get()?)?)?
},
64 => {
let expr_edx = Expr::zext(64, get_register(x86_reg::X86_REG_EDX)?.get()?)?;
let expr_edx = Expr::shl(expr_edx, expr_const(32, 64))?;
Expr::or(expr_edx, Expr::zext(64, get_register(x86_reg::X86_REG_EAX)?.get()?)?)?
},
_ => return Err("invalid bit-width in x86 div".into())
};
let quotient = block.temp(divisor.bits());
let remainder = block.temp(divisor.bits());
block.assign(quotient.clone(), Expr::divs(dividend.clone(), divisor.clone())?);
block.assign(remainder.clone(), Expr::mods(dividend, divisor.clone())?);
match divisor.bits() {
16 => {
let al = get_register(x86_reg::X86_REG_AL)?;
let ah = get_register(x86_reg::X86_REG_AH)?;
al.set(&mut block, Expr::trun(8, quotient.into())?)?;
ah.set(&mut block, Expr::trun(8, remainder.into())?)?;
},
32 => {
let ax = get_register(x86_reg::X86_REG_AX)?;
let dx = get_register(x86_reg::X86_REG_DX)?;
ax.set(&mut block, Expr::trun(16, quotient.into())?)?;
dx.set(&mut block, Expr::trun(16, remainder.into())?)?;
},
64 => {
let eax = get_register(x86_reg::X86_REG_EAX)?;
let edx = get_register(x86_reg::X86_REG_EDX)?;
eax.set(&mut block, Expr::trun(32, quotient.into())?)?;
edx.set(&mut block, Expr::trun(32, remainder.into())?)?;
},
_ => return Err("invalid bit-width in x86 div".into())
}
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
// If we have one operand, we go in AX, DX:AX, EDX:EAX
// If we have two operands, sign-extend rhs if required, go in 0 operand
// If we have three operands, sign-extend rhs if required, go in 0 operand
pub fn imul(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let block_index = {
let mut block = control_flow_graph.new_block()?;
// Get multiplicand
let multiplicand = match detail.op_count {
1 => match detail.operands[0].size {
// AL
1 => get_register(x86_reg::X86_REG_AL)?.get()?,
// AX
2 => get_register(x86_reg::X86_REG_AX)?.get()?,
// EAX
4 => get_register(x86_reg::X86_REG_EAX)?.get()?,
_ => bail!("invalid operand size for imul")
},
2 => operand_load(&mut block, &detail.operands[0])?,
3 => operand_load(&mut block, &detail.operands[1])?,
_ => bail!("invalid number of operands for imul {} at 0x{:x}",
detail.op_count,
instruction.address)
};
// Get multiplier
let multiplier = match detail.op_count {
1 => operand_load(&mut block, &detail.operands[0])?,
2 => {
let multiplier = operand_load(&mut block, &detail.operands[1])?;
if multiplier.bits() < multiplicand.bits() {
Expr::sext(multiplicand.bits(), multiplier)?
}
else {
multiplier
}
},
3 => {
let multiplier = operand_load(&mut block, &detail.operands[2])?;
if multiplier.bits() < multiplicand.bits() {
Expr::sext(multiplicand.bits(), multiplier)?
}
else {
multiplier
}
}
_ => bail!("invalid number of operands for imul")
};
// Perform multiplication
let bit_width = multiplicand.bits() * 2;
let result = block.temp(bit_width);
block.assign(result.clone(), Expr::mul(
Expr::zext(bit_width, multiplicand)?,
Expr::zext(bit_width, multiplier)?
)?);
// Set the result
match detail.op_count {
1 => {
match detail.operands[0].size {
1 => get_register(x86_reg::X86_REG_AX)?.set(&mut block, result.clone().into())?,
2 => {
let dx = get_register(x86_reg::X86_REG_DX)?;
let ax = get_register(x86_reg::X86_REG_AX)?;
let expr = Expr::shr(result.clone().into(), expr_const(16, 32))?;
dx.set(&mut block, Expr::trun(16, expr)?)?;
ax.set(&mut block, Expr::trun(16, result.clone().into())?)?;
},
4 => {
let edx = get_register(x86_reg::X86_REG_EDX)?;
let eax = get_register(x86_reg::X86_REG_EAX)?;
let expr = Expr::shr(result.clone().into(), expr_const(32, 64))?;
edx.set(&mut block, Expr::trun(32, expr)?)?;
eax.set(&mut block, Expr::trun(32, result.clone().into())?)?;
},
_ => bail!("Invalid operand size for imul")
}
},
2 => {
let expr = Expr::trun(bit_width / 2, result.clone().into())?;
operand_store(&mut block, &detail.operands[0], expr)?;
}
3 => {
let expr = Expr::trun(bit_width / 2, result.clone().into())?;
operand_store(&mut block, &detail.operands[0], expr)?;
}
_ => bail!("invalid number of operands for imul")
}
// Set flags
block.assign(scalar("OF", 1),
Expr::cmpneq(
Expr::trun(
bit_width / 2,
Expr::shr(
result.clone().into(),
expr_const((bit_width / 2) as u64, bit_width)
)?
)?,
expr_const(0, bit_width / 2)
)?
);
block.assign(scalar("CF", 1), expr_scalar("OF", 1));
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn inc(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let block_index = {
let mut block = control_flow_graph.new_block()?;
let dst = operand_load(&mut block, &detail.operands[0])?;
let expr = Expr::add(dst.clone().into(), expr_const(1, dst.bits()))?;
set_zf(&mut block, expr.clone())?;
set_sf(&mut block, expr.clone())?;
set_of(&mut block, expr.clone(), dst.clone(), expr_const(1, dst.bits()))?;
set_cf(&mut block, expr.clone(), dst.clone())?;
operand_store(&mut block, &detail.operands[0], expr)?;
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn int(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let block_index = {
let mut block = control_flow_graph.new_block()?;
let expr = operand_load(&mut block, &detail.operands[0])?;
block.raise(expr);
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn jcc(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let block_index = {
let mut block = control_flow_graph.new_block()?;
// we only need to emit a brc here if the destination cannot be determined
// at translation time
if detail.operands[0].type_ != x86_op_type::X86_OP_IMM {
let dst = operand_load(&mut block, &detail.operands[0])?;
let expr = cc_condition(&instruction)?;
block.brc(dst, expr);
}
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn jmp(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let block_index = {
let mut block = control_flow_graph.new_block()?;
// we only need to emit a brc here if the destination cannot be determined
// at translation time
if detail.operands[0].type_ != x86_op_type::X86_OP_IMM {
let dst = operand_load(&mut block, &detail.operands[0])?;
block.brc(dst, expr_const(1, 1));
}
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn lea(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let block_index = {
let mut block = control_flow_graph.new_block()?;
let src = operand_value(&detail.operands[1])?;
operand_store(&mut block, &detail.operands[0], src)?;
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn leave(control_flow_graph: &mut ControlFlowGraph, _: &capstone::Instr) -> Result<()> {
let block_index = {
let mut block = control_flow_graph.new_block()?;
block.assign(scalar("esp", 32), expr_scalar("ebp", 32));
let ebp = pop_value(&mut block, 32)?;
block.assign(scalar("ebp", 32), ebp);
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn lodsb(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let head_index = {
let mut block = control_flow_graph.new_block()?;
let rhs = operand_load(&mut block, &detail.operands[1])?;
get_register(x86_reg::X86_REG_AL)?.set(&mut block, rhs)?;
block.index()
};
let inc_index = {
let mut block = control_flow_graph.new_block()?;
block.assign(
scalar("esi", 32),
Expr::add(expr_scalar("esi", 32), expr_const(1, 32))?
);
block.index()
};
let dec_index = {
let mut block = control_flow_graph.new_block()?;
block.assign(
scalar("esi", 32),
Expr::sub(expr_scalar("esi", 32), expr_const(1, 32))?
);
block.index()
};
let tail_index = {
control_flow_graph.new_block()?.index()
};
control_flow_graph.conditional_edge(
head_index,
inc_index,
Expr::cmpeq(expr_scalar("DF", 1), expr_const(0, 1))?
)?;
control_flow_graph.conditional_edge(
head_index,
dec_index,
Expr::cmpeq(expr_scalar("DF", 1), expr_const(1, 1))?
)?;
control_flow_graph.unconditional_edge(inc_index, tail_index)?;
control_flow_graph.unconditional_edge(dec_index, tail_index)?;
control_flow_graph.set_entry(head_index)?;
control_flow_graph.set_exit(tail_index)?;
Ok(())
}
pub fn loop_(control_flow_graph: &mut ControlFlowGraph, _: &capstone::Instr) -> Result<()> {
let block_index = {
let mut block = control_flow_graph.new_block()?;
let ecx = scalar("ecx", 32);
block.assign(ecx.clone(), Expr::sub(ecx.clone().into(), expr_const(1, ecx.bits()))?);
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn mov(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let block_index = {
let mut block = control_flow_graph.new_block()?;
let src = operand_load(&mut block, &detail.operands[1])?;
operand_store(&mut block, &detail.operands[0], src)?;
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn movs(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let head_index = {
let mut block = control_flow_graph.new_block()?;
let src = operand_load(&mut block, &detail.operands[1])?;
operand_store(&mut block, &detail.operands[0], src.clone())?;
block.assign(
scalar("esi", 32),
Expr::add(expr_scalar("esi", 32), expr_const((src.bits() / 8) as u64, 32))?
);
block.assign(
scalar("edi", 32),
Expr::add(expr_scalar("edi", 32), expr_const((src.bits() / 8) as u64, 32))?
);
block.index()
};
let inc_index = {
let mut block = control_flow_graph.new_block()?;
block.assign(
scalar("esi", 32),
Expr::add(expr_scalar("esi", 32), expr_const(1, 32))?
);
block.index()
};
let dec_index = {
let mut block = control_flow_graph.new_block()?;
block.assign(
scalar("esi", 32),
Expr::sub(expr_scalar("esi", 32), expr_const(1, 32))?
);
block.index()
};
let tail_index = {
control_flow_graph.new_block()?.index()
};
control_flow_graph.conditional_edge(
head_index,
inc_index,
Expr::cmpeq(expr_scalar("DF", 1), expr_const(0, 1))?
)?;
control_flow_graph.conditional_edge(
head_index,
dec_index,
Expr::cmpeq(expr_scalar("DF", 1), expr_const(1, 1))?
)?;
control_flow_graph.unconditional_edge(inc_index, tail_index)?;
control_flow_graph.unconditional_edge(dec_index, tail_index)?;
control_flow_graph.set_entry(head_index)?;
control_flow_graph.set_exit(tail_index)?;
Ok(())
}
pub fn movsx(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let block_index = {
let mut block = control_flow_graph.new_block()?;
let src = operand_load(&mut block, &detail.operands[1])?;
let value = Expr::sext((detail.operands[0].size as usize) * 8, src)?;
operand_store(&mut block, &detail.operands[0], value)?;
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn movzx(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let block_index = {
let mut block = control_flow_graph.new_block()?;
let src = operand_load(&mut block, &detail.operands[1])?;
let value = Expr::zext((detail.operands[0].size as usize) * 8, src)?;
operand_store(&mut block, &detail.operands[0], value)?;
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn mul(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let block_index = {
let mut block = control_flow_graph.new_block()?;
let rhs = operand_load(&mut block, &detail.operands[0])?;
let lhs = match rhs.bits() {
8 => get_register(x86_reg::X86_REG_AL)?.get()?,
16 => get_register(x86_reg::X86_REG_AX)?.get()?,
32 => get_register(x86_reg::X86_REG_EAX)?.get()?,
_ => bail!("invalid bit-width for mul")
};
let bit_width = rhs.bits() * 2;
let result = block.temp(bit_width);
let expr = Expr::mul(Expr::zext(bit_width, lhs)?, Expr::zext(bit_width, rhs.clone())?)?;
block.assign(result.clone(), expr);
match rhs.bits() {
8 => {
let ax = get_register(x86_reg::X86_REG_AX)?;
ax.set(&mut block, result.into())?;
let expr = Expr::cmpeq(get_register(x86_reg::X86_REG_AH)?.get()?, expr_const(0, 8))?;
block.assign(scalar("ZF", 1), expr);
block.assign(scalar("CF", 1), expr_scalar("ZF", 1));
},
16 => {
let dx = get_register(x86_reg::X86_REG_DX)?;
let ax = get_register(x86_reg::X86_REG_AX)?;
dx.set(&mut block, Expr::trun(16, Expr::shr(result.clone().into(), expr_const(16, 32))?)?)?;
ax.set(&mut block, Expr::trun(16, result.into())?)?;
block.assign(scalar("ZF", 1), Expr::cmpeq(dx.get()?, expr_const(0, 16))?);
block.assign(scalar("CF", 1), expr_scalar("ZF", 1));
},
32 => {
let edx = get_register(x86_reg::X86_REG_EDX)?;
let eax = get_register(x86_reg::X86_REG_EAX)?;
edx.set(&mut block, Expr::trun(32, Expr::shr(result.clone().into(), expr_const(32, 64))?)?)?;
eax.set(&mut block, Expr::trun(32, result.into())?)?;
block.assign(scalar("ZF", 1), Expr::cmpeq(edx.get()?, expr_const(0, 32))?);
block.assign(scalar("CF", 1), expr_scalar("ZF", 1));
},
_ => bail!("invalid bit-width for mul")
}
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn neg(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let block_index = {
let mut block = control_flow_graph.new_block()?;
let dst = operand_load(&mut block, &detail.operands[0])?;
let result = block.temp(dst.bits());
block.assign(scalar("CF", 1), Expr::cmpneq(dst.clone().into(), expr_const(0, dst.bits()))?);
block.assign(result.clone(), Expr::sub(expr_const(0, dst.bits()), dst.clone().into())?);
set_zf(&mut block, result.clone().into())?;
set_sf(&mut block, result.clone().into())?;
set_of(&mut block, result.clone().into(), expr_const(0, dst.bits()), dst.clone().into())?;
operand_store(&mut block, &detail.operands[0], result.clone().into())?;
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn nop(control_flow_graph: &mut ControlFlowGraph, _: &capstone::Instr) -> Result<()> {
let block_index = {
control_flow_graph.new_block()?.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn not(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let block_index = {
let mut block = control_flow_graph.new_block()?;
let dst = operand_load(&mut block, &detail.operands[0])?;
let expr = Expr::xor(dst.clone(), expr_const(!0, dst.bits()))?;
operand_store(&mut block, &detail.operands[0], expr)?;
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn or(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let block_index = {
let mut block = control_flow_graph.new_block()?;
// get operands
let lhs = operand_load(&mut block, &detail.operands[0])?;
let mut rhs = operand_load(&mut block, &detail.operands[1])?;
let result = block.temp(lhs.bits());
if lhs.bits() != rhs.bits() {
rhs = Expr::sext(lhs.bits(), rhs)?;
}
// perform addition
block.assign(result.clone(), Expr::or(lhs.clone(), rhs.clone())?);
// calculate flags
set_zf(&mut block, result.clone().into())?;
set_sf(&mut block, result.clone().into())?;
block.assign(scalar("CF", 1), expr_const(0, 1));
block.assign(scalar("OF", 1), expr_const(0, 1));
// store result
operand_store(&mut block, &detail.operands[0], result.into())?;
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn pop(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
// create a block for this instruction
let block_index = {
let mut block = control_flow_graph.new_block()?;
let value = match detail.operands[0].type_ {
x86_op_type::X86_OP_MEM => pop_value(&mut block, detail.operands[0].size as usize * 8)?,
x86_op_type::X86_OP_REG =>
pop_value(&mut block, get_register(*detail.operands[0].reg())?.bits())?,
_ => bail!("invalid op type for `pop` instruction")
};
operand_store(&mut block, &detail.operands[0], value)?;
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn push(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let block_index = {
let mut block = control_flow_graph.new_block()?;
let value = operand_load(&mut block, &detail.operands[0])?;
push_value(&mut block, value)?;
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn ret(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let block_index = {
let mut block = control_flow_graph.new_block()?;
let value = pop_value(&mut block, 32)?;
if detail.op_count == 1 {
let imm = operand_load(&mut block, &detail.operands[0])?;
block.assign(scalar("esp", 32), Expr::add(expr_scalar("esp", 32), imm)?);
}
block.assign(scalar("eip", 32), value);
block.brc(expr_scalar("eip", 32), expr_const(1, 1));
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn rol(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let block_index = {
let mut block = control_flow_graph.new_block()?;
// get operands
let lhs = operand_load(&mut block, &detail.operands[0])?;
let count = operand_load(&mut block, &detail.operands[1])?;
let mut count = Expr::and(count.clone(), expr_const(0x1f, count.bits()))?;
if count.bits() < lhs.bits() {
count = Expr::zext(lhs.bits(), count)?;
}
let shift_left_bits = count;
let shift_right_bits = Expr::sub(
expr_const(lhs.bits() as u64, lhs.bits()),
shift_left_bits.clone()
)?;
let result = Expr::or(
Expr::shl(lhs.clone(), shift_left_bits.clone())?,
Expr::shr(lhs.clone(), shift_right_bits.clone())?
)?;
// CF is the bit sent from one end to the other. In our case, it should be LSB of result
block.assign(scalar("CF", 1), Expr::shr(
result.clone(),
expr_const(result.bits() as u64 - 1, result.bits())
)?);
// OF is XOR of two most-significant bits of result
block.assign(scalar("OF", 1), Expr::xor(
Expr::trun(1, Expr::shr(result.clone(), expr_const(result.bits() as u64 - 1, result.bits()))?)?,
Expr::trun(1, Expr::shr(result.clone(), expr_const(result.bits() as u64 - 2, result.bits()))?)?
)?);
// SF/ZF are unaffected
// store result
operand_store(&mut block, &detail.operands[0], result.into())?;
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn ror(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let block_index = {
let mut block = control_flow_graph.new_block()?;
// get operands
let lhs = operand_load(&mut block, &detail.operands[0])?;
let count = operand_load(&mut block, &detail.operands[1])?;
let mut count = Expr::and(count.clone(), expr_const(0x1f, count.bits()))?;
if count.bits() < lhs.bits() {
count = Expr::zext(lhs.bits(), count)?;
}
let shift_right_bits = count;
let shift_left_bits = Expr::sub(
expr_const(lhs.bits() as u64, lhs.bits()),
shift_right_bits.clone()
)?;
let result = Expr::or(
Expr::shl(lhs.clone(), shift_left_bits.clone())?,
Expr::shr(lhs.clone(), shift_right_bits.clone())?
)?;
// CF is the bit sent from one end to the other. In our case, it should be MSB of result
block.assign(scalar("CF", 1), Expr::shr(
result.clone(),
expr_const(result.bits() as u64 - 1, result.bits())
)?);
// OF is XOR of two most-significant bits of result
block.assign(scalar("OF", 1), Expr::xor(
Expr::trun(1, Expr::shr(result.clone(), expr_const(result.bits() as u64 - 1, result.bits()))?)?,
Expr::trun(1, Expr::shr(result.clone(), expr_const(result.bits() as u64 - 2, result.bits()))?)?
)?);
// SF/ZF are unaffected
// store result
operand_store(&mut block, &detail.operands[0], result.into())?;
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn sar(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let block_index = {
let mut block = control_flow_graph.new_block()?;
// get operands
let lhs = operand_load(&mut block, &detail.operands[0])?;
let mut rhs = operand_load(&mut block, &detail.operands[1])?;
if lhs.bits() != rhs.bits() {
rhs = Expr::zext(lhs.bits(), rhs)?;
}
// Create the mask we apply if that lhs is signed
let mask = Expr::shl(expr_const(1, lhs.bits()), rhs.clone())?;
let mask = Expr::sub(mask, expr_const(1, lhs.bits()))?;
let mask = Expr::shl(mask, Expr::sub(
expr_const(lhs.bits() as u64, lhs.bits()),
rhs.clone())?
)?;
// Multiple the mask by the sign bit
let expr = Expr::shr(lhs.clone(), expr_const(lhs.bits() as u64 - 1, lhs.bits()))?;
let expr = Expr::mul(mask, expr)?;
// Do the SAR
let expr = Expr::or(expr, Expr::shr(lhs.clone(), rhs.clone())?)?;
let temp = block.temp(lhs.bits());
block.assign(temp.clone(), expr);
// OF is the last bit shifted out
block.assign(scalar("OF", 1), expr_const(0, lhs.bits()));
set_zf(&mut block, temp.clone().into())?;
set_sf(&mut block, temp.clone().into())?;
set_cf(&mut block, temp.clone().into(), lhs.clone())?;
operand_store(&mut block, &detail.operands[0], temp.into())?;
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn sbb(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let block_index = {
let mut block = control_flow_graph.new_block()?;
// get operands
let lhs = operand_load(&mut block, &detail.operands[0])?;
let mut rhs = operand_load(&mut block, &detail.operands[1])?;
if lhs.bits() != rhs.bits() {
rhs = Expr::sext(lhs.bits(), rhs)?;
}
let rhs = Expr::add(rhs.clone(), Expr::zext(rhs.bits(), expr_scalar("CF", 1))?)?;
let expr = Expr::sub(lhs.clone(), rhs.clone())?;
// calculate flags
set_zf(&mut block, expr.clone())?;
set_sf(&mut block, expr.clone())?;
set_of(&mut block, expr.clone(), lhs.clone(), rhs.clone())?;
set_cf(&mut block, expr.clone(), lhs.clone())?;
// store result
operand_store(&mut block, &detail.operands[0], expr)?;
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn scasb(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let head_index = {
let mut block = control_flow_graph.new_block()?;
// get operands
let lhs = operand_load(&mut block, &detail.operands[0])?;
let rhs = operand_load(&mut block, &detail.operands[1])?;
let expr = Expr::sub(lhs.clone(), rhs.clone())?;
// calculate flags
set_zf(&mut block, expr.clone())?;
set_sf(&mut block, expr.clone())?;
set_of(&mut block, expr.clone(), lhs.clone(), rhs.clone())?;
set_cf(&mut block, expr.clone(), lhs.clone())?;
block.index()
};
let inc_index = {
let mut block = control_flow_graph.new_block()?;
block.assign(
scalar("edi", 32),
Expr::add(expr_scalar("edi", 32), expr_const(1, 32))?
);
block.index()
};
let dec_index = {
let mut block = control_flow_graph.new_block()?;
block.assign(
scalar("edi", 32),
Expr::sub(expr_scalar("edi", 32), expr_const(1, 32))?
);
block.index()
};
let tail_index = {
control_flow_graph.new_block()?.index()
};
control_flow_graph.conditional_edge(
head_index,
inc_index,
Expr::cmpeq(expr_scalar("DF", 1), expr_const(0, 1))?
)?;
control_flow_graph.conditional_edge(
head_index,
dec_index,
Expr::cmpeq(expr_scalar("DF", 1), expr_const(1, 1))?
)?;
control_flow_graph.unconditional_edge(inc_index, tail_index)?;
control_flow_graph.unconditional_edge(dec_index, tail_index)?;
control_flow_graph.set_entry(head_index)?;
control_flow_graph.set_exit(tail_index)?;
Ok(())
}
pub fn setcc(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let block_index = {
let mut block = control_flow_graph.new_block()?;
let expr = cc_condition(instruction)?;
operand_store(&mut block, &detail.operands[0], Expr::zext(8, expr)?)?;
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn shl(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let block_index = {
let mut block = control_flow_graph.new_block()?;
// get operands
let lhs = operand_load(&mut block, &detail.operands[0])?;
let mut rhs = operand_load(&mut block, &detail.operands[1])?;
if lhs.bits() != rhs.bits() {
rhs = Expr::zext(lhs.bits(), rhs)?;
}
// Do the SHL
let expr = Expr::shl(lhs.clone(), rhs.clone())?;
// CF is the last bit shifted out
// This will give us a bit mask if rhs is not equal to zero
let non_zero_mask = Expr::sub(
expr_const(0, rhs.bits()),
Expr::zext(rhs.bits(), Expr::cmpneq(rhs.clone(), expr_const(0, rhs.bits()))?)?
)?;
// This shifts lhs left by (rhs - 1)
let cf = Expr::shl(lhs.clone(), Expr::sub(rhs.clone(), expr_const(1, rhs.bits()))?)?;
// Apply mask
let cf = Expr::trun(1, Expr::and(cf, non_zero_mask)?)?;
block.assign(scalar("CF", 1), cf.clone());
// OF is set if most significant bit of result is equal to OF
let of = Expr::cmpeq(
cf,
Expr::trun(
1,
Expr::shr(
expr.clone(),
expr_const(expr.bits() as u64 - 1, expr.bits())
)?
)?
)?;
block.assign(scalar("OF", 1), of);
set_zf(&mut block, expr.clone())?;
set_sf(&mut block, expr.clone())?;
operand_store(&mut block, &detail.operands[0], expr)?;
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn shr(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let block_index = {
let mut block = control_flow_graph.new_block()?;
// get operands
let lhs = operand_load(&mut block, &detail.operands[0])?;
let mut rhs = operand_load(&mut block, &detail.operands[1])?;
if lhs.bits() != rhs.bits() {
rhs = Expr::zext(lhs.bits(), rhs)?;
}
// Do the SHR
let expr = Expr::shr(lhs.clone(), rhs.clone())?;
// CF is the last bit shifted out
// This will give us a bit mask if rhs is not equal to zero
let non_zero_mask = Expr::sub(
expr_const(0, rhs.bits()),
Expr::zext(rhs.bits(), Expr::cmpneq(rhs.clone(), expr_const(0, rhs.bits()))?)?
)?;
// This shifts lhs right by (rhs - 1)
let cf = Expr::shr(lhs.clone(), Expr::sub(rhs.clone(), expr_const(1, rhs.bits()))?)?;
// Apply mask
let cf = Expr::trun(1, Expr::and(cf, non_zero_mask)?)?;
block.assign(scalar("CF", 1), cf);
// OF set to most significant bit of the original operand
block.assign(scalar("OF", 1), Expr::trun(
1,
Expr::shr(lhs.clone(), expr_const(lhs.bits() as u64 - 1, lhs.bits()))?
)?);
set_zf(&mut block, expr.clone())?;
set_sf(&mut block, expr.clone())?;
operand_store(&mut block, &detail.operands[0], expr)?;
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn shld(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let block_index = {
let mut block = control_flow_graph.new_block()?;
// get operands
let dst = operand_load(&mut block, &detail.operands[0])?;
let rhs = operand_load(&mut block, &detail.operands[1])?;
let count = operand_load(&mut block, &detail.operands[2])?;
let tmp = Expr::or(
Expr::shl(Expr::zext(dst.bits() * 2, dst.clone())?, expr_const(dst.bits() as u64, dst.bits() * 2))?,
Expr::zext(dst.bits() * 2, rhs)?
)?;
let result = Expr::shl(tmp.clone(), Expr::zext(tmp.bits(), count.clone())?)?;
let cf = Expr::trun(
1,
Expr::shl(
tmp.clone(),
Expr::zext(
tmp.bits(),
Expr::sub(count.clone(), expr_const(1, count.bits()))?
)?
)?
)?;
block.assign(scalar("CF", 1), cf);
set_zf(&mut block, result.clone())?;
set_sf(&mut block, result.clone())?;
operand_store(&mut block, &detail.operands[0], Expr::trun(dst.bits(), result)?)?;
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn shrd(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let block_index = {
let mut block = control_flow_graph.new_block()?;
// get operands
let dst = operand_load(&mut block, &detail.operands[0])?;
let rhs = operand_load(&mut block, &detail.operands[1])?;
let count = operand_load(&mut block, &detail.operands[2])?;
let tmp = Expr::or(
Expr::zext(dst.bits() * 2, dst.clone())?,
Expr::shl(Expr::zext(dst.bits() * 2, rhs)?, expr_const(dst.bits() as u64, dst.bits() * 2))?
)?;
let result = Expr::shr(tmp.clone(), Expr::zext(tmp.bits(), count.clone())?)?;
let cf = Expr::trun(
1,
Expr::shr(
tmp.clone(),
Expr::zext(
tmp.bits(),
Expr::sub(count.clone(), expr_const(1, count.bits()))?
)?
)?
)?;
block.assign(scalar("CF", 1), cf);
set_zf(&mut block, result.clone())?;
set_sf(&mut block, result.clone())?;
operand_store(&mut block, &detail.operands[0], Expr::trun(dst.bits(), result)?)?;
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn stc(control_flow_graph: &mut ControlFlowGraph, _: &capstone::Instr) -> Result<()> {
let block_index = {
let mut block = control_flow_graph.new_block()?;
block.assign(scalar("CF", 1), expr_const(1, 1));
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn std(control_flow_graph: &mut ControlFlowGraph, _: &capstone::Instr) -> Result<()> {
let block_index = {
let mut block = control_flow_graph.new_block()?;
block.assign(scalar("DF", 1), expr_const(1, 1));
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn sti(control_flow_graph: &mut ControlFlowGraph, _: &capstone::Instr) -> Result<()> {
let block_index = {
let mut block = control_flow_graph.new_block()?;
block.assign(scalar("IF", 1), expr_const(1, 1));
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn stos(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
// create a block for this instruction
let (block_index, bits) = {
let mut block = control_flow_graph.new_block()?;
let src = operand_load(&mut block, &detail.operands[1])?;
let bits = src.bits();
operand_store(&mut block, &detail.operands[0], src)?;
(block.index(), bits as u64)
};
let inc_index = {
let mut inc_block = control_flow_graph.new_block()?;;
inc_block.assign(
scalar("edi", 32),
Expr::add(expr_scalar("edi", 32), expr_const(bits / 8, 32))?
);
inc_block.index()
};
let dec_index = {
let mut dec_block = control_flow_graph.new_block()?;;
dec_block.assign(
scalar("edi", 32),
Expr::sub(expr_scalar("edi", 32), expr_const(bits / 8, 32))?
);
dec_block.index()
};
let terminating_index = {
control_flow_graph.new_block()?.index()
};
control_flow_graph.conditional_edge(
block_index,
inc_index,
Expr::cmpeq(expr_scalar("DF", 1), expr_const(0, 1))?
)?;
control_flow_graph.conditional_edge(
block_index,
dec_index,
Expr::cmpeq(expr_scalar("DF", 1), expr_const(1, 1))?
)?;
control_flow_graph.unconditional_edge(inc_index, terminating_index)?;
control_flow_graph.unconditional_edge(dec_index, terminating_index)?;
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(terminating_index)?;
Ok(())
}
pub fn sub(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
// create a block for this instruction
let block_index = {
let mut block = control_flow_graph.new_block()?;
// get operands
let lhs = operand_load(&mut block, &detail.operands[0])?;
let mut rhs = operand_load(&mut block, &detail.operands[1])?;
if lhs.bits() != rhs.bits() {
rhs = Expr::sext(lhs.bits(), rhs)?;
}
let result = block.temp(lhs.bits());
block.assign(result.clone(), Expr::sub(lhs.clone(), rhs.clone())?);
// calculate flags
set_zf(&mut block, result.clone().into())?;
set_sf(&mut block, result.clone().into())?;
set_of(&mut block, result.clone().into(), lhs.clone(), rhs.clone())?;
set_cf(&mut block, result.clone().into(), lhs.clone())?;
// store result
operand_store(&mut block, &detail.operands[0], result.into())?;
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn sysenter(control_flow_graph: &mut ControlFlowGraph, _: &capstone::Instr) -> Result<()> {
// create a block for this instruction
let block_index = {
let mut block = control_flow_graph.new_block()?;
// get operands
block.raise(expr_scalar("sysenter", 1));
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn test(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let block_index = {
let mut block = control_flow_graph.new_block()?;
// get operands
let lhs = operand_load(&mut block, &detail.operands[0])?;
let rhs = operand_load(&mut block, &detail.operands[1])?;
let expr = Expr::and(lhs.clone(), rhs.clone())?;
// calculate flags
set_zf(&mut block, expr.clone())?;
set_sf(&mut block, expr)?;
block.assign(scalar("CF", 1), expr_const(0, 1));
block.assign(scalar("OF", 1), expr_const(0, 1));;
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn xadd(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let block_index = {
let mut block = control_flow_graph.new_block()?;
// get operands
let lhs = operand_load(&mut block, &detail.operands[0])?;
let rhs = operand_load(&mut block, &detail.operands[1])?;
let result = block.temp(lhs.bits());
// perform addition
block.assign(result.clone(), Expr::add(lhs.clone(), rhs.clone())?);
// calculate flags
set_zf(&mut block, result.clone().into())?;
set_sf(&mut block, result.clone().into())?;
set_of(&mut block, result.clone().into(), lhs.clone(), rhs.clone())?;
set_cf(&mut block, result.clone().into(), lhs.clone())?;
// store result
operand_store(&mut block, &detail.operands[0], result.into())?;
operand_store(&mut block, &detail.operands[1], rhs)?;
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn xchg(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
let block_index = {
let mut block = control_flow_graph.new_block()?;
// get operands
let lhs = operand_load(&mut block, &detail.operands[0])?;
let rhs = operand_load(&mut block, &detail.operands[1])?;
let tmp = block.temp(lhs.bits());
block.assign(tmp.clone(), lhs.clone());
operand_store(&mut block, &detail.operands[0], rhs)?;
operand_store(&mut block, &detail.operands[1], tmp.into())?;
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn xor(control_flow_graph: &mut ControlFlowGraph, instruction: &capstone::Instr) -> Result<()> {
let detail = try!(details(instruction));
// create a block for this instruction
let block_index = {
let mut block = control_flow_graph.new_block()?;
// get operands
let lhs = operand_load(&mut block, &detail.operands[0])?;
let mut rhs = operand_load(&mut block, &detail.operands[1])?;
if lhs.bits() != rhs.bits() {
rhs = Expr::sext(lhs.bits(), rhs)?;
}
let result = block.temp(lhs.bits());
block.assign(result.clone(), Expr::xor(lhs.clone(), rhs.clone())?);
// calculate flags
set_zf(&mut block, result.clone().into())?;
set_sf(&mut block, result.clone().into())?;
block.assign(scalar("CF", 1), expr_const(0, 1));
block.assign(scalar("OF", 1), expr_const(0, 1));;
// store result
operand_store(&mut block, &detail.operands[0], result.into())?;
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
|
#[doc = "Register `DCMI_CR` reader"]
pub type R = crate::R<DCMI_CR_SPEC>;
#[doc = "Register `DCMI_CR` writer"]
pub type W = crate::W<DCMI_CR_SPEC>;
#[doc = "Field `CAPTURE` reader - CAPTURE"]
pub type CAPTURE_R = crate::BitReader;
#[doc = "Field `CAPTURE` writer - CAPTURE"]
pub type CAPTURE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CM` reader - CM"]
pub type CM_R = crate::BitReader;
#[doc = "Field `CM` writer - CM"]
pub type CM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CROP` reader - CROP"]
pub type CROP_R = crate::BitReader;
#[doc = "Field `CROP` writer - CROP"]
pub type CROP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `JPEG` reader - JPEG"]
pub type JPEG_R = crate::BitReader;
#[doc = "Field `JPEG` writer - JPEG"]
pub type JPEG_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `ESS` reader - ESS"]
pub type ESS_R = crate::BitReader;
#[doc = "Field `ESS` writer - ESS"]
pub type ESS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PCKPOL` reader - PCKPOL"]
pub type PCKPOL_R = crate::BitReader;
#[doc = "Field `PCKPOL` writer - PCKPOL"]
pub type PCKPOL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `HSPOL` reader - HSPOL"]
pub type HSPOL_R = crate::BitReader;
#[doc = "Field `HSPOL` writer - HSPOL"]
pub type HSPOL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `VSPOL` reader - VSPOL"]
pub type VSPOL_R = crate::BitReader;
#[doc = "Field `VSPOL` writer - VSPOL"]
pub type VSPOL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `FCRC` reader - FCRC"]
pub type FCRC_R = crate::FieldReader;
#[doc = "Field `FCRC` writer - FCRC"]
pub type FCRC_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `EDM` reader - EDM"]
pub type EDM_R = crate::FieldReader;
#[doc = "Field `EDM` writer - EDM"]
pub type EDM_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `ENABLE` reader - ENABLE"]
pub type ENABLE_R = crate::BitReader;
#[doc = "Field `ENABLE` writer - ENABLE"]
pub type ENABLE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `BSM` reader - BSM"]
pub type BSM_R = crate::FieldReader;
#[doc = "Field `BSM` writer - BSM"]
pub type BSM_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `OEBS` reader - OEBS"]
pub type OEBS_R = crate::BitReader;
#[doc = "Field `OEBS` writer - OEBS"]
pub type OEBS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `LSM` reader - LSM"]
pub type LSM_R = crate::BitReader;
#[doc = "Field `LSM` writer - LSM"]
pub type LSM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `OELS` reader - OELS"]
pub type OELS_R = crate::BitReader;
#[doc = "Field `OELS` writer - OELS"]
pub type OELS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - CAPTURE"]
#[inline(always)]
pub fn capture(&self) -> CAPTURE_R {
CAPTURE_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - CM"]
#[inline(always)]
pub fn cm(&self) -> CM_R {
CM_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - CROP"]
#[inline(always)]
pub fn crop(&self) -> CROP_R {
CROP_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - JPEG"]
#[inline(always)]
pub fn jpeg(&self) -> JPEG_R {
JPEG_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - ESS"]
#[inline(always)]
pub fn ess(&self) -> ESS_R {
ESS_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - PCKPOL"]
#[inline(always)]
pub fn pckpol(&self) -> PCKPOL_R {
PCKPOL_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 6 - HSPOL"]
#[inline(always)]
pub fn hspol(&self) -> HSPOL_R {
HSPOL_R::new(((self.bits >> 6) & 1) != 0)
}
#[doc = "Bit 7 - VSPOL"]
#[inline(always)]
pub fn vspol(&self) -> VSPOL_R {
VSPOL_R::new(((self.bits >> 7) & 1) != 0)
}
#[doc = "Bits 8:9 - FCRC"]
#[inline(always)]
pub fn fcrc(&self) -> FCRC_R {
FCRC_R::new(((self.bits >> 8) & 3) as u8)
}
#[doc = "Bits 10:11 - EDM"]
#[inline(always)]
pub fn edm(&self) -> EDM_R {
EDM_R::new(((self.bits >> 10) & 3) as u8)
}
#[doc = "Bit 14 - ENABLE"]
#[inline(always)]
pub fn enable(&self) -> ENABLE_R {
ENABLE_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bits 16:17 - BSM"]
#[inline(always)]
pub fn bsm(&self) -> BSM_R {
BSM_R::new(((self.bits >> 16) & 3) as u8)
}
#[doc = "Bit 18 - OEBS"]
#[inline(always)]
pub fn oebs(&self) -> OEBS_R {
OEBS_R::new(((self.bits >> 18) & 1) != 0)
}
#[doc = "Bit 19 - LSM"]
#[inline(always)]
pub fn lsm(&self) -> LSM_R {
LSM_R::new(((self.bits >> 19) & 1) != 0)
}
#[doc = "Bit 20 - OELS"]
#[inline(always)]
pub fn oels(&self) -> OELS_R {
OELS_R::new(((self.bits >> 20) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - CAPTURE"]
#[inline(always)]
#[must_use]
pub fn capture(&mut self) -> CAPTURE_W<DCMI_CR_SPEC, 0> {
CAPTURE_W::new(self)
}
#[doc = "Bit 1 - CM"]
#[inline(always)]
#[must_use]
pub fn cm(&mut self) -> CM_W<DCMI_CR_SPEC, 1> {
CM_W::new(self)
}
#[doc = "Bit 2 - CROP"]
#[inline(always)]
#[must_use]
pub fn crop(&mut self) -> CROP_W<DCMI_CR_SPEC, 2> {
CROP_W::new(self)
}
#[doc = "Bit 3 - JPEG"]
#[inline(always)]
#[must_use]
pub fn jpeg(&mut self) -> JPEG_W<DCMI_CR_SPEC, 3> {
JPEG_W::new(self)
}
#[doc = "Bit 4 - ESS"]
#[inline(always)]
#[must_use]
pub fn ess(&mut self) -> ESS_W<DCMI_CR_SPEC, 4> {
ESS_W::new(self)
}
#[doc = "Bit 5 - PCKPOL"]
#[inline(always)]
#[must_use]
pub fn pckpol(&mut self) -> PCKPOL_W<DCMI_CR_SPEC, 5> {
PCKPOL_W::new(self)
}
#[doc = "Bit 6 - HSPOL"]
#[inline(always)]
#[must_use]
pub fn hspol(&mut self) -> HSPOL_W<DCMI_CR_SPEC, 6> {
HSPOL_W::new(self)
}
#[doc = "Bit 7 - VSPOL"]
#[inline(always)]
#[must_use]
pub fn vspol(&mut self) -> VSPOL_W<DCMI_CR_SPEC, 7> {
VSPOL_W::new(self)
}
#[doc = "Bits 8:9 - FCRC"]
#[inline(always)]
#[must_use]
pub fn fcrc(&mut self) -> FCRC_W<DCMI_CR_SPEC, 8> {
FCRC_W::new(self)
}
#[doc = "Bits 10:11 - EDM"]
#[inline(always)]
#[must_use]
pub fn edm(&mut self) -> EDM_W<DCMI_CR_SPEC, 10> {
EDM_W::new(self)
}
#[doc = "Bit 14 - ENABLE"]
#[inline(always)]
#[must_use]
pub fn enable(&mut self) -> ENABLE_W<DCMI_CR_SPEC, 14> {
ENABLE_W::new(self)
}
#[doc = "Bits 16:17 - BSM"]
#[inline(always)]
#[must_use]
pub fn bsm(&mut self) -> BSM_W<DCMI_CR_SPEC, 16> {
BSM_W::new(self)
}
#[doc = "Bit 18 - OEBS"]
#[inline(always)]
#[must_use]
pub fn oebs(&mut self) -> OEBS_W<DCMI_CR_SPEC, 18> {
OEBS_W::new(self)
}
#[doc = "Bit 19 - LSM"]
#[inline(always)]
#[must_use]
pub fn lsm(&mut self) -> LSM_W<DCMI_CR_SPEC, 19> {
LSM_W::new(self)
}
#[doc = "Bit 20 - OELS"]
#[inline(always)]
#[must_use]
pub fn oels(&mut self) -> OELS_W<DCMI_CR_SPEC, 20> {
OELS_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 = "DCMI control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`dcmi_cr::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 [`dcmi_cr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct DCMI_CR_SPEC;
impl crate::RegisterSpec for DCMI_CR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`dcmi_cr::R`](R) reader structure"]
impl crate::Readable for DCMI_CR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`dcmi_cr::W`](W) writer structure"]
impl crate::Writable for DCMI_CR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets DCMI_CR to value 0"]
impl crate::Resettable for DCMI_CR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use base64;
use hex;
use std::ops::BitXor;
// Fixed XOR
#[derive(Debug, PartialEq)]
struct BytesXOR(Vec<u8>);
impl BitXor for BytesXOR {
type Output = Self;
fn bitxor(self, BytesXOR(rhs): Self) -> Self {
let BytesXOR(lhs) = self;
assert_eq!(lhs.len(), rhs.len());
BytesXOR(lhs.iter().zip(rhs.iter()).map(|(x, y)| *x ^ *y).collect())
}
}
pub fn fixed_XOR(data_1: &str, data_2: &str) -> String {
let one = hex::decode(data_1).unwrap();
let two = hex::decode(data_2).unwrap();
let xor = BytesXOR(one) ^ BytesXOR(two);
hex::encode(xor.0)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_fixed_XOR() {
let data_1 = "1c0111001f010100061a024b53535009181c";
let data_2 = "686974207468652062756c6c277320657965";
assert_eq!(
fixed_XOR(data_1, data_2),
"746865206b696420646f6e277420706c6179"
);
}
}
|
use std::{i8, i16, i32, i64, u8, u16, u32, u64, isize, usize, f32, f64};
use std::io::stdin;
fn main() {
println!("Hello World");
let num = 10;
let mut age: i32 = 40;
println!("Max i8 {}", i8::MAX);
println!("Min i8 {}", i8::MIN);
println!("Max i16 {}", i16::MAX);
println!("Min i16 {}", i16::MIN);
println!("Max i32 {}", i32::MAX);
println!("Min i32 {}", i32::MIN);
println!("Max i64 {}", i64::MAX);
println!("Min i64 {}", i64::MIN);
println!("Max isize {}", isize::MAX);
println!("Min isize {}", isize::MIN);
println!("Max usize {}", usize::MAX);
println!("Min usize {}", usize::MIN);
println!("Max f32 {}", f32::MAX);
println!("Min f32 {}", f32::MIN);
println!("Max f64 {}", f64::MAX);
println!("Min f64 {}", f64::MIN);
let is_it_true: bool = true;
let let_x: char = 'x';
println!("I am {} years old", age);
let (f_name, l_name) = ("Derek", "Banas");
println!("It is {0} that {1} is {0}", is_it_true, let_x);
println!("{:.2}", 1.234);
println!("B: {:b} H: {:x} O: {:o}", 10, 10, 10);
println!("{ten:>ws$}", ten = 10, ws = 5);
println!("{ten:>0ws$}", ten = 10, ws = 5);
println!("5 + 4 = {}", 5 + 4);
println!("5 - 4 = {}", 5 - 4);
println!("5 * 4 = {}", 5 * 4);
println!("5 / 4 = {}", 5 / 4);
println!("5 % 4 = {}", 5 % 4);
let mut neg_4 = -4i32;
println!("abs(-4) = {}", neg_4.abs());
println!("4 ^ 6 = {}", 4i32.pow(6));
println!("e ^ 2 = {}", 1f64.exp());
println!("Sin 3.14 = {}", 3.14f64.sin());
let age_old = 6;
if (age_old == 5) {
println!("Go to Kindergarten");
} else if (age_old > 5) && (age_old <= 18) {
println!("Go to grade {}", (age_old - 5));
} else if (age_old <= 25) && (age_old > 18) {
println!("Go to College");
} else {
println!("Do what you want");
}
println!("!true = {}", !true);
println!("true || false = {}", true || false);
println!("true != false = {}", true != false);
let can_vote = if (age_old >= 18) { true } else { false };
println!("Can Vote: {}", can_vote);
let mut x = 1;
loop {
if ((x % 2) == 0) {
println!("{}", x);
x += 1;
continue;
}
if (x > 10) {
break;
}
x += 1;
continue;
}
let mut y = 1;
while y <= 10 {
println!("{}", y);
y += 1;
}
for z in 1..10 {
println!("FOR : {}", z);
}
let rand_string = "I am a random string";
println!("Length : {}", rand_string.len());
let (first, second) = rand_string.split_at(6);
println!("first: {}", first);
println!("second: {}", second);
let count = rand_string.chars().count();
let mut chars = rand_string.chars();
let mut indiv_char = chars.next();
loop {
match indiv_char {
Some(x) => println!("{}", x),
None => break,
}
indiv_char = chars.next();
}
let mut iter = rand_string.split_whitespace();
let mut indiv_word = iter.next();
loop {
match indiv_word {
Some(x) => println!("{}", x),
None => break,
}
indiv_word = iter.next();
}
let rand_string2 = "I am a random string\nThere are other strings like it\nThis string is the best";
let mut lines = rand_string2.lines();
let mut indiv_line = lines.next();
loop {
match indiv_line {
Some(x) => println!("{}", x),
None => break,
}
indiv_line = lines.next();
}
println!("Find Best : {}", rand_string2.contains("best"));
'outer: loop {
let number: i32 = 10;
println!("Pick a Number");
loop {
let mut line = String::new();
let input = stdin().read_line(&mut line);
let guess: Option<i32> = input.ok().map_or(None, |_| line.trim().parse().ok());
match guess {
None => println!("Enter a number"),
Some(n) if n == number => {
println!("You Guessed it");
break 'outer;
}
Some(n) if n < number => println!("Too Low"),
Some(n) if n > number => println!("Too High"),
Some(_) => println!("Error"),
}
}
}
let rand_array = [1, 2, 3];
println!("{}", rand_array[0]);
println!("{}", rand_array.len());
println!("Second 2 : {:?}", &rand_array[1..3]);
}
|
// generated protobuf files will be included here. See build.rs for details
include!(env!("PROTO_MOD_RS"));
|
//! Some random linked list traits, may or may not be used in actual program.
mod implementation;
#[cfg(test)]
mod test;
/// An implicitly linked list, allowing freestanding items and multiple links
/// inside itself.
pub trait ImplicitLinkedList<Key>
where
Key: Copy + Eq,
{
type Item: ImplicitLinkedListItem<Key = Key>;
fn get_item(&self, key: Key) -> &Self::Item;
fn get_item_mut(&mut self, key: Key) -> &mut Self::Item;
fn insert_item(&mut self, item: Self::Item) -> Key;
fn remove_item(&mut self, idx: Key) -> Self::Item;
fn next_key(&self, key: Key) -> Option<Key> {
self.get_item(key).next()
}
fn prev_key(&self, key: Key) -> Option<Key> {
self.get_item(key).next()
}
/// Position this item after the given item.
fn attach_after(&mut self, after: Key, this: Key) {
debug_assert!(
self.get_item(this).is_freestanding(),
"The value attached should be freestanding"
);
let after_item = self.get_item_mut(after);
let next = after_item.next();
after_item.set_next(Some(this));
let current = self.get_item_mut(this);
current.set_prev(Some(after));
current.set_next(next);
if let Some(idx) = next {
let next = self.get_item_mut(idx);
next.set_prev(Some(this));
};
}
/// Position this item before the given item.
fn attach_before(&mut self, before: Key, this: Key) {
debug_assert!(
self.get_item(this).is_freestanding(),
"The value attached should be freestanding"
);
let before_item = self.get_item_mut(before);
let prev = before_item.prev();
before_item.set_prev(Some(this));
let current = self.get_item_mut(this);
current.set_next(Some(before));
current.set_prev(prev);
if let Some(idx) = prev {
let prev = self.get_item_mut(idx);
prev.set_next(Some(this));
};
}
/// Detaches this item from the list.
fn detach(&mut self, idx: Key) {
let inst = self.get_item_mut(idx);
let next_idx = inst.take_next();
let prev_idx = inst.take_prev();
if let Some(prev_idx) = prev_idx {
let prev = self.get_item_mut(prev_idx);
prev.set_next(next_idx);
}
if let Some(next_idx) = next_idx {
let next = self.get_item_mut(next_idx);
next.set_prev(prev_idx)
}
}
/// Split the chain into two after the given item, or return `None` if no
/// item is after the given item.
fn split_after(&mut self, idx: Key) -> Option<Key> {
let head = self.get_item_mut(idx).take_next();
if let Some(head) = head {
self.get_item_mut(head).set_prev(None);
}
head
}
/// Split the chain into two before the given item, or return `None` if no
/// item is before the given item.
fn split_before(&mut self, idx: Key) -> Option<Key> {
let tail = self.get_item_mut(idx).take_prev();
if let Some(tail) = tail {
self.get_item_mut(tail).set_next(None);
}
tail
}
fn connect(&mut self, tail: Key, head: Key) {
debug_assert!(head != tail, "Cannot connect an item to itself");
debug_assert!(
self.get_item(head).prev().is_none(),
"Head item should be the last one in chain"
);
debug_assert!(
self.get_item(tail).next().is_none(),
"Tail item should be the first one in chain"
);
let head_item = self.get_item_mut(head);
head_item.set_prev(Some(tail));
let tail_item = self.get_item_mut(tail);
tail_item.set_next(Some(head));
}
/// Creates an iterator of items of Self in a chain, from item `from` to `to`.
///
/// - If `from` is `None`, the resulting iterator will be empty.
/// - If `to` is `None`, the resulting iterator will iterate until the end of chain.
fn items_iter(&self, from: Option<Key>, to: Option<Key>) -> ItemsIter<Self, Key> {
ItemsIter::new(self, from, to)
}
}
pub trait ImplicitLinkedListGet2<Key>: ImplicitLinkedList<Key>
where
Key: Copy + Eq,
{
fn get2_mut(&mut self, i1: Key, i2: Key) -> (&mut Self::Item, &mut Self::Item);
}
/// An implicit linked list item. Contains keys for the previous and next items
/// of `Self`.
pub trait ImplicitLinkedListItem {
type Key: Copy + Eq;
fn next(&self) -> Option<Self::Key>;
fn set_next(&mut self, key: Option<Self::Key>);
fn take_next(&mut self) -> Option<Self::Key> {
let next = self.next();
self.set_next(None);
next
}
fn prev(&self) -> Option<Self::Key>;
fn set_prev(&mut self, key: Option<Self::Key>);
fn take_prev(&mut self) -> Option<Self::Key> {
let prev = self.prev();
self.set_prev(None);
prev
}
fn is_freestanding(&self) -> bool {
self.next().is_none() && self.prev().is_none()
}
}
/// An iterator of all items in one chain in an [`ImplicitLinkedList`]. Created
/// by [`ImplicitLinkedList::item_iter`].
pub struct ItemsIter<'a, Ctx, Key>
where
Ctx: ?Sized,
{
ctx: &'a Ctx,
curr: Option<Key>,
tail: Option<Key>,
}
impl<'a, Ctx, Key> ItemsIter<'a, Ctx, Key>
where
Ctx: ?Sized,
{
pub fn new(ctx: &'a Ctx, curr: Option<Key>, tail: Option<Key>) -> Self {
Self { ctx, curr, tail }
}
}
impl<'a, Ctx, Key> Iterator for ItemsIter<'a, Ctx, Key>
where
Ctx: ImplicitLinkedList<Key> + ?Sized,
Ctx::Item: 'a,
Key: Copy + Eq,
{
type Item = (Key, &'a Ctx::Item);
fn next(&mut self) -> Option<Self::Item> {
if self.curr.is_none() || self.curr == self.tail {
return None;
}
let curr = self.curr.unwrap();
let item = self.ctx.get_item(curr);
self.curr = item.next();
Some((curr, item))
}
}
|
// Copyright (c) The diem-devtools Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Support for partitioning test runs across several machines.
//!
//! At the moment this only supports a simple hash-based sharding. In the future it could potentially
//! be made smarter: e.g. using data to pick different sets of binaries and tests to run, with
//! an aim to minimize total build and test times.
use crate::test_list::TestBinary;
use anyhow::{anyhow, bail, Context};
use std::{
fmt,
hash::{Hash, Hasher},
str::FromStr,
};
use twox_hash::XxHash64;
/// A builder for creating `Partitioner` instances.
///
/// The relationship between `PartitionerBuilder` and `Partitioner` is similar to that between
/// `std`'s `BuildHasher` and `Hasher`.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum PartitionerBuilder {
/// Partition based on counting test numbers.
Count {
/// The shard this is in, counting up from 1.
shard: u64,
/// The total number of shards.
total_shards: u64,
},
/// Partition based on hashing. Individual partitions are stateless.
Hash {
/// The shard this is in, counting up from 1.
shard: u64,
/// The total number of shards.
total_shards: u64,
},
}
/// Represents an individual partitioner, typically scoped to a test binary.
pub trait Partitioner: fmt::Debug {
/// Returns true if the given test name matches the partition.
fn test_matches(&mut self, test_name: &str) -> bool;
}
impl PartitionerBuilder {
/// Creates a new `Partitioner` from this `PartitionerBuilder`.
pub fn build(&self, _test_binary: &TestBinary) -> Box<dyn Partitioner> {
// Note we don't use test_binary at the moment but might in the future.
match self {
PartitionerBuilder::Count {
shard,
total_shards,
} => Box::new(CountPartitioner::new(*shard, *total_shards)),
PartitionerBuilder::Hash {
shard,
total_shards,
} => Box::new(HashPartitioner::new(*shard, *total_shards)),
}
}
// ---
// Helper methods
// ---
fn parse_impl(s: &str) -> anyhow::Result<Self> {
// Parse the string: it looks like "hash:<shard>/<total_shards>".
if let Some(input) = s.strip_prefix("hash:") {
let (shard, total_shards) =
parse_shards(input).context("partition must be in the format \"hash:M/N\"")?;
Ok(PartitionerBuilder::Hash {
shard,
total_shards,
})
} else if let Some(input) = s.strip_prefix("count:") {
let (shard, total_shards) =
parse_shards(input).context("partition must be in the format \"count:M/N\"")?;
Ok(PartitionerBuilder::Count {
shard,
total_shards,
})
} else {
bail!(
"partition input '{}' must begin with \"hash:\" or \"count:\"",
s
)
}
}
}
/// An error that occurs while parsing a `PartitionerBuilder` input.
#[derive(Debug)]
pub struct ParseError(anyhow::Error);
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let chain = self.0.chain();
let len = chain.len();
for (i, err) in chain.enumerate() {
if i == 0 {
writeln!(f, "{}", err)?;
} else if i < len - 1 {
writeln!(f, "({})", err)?;
} else {
// Skip the last newline since that's what looks best with structopt.
write!(f, "({})", err)?;
}
}
Ok(())
}
}
impl FromStr for PartitionerBuilder {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::parse_impl(s).map_err(ParseError)
}
}
fn parse_shards(input: &str) -> anyhow::Result<(u64, u64)> {
let mut split = input.splitn(2, '/');
// First "next" always returns a value.
let shard_str = split.next().expect("split should have at least 1 element");
// Second "next" may or may not return a value.
let total_shards_str = split
.next()
.ok_or_else(|| anyhow!("expected input '{}' to be in the format M/N", input))?;
let shard: u64 = shard_str
.parse()
.with_context(|| format!("failed to parse shard '{}' as u64", shard_str))?;
let total_shards: u64 = total_shards_str
.parse()
.with_context(|| format!("failed to parse total_shards '{}' as u64", total_shards_str))?;
// Check that shard > 0 and <= total_shards.
if !(1..=total_shards).contains(&shard) {
bail!(
"shard {} must be a number between 1 and total shards {}, inclusive",
shard,
total_shards
);
}
Ok((shard, total_shards))
}
#[derive(Clone, Debug)]
struct CountPartitioner {
shard_minus_one: u64,
total_shards: u64,
curr: u64,
}
impl CountPartitioner {
fn new(shard: u64, total_shards: u64) -> Self {
let shard_minus_one = shard - 1;
Self {
shard_minus_one,
total_shards,
curr: 0,
}
}
}
impl Partitioner for CountPartitioner {
fn test_matches(&mut self, _test_name: &str) -> bool {
let matches = self.curr == self.shard_minus_one;
self.curr = (self.curr + 1) % self.total_shards;
matches
}
}
#[derive(Clone, Debug)]
struct HashPartitioner {
shard_minus_one: u64,
total_shards: u64,
}
impl HashPartitioner {
fn new(shard: u64, total_shards: u64) -> Self {
let shard_minus_one = shard - 1;
Self {
shard_minus_one,
total_shards,
}
}
}
impl Partitioner for HashPartitioner {
fn test_matches(&mut self, test_name: &str) -> bool {
let mut hasher = XxHash64::default();
test_name.hash(&mut hasher);
hasher.finish() % self.total_shards == self.shard_minus_one
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn partitioner_builder_from_str() {
let successes = vec![
(
"hash:1/2",
PartitionerBuilder::Hash {
shard: 1,
total_shards: 2,
},
),
(
"hash:1/1",
PartitionerBuilder::Hash {
shard: 1,
total_shards: 1,
},
),
(
"hash:99/200",
PartitionerBuilder::Hash {
shard: 99,
total_shards: 200,
},
),
];
let failures = vec![
"foo",
"hash",
"hash:",
"hash:1",
"hash:1/",
"hash:0/2",
"hash:3/2",
"hash:m/2",
"hash:1/n",
"hash:1/2/3",
];
for (input, output) in successes {
assert_eq!(
PartitionerBuilder::from_str(input).unwrap_or_else(|err| panic!(
"expected input '{}' to succeed, failed with: {}",
input, err
)),
output,
"success case '{}' matches",
input,
);
}
for input in failures {
PartitionerBuilder::from_str(input)
.expect_err(&format!("expected input '{}' to fail", input));
}
}
}
|
use std::io::{Write, Result};
use pulldown_cmark::{Event, Tag};
use crate::gen::Document;
mod preamble;
#[derive(Debug)]
pub struct Article;
impl<'a> Document<'a> for Article {
type Simple = super::SimpleGen;
type Paragraph = super::Paragraph;
type Rule = super::Rule;
type Header = super::Header;
type BlockQuote = super::BlockQuote;
type CodeBlock = super::CodeBlock;
type List = super::List;
type Item = super::Item;
type FootnoteDefinition = super::FootnoteDefinition;
type Table = super::Table;
type TableHead = super::TableHead;
type TableRow = super::TableRow;
type TableCell = super::TableCell;
type InlineEmphasis = super::InlineEmphasis;
type InlineStrong = super::InlineStrong;
type InlineCode = super::InlineCode;
type Link = super::Link<'a>;
type Image = super::Image<'a>;
fn new() -> Self {
Article
}
fn gen_preamble(&mut self, out: &mut impl Write) -> Result<()> {
// TODO: papersize, documentclass, geometry
// TODO: itemizespacing
writeln!(out, "\\documentclass[a4paper]{{scrartcl}}")?;
writeln!(out, "\\usepackage[utf8]{{inputenc}}")?;
writeln!(out)?;
// TODO: include rust highlighting
// TODO: use minted instead of lstlistings?
// TODO: lstset
writeln!(out, "\\usepackage{{listings}}")?;
writeln!(out, "\\usepackage[usenames, dvipsnames]{{color}}")?;
writeln!(out, "\\usepackage{{xcolor}}")?;
writeln!(out, "{}", preamble::lstset)?;
writeln!(out, "{}", preamble::lstdefineasm)?;
writeln!(out, "{}", preamble::lstdefinerust)?;
// TODO: graphicspath
writeln!(out, "\\usepackage{{graphicx}}")?;
writeln!(out, "\\usepackage{{hyperref}}")?;
// TODO: cleveref options
writeln!(out, "\\usepackage{{cleveref}}")?;
writeln!(out, "\\usepackage{{refcount}}")?;
writeln!(out, "\\usepackage{{array}}")?;
writeln!(out, "{}", preamble::thickhline)?;
writeln!(out)?;
writeln!(out, "{}", preamble::aquote)?;
writeln!(out)?;
writeln!(out, "\\begin{{document}}")?;
writeln!(out)?;
Ok(())
}
fn gen_epilogue(&mut self, out: &mut impl Write) -> Result<()> {
writeln!(out, "\\end{{document}}")?;
Ok(())
}
}
|
use crate::vec::Vec3;
use num::Float;
use num_traits::NumAssign;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Particle<T: Float> {
pub position: Vec3<T>,
pub velocity: Vec3<T>,
pub acceleration: Vec3<T>,
pub damping: T,
/// We store the inverse mass because it makes infinite mass possible and zero mass impossible.
///
/// Zero mass would be problematic because any force would result in infinite acceleration,
/// and more practically, it would result in division by zero.
///
/// Infinite mass is a convenient way to make an immovable object.
///
/// Inverse mass is also conveniently used in our physics equations:
/// ```text
/// f = ma ∴ a = f*(1/m)
/// ```
/// `(1/m)` is inverse mass.
pub inverse_mass: T,
}
impl<T: Float + NumAssign> Particle<T> {
pub fn integrate(&mut self, duration: T) {
self.position += self.velocity * duration;
self.velocity += self.acceleration * duration;
self.velocity *= self.damping.powf(duration);
}
}
|
use std::cmp::max;
impl Solution {
pub fn rob(nums: Vec<i32>) -> i32 {
let n = nums.len();
if n == 0{
return 0;
}
if n == 1{
return nums[0];
}
robRange(&nums,0,n-2).max(robRange(&nums,1,n-1))
}
}
fn robRange(nums:&[i32],start:usize,end:usize) -> i32{
if start == end{
return nums[start];
}
let mut dp = vec![0;nums.len()];
dp[start] = nums[start];
dp[start + 1] = max(nums[start],nums[start + 1]);
for i in (start + 2)..=end{
dp[i] = max(dp[i - 1],dp[i - 2] + nums[i]);
}
dp[end]
} |
extern crate actix;
extern crate actix_web;
extern crate openssl;
#[macro_use] extern crate lazy_static;
#[macro_use] extern crate serde_derive;
mod crypto;
use actix_web::{server, App, Json, HttpRequest, http, Error};
use actix_web::error::{ ErrorBadRequest, ErrorInternalServerError};
use crypto::{CryptoService, RSACryptoService};
use openssl::bn::BigNum;
use std::env;
lazy_static! {
static ref CRYPTO_SERVICE: RSACryptoService = RSACryptoService::new();
}
#[derive(Serialize)]
struct SecretMsg{
secret: String,
}
#[derive(Deserialize)]
struct OracleReq {
check: String,
}
#[derive(Serialize)]
struct OracleRsp {
parity: bool,
}
fn secret(_req: &HttpRequest) -> Result<Json<SecretMsg>, Error> {
let plaintext = env::var("SECRET").unwrap_or(String::from("SECRETSECRETSECRET"));
let cryptotext: Vec<u8> = CRYPTO_SERVICE.encrypt(plaintext.as_bytes())
.map_err(ErrorInternalServerError)?;
let secret_num = BigNum::from_slice(cryptotext.as_slice())
.map_err(ErrorInternalServerError)?;
let secret = String::from(&**secret_num.to_dec_str().unwrap());
Ok(Json(SecretMsg{secret: secret}))
}
fn oracle(req: Json<OracleReq>) -> Result<Json<OracleRsp>, Error> {
let check = BigNum::from_dec_str(&req.check).map_err(ErrorBadRequest)?;
let cryptotext = check.to_vec();
let plaintext: Vec<u8> = CRYPTO_SERVICE.decrypt(cryptotext.as_slice())
.map_err(ErrorInternalServerError)?;
let dec_num = BigNum::from_slice(plaintext.as_slice()).unwrap();
let parity = dec_num.mod_word(2).unwrap() == 0;
return Ok(Json(OracleRsp { parity: parity }));
}
fn pubkey(_req: &HttpRequest) -> String {
let pubkey = CRYPTO_SERVICE.pubkey_pem();
pubkey
}
fn main() {
let sys = actix::System::new("RSA padding oracle");
server::new( || {
vec![
App::new()
.resource("/pubkey", |r| r.f(pubkey))
.resource("/secret", |r| r.f(secret))
.resource("/oracle", |r| r.method(http::Method::POST).with(oracle)),
//App::new().resource("/", |r| r.f(|_r| HttpResponse::Ok())),
]
})
.bind("127.0.0.1:8080")
.expect("Can not bind to port 8080")
.start();
println!("Started http server: 127.0.0.1:8080");
let _ = sys.run();
}
|
use std::collections::HashSet;
use crate::util::lines_from_file;
pub fn day17() {
println!("== Day 17 ==");
let input = lines_from_file("src/day17/input.txt");
let a = part_a(&input);
println!("Part A: {}", a);
let b = part_b(&input);
println!("Part B: {}", b);
}
fn part_a(input: &Vec<String>) -> i32 {
let target: Vec<(char, (i32, i32))> = parse_target(input);
// println!("{:?}", target);
let steps = i32::abs(target[1].1.0) * i32::abs(target[0].1.1);
let mut y = 0;
let mut velocities = Vec::new();
for x in 0..target[0].1.1 {
for y in 0..i32::abs(target[1].1.0) {
velocities.push((x, y));
}
}
for test_vel in velocities {
let mut pos = (0, 0);
let mut vel = test_vel;
// println!("Testing: {:?}", vel);
let mut ys = Vec::new();
for _step in 0..steps {
pos.0 += vel.0;
pos.1 += vel.1;
vel.0 -= 1;
vel.1 -= 1;
if vel.0 < 0 {
vel.0 = 0;
}
ys.push(pos.1);
// println!("Pos: {:?} , in range: {}", pos, in_range(&pos, &target));
if in_range(&pos, &target) {
let by = *ys.iter().max().unwrap();
if by > y { y = by }
}
if past_range(&pos, &target) {
break;
}
}
}
y
}
fn part_b(input: &Vec<String>) -> usize {
let target: Vec<(char, (i32, i32))> = parse_target(input);
let steps = i32::abs(target[1].1.0) * i32::abs(target[0].1.1);
let mut velocities = Vec::new();
for x in 0..=target[0].1.1 {
for y in target[1].1.0..=i32::abs(target[1].1.0) {
velocities.push((x, y));
}
}
let mut valid: Vec<(i32, i32)> = Vec::new();
for test_vel in velocities {
let mut pos = (0, 0);
let mut vel = test_vel;
// println!("Testing: {:?}", vel);
for _step in 0..steps {
pos.0 += vel.0;
pos.1 += vel.1;
vel.0 -= 1;
vel.1 -= 1;
if vel.0 < 0 {
vel.0 = 0;
}
// println!("Pos: {:?} , in range: {}", pos, in_range(&pos, &target));
if in_range(&pos, &target) {
valid.push(test_vel);
break;
}
if past_range(&pos, &target) {
break;
}
}
}
let set: HashSet<&(i32, i32)> = HashSet::from_iter(valid.iter());
set.len()
}
fn parse_target(input: &Vec<String>) -> Vec<(char, (i32, i32))> {
input.get(0)
.unwrap()
.split(": ")
.collect::<Vec<&str>>()
.get(1)
.unwrap()
.split(", ")
.collect::<Vec<&str>>()
.iter()
.map(|s| s.split("=").collect::<Vec<&str>>())
.map(|v| {
let xy = v.get(0).unwrap().chars().collect::<Vec<char>>()[0];
let range_vec: Vec<i32> = v.get(1).unwrap().split("..").collect::<Vec<&str>>().iter().map(|n| i32::from_str_radix(n, 10).unwrap()).collect();
return (xy, (*range_vec.get(0).unwrap(), *range_vec.get(1).unwrap()));
})
.collect::<Vec<(char, (i32, i32))>>()
}
fn past_range(pos: &(i32, i32), target: &Vec<(char, (i32, i32))>) -> bool {
if pos.0 > target[0].1.1 { return true; }
if pos.1 < target[1].1.0 { return true; }
return false;
}
fn in_range(pos: &(i32, i32), target: &Vec<(char, (i32, i32))>) -> bool {
let x = pos.0;
let y = pos.1;
let tx = target[0].1;
let ty = target[1].1;
x >= tx.0 && x <= tx.1 && y >= ty.0 && y <= ty.1
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn in_range_t() {
let target = vec![('x', (20, 30)), ('y', (-10, -5))];
assert_eq!(true, in_range(&(21, -10), &target));
assert_eq!(false, in_range(&(19, -10), &target));
assert_eq!(false, in_range(&(20, -11), &target));
assert_eq!(false, in_range(&(10, -11), &target));
assert_eq!(true, in_range(&(30, -5), &target));
assert_eq!(true, in_range(&(20, -5), &target));
}
#[test]
fn part_a_test_input() {
let filename = "src/day17/test-input.txt";
let input = lines_from_file(filename);
let result = part_a(&input);
assert_eq!(45, result)
}
#[test]
fn part_a_real() {
let filename = "src/day17/input.txt";
let input = lines_from_file(filename);
let result = part_a(&input);
assert_eq!(35511, result)
}
#[test]
fn part_b_test_input() {
let filename = "src/day17/test-input.txt";
let input = lines_from_file(filename);
let result = part_b(&input);
assert_eq!(112, result)
}
#[test]
fn part_b_real() {
let filename = "src/day17/input.txt";
let input = lines_from_file(filename);
let result = part_b(&input);
assert_eq!(3282, result)
}
}
|
//! Convert parser model to rust-protobuf model
use std::iter;
use crate::model;
use crate::str_lit::StrLitDecodeError;
use protobuf::Message;
#[derive(Debug)]
pub enum ConvertError {
UnsupportedOption(String),
ExtensionNotFound(String),
WrongExtensionType(String, &'static str),
UnsupportedExtensionType(String, String),
StrLitDecodeError(StrLitDecodeError),
DefaultValueIsNotStringLiteral,
WrongOptionType,
}
impl From<StrLitDecodeError> for ConvertError {
fn from(e: StrLitDecodeError) -> Self {
ConvertError::StrLitDecodeError(e)
}
}
pub type ConvertResult<T> = Result<T, ConvertError>;
trait ProtobufOptions {
fn by_name(&self, name: &str) -> Option<&model::ProtobufConstant>;
fn by_name_bool(&self, name: &str) -> ConvertResult<Option<bool>> {
match self.by_name(name) {
Some(&model::ProtobufConstant::Bool(b)) => Ok(Some(b)),
Some(_) => Err(ConvertError::WrongOptionType),
None => Ok(None),
}
}
}
impl<'a> ProtobufOptions for &'a [model::ProtobufOption] {
fn by_name(&self, name: &str) -> Option<&model::ProtobufConstant> {
let option_name = name;
for model::ProtobufOption { name, value } in *self {
if name == option_name {
return Some(value);
}
}
None
}
}
enum MessageOrEnum {
Message,
Enum,
}
impl MessageOrEnum {
fn descriptor_type(&self) -> protobuf::descriptor::FieldDescriptorProto_Type {
match *self {
MessageOrEnum::Message => protobuf::descriptor::FieldDescriptorProto_Type::TYPE_MESSAGE,
MessageOrEnum::Enum => protobuf::descriptor::FieldDescriptorProto_Type::TYPE_ENUM,
}
}
}
#[derive(Debug, Eq, PartialEq, Clone)]
struct RelativePath {
path: String,
}
impl RelativePath {
fn empty() -> RelativePath {
RelativePath::new(String::new())
}
fn new(path: String) -> RelativePath {
assert!(!path.starts_with('.'));
RelativePath { path }
}
fn is_empty(&self) -> bool {
self.path.is_empty()
}
fn _last_part(&self) -> Option<&str> {
match self.path.rfind('.') {
Some(pos) => Some(&self.path[pos + 1..]),
None => {
if self.path.is_empty() {
None
} else {
Some(&self.path)
}
}
}
}
fn parent(&self) -> Option<RelativePath> {
match self.path.rfind('.') {
Some(pos) => Some(RelativePath::new(self.path[..pos].to_owned())),
None => {
if self.path.is_empty() {
None
} else {
Some(RelativePath::empty())
}
}
}
}
fn self_and_parents(&self) -> Vec<RelativePath> {
let mut tmp = self.clone();
let mut r = vec![self.clone()];
while let Some(parent) = tmp.parent() {
r.push(parent.clone());
tmp = parent;
}
r
}
fn append(&self, simple: &str) -> RelativePath {
if self.path.is_empty() {
RelativePath::new(simple.to_owned())
} else {
RelativePath::new(format!("{}.{}", self.path, simple))
}
}
fn split_first_rem(&self) -> Option<(&str, RelativePath)> {
if self.is_empty() {
None
} else {
Some(match self.path.find('.') {
Some(dot) => (
&self.path[..dot],
RelativePath::new(self.path[dot + 1..].to_owned()),
),
None => (&self.path, RelativePath::empty()),
})
}
}
}
#[cfg(test)]
mod relative_path_test {
use super::*;
#[test]
fn parent() {
assert_eq!(None, RelativePath::empty().parent());
assert_eq!(
Some(RelativePath::empty()),
RelativePath::new("aaa".to_owned()).parent()
);
assert_eq!(
Some(RelativePath::new("abc".to_owned())),
RelativePath::new("abc.def".to_owned()).parent()
);
assert_eq!(
Some(RelativePath::new("abc.def".to_owned())),
RelativePath::new("abc.def.gh".to_owned()).parent()
);
}
#[test]
fn last_part() {
assert_eq!(None, RelativePath::empty()._last_part());
assert_eq!(
Some("aaa"),
RelativePath::new("aaa".to_owned())._last_part()
);
assert_eq!(
Some("def"),
RelativePath::new("abc.def".to_owned())._last_part()
);
assert_eq!(
Some("gh"),
RelativePath::new("abc.def.gh".to_owned())._last_part()
);
}
#[test]
fn self_and_parents() {
assert_eq!(
vec![
RelativePath::new("ab.cde.fghi".to_owned()),
RelativePath::new("ab.cde".to_owned()),
RelativePath::new("ab".to_owned()),
RelativePath::empty(),
],
RelativePath::new("ab.cde.fghi".to_owned()).self_and_parents()
);
}
}
#[derive(Clone, Eq, PartialEq, Debug)]
struct AbsolutePath {
path: String,
}
impl AbsolutePath {
fn root() -> AbsolutePath {
AbsolutePath::new(String::new())
}
fn new(path: String) -> AbsolutePath {
assert!(path.is_empty() || path.starts_with('.'));
assert!(!path.ends_with('.'));
AbsolutePath { path }
}
fn from_path_without_dot(path: &str) -> AbsolutePath {
if path.is_empty() {
AbsolutePath::root()
} else {
assert!(!path.starts_with('.'));
assert!(!path.ends_with('.'));
AbsolutePath::new(format!(".{path}"))
}
}
fn from_path_maybe_dot(path: &str) -> AbsolutePath {
if path.starts_with('.') {
AbsolutePath::new(path.to_owned())
} else {
AbsolutePath::from_path_without_dot(path)
}
}
fn push_simple(&mut self, simple: &str) {
assert!(!simple.is_empty());
assert!(!simple.contains('.'));
self.path.push('.');
self.path.push_str(simple);
}
fn push_relative(&mut self, relative: &RelativePath) {
if !relative.is_empty() {
self.path.push('.');
self.path.push_str(&relative.path);
}
}
fn remove_prefix(&self, prefix: &AbsolutePath) -> Option<RelativePath> {
if self.path.starts_with(&prefix.path) {
let rem = &self.path[prefix.path.len()..];
if rem.is_empty() {
return Some(RelativePath::empty());
}
if let Some(stripped) = rem.strip_prefix('.') {
return Some(RelativePath::new(stripped.to_string()));
}
}
None
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn absolute_path_push_simple() {
let mut foo = AbsolutePath::new(".foo".to_owned());
foo.push_simple("bar");
assert_eq!(AbsolutePath::new(".foo.bar".to_owned()), foo);
let mut foo = AbsolutePath::root();
foo.push_simple("bar");
assert_eq!(AbsolutePath::new(".bar".to_owned()), foo);
}
#[test]
fn absolute_path_remove_prefix() {
assert_eq!(
Some(RelativePath::empty()),
AbsolutePath::new(".foo".to_owned())
.remove_prefix(&AbsolutePath::new(".foo".to_owned()))
);
assert_eq!(
Some(RelativePath::new("bar".to_owned())),
AbsolutePath::new(".foo.bar".to_owned())
.remove_prefix(&AbsolutePath::new(".foo".to_owned()))
);
assert_eq!(
Some(RelativePath::new("baz.qux".to_owned())),
AbsolutePath::new(".foo.bar.baz.qux".to_owned())
.remove_prefix(&AbsolutePath::new(".foo.bar".to_owned()))
);
assert_eq!(
None,
AbsolutePath::new(".foo.barbaz".to_owned())
.remove_prefix(&AbsolutePath::new(".foo.bar".to_owned()))
);
}
}
enum LookupScope<'a> {
File(&'a model::FileDescriptor),
Message(&'a model::Message),
}
impl<'a> LookupScope<'a> {
fn messages(&self) -> &[model::Message] {
match *self {
LookupScope::File(file) => &file.messages,
LookupScope::Message(messasge) => &messasge.messages,
}
}
fn find_message(&self, simple_name: &str) -> Option<&model::Message> {
self.messages().iter().find(|m| m.name == simple_name)
}
fn enums(&self) -> &[model::Enumeration] {
match *self {
LookupScope::File(file) => &file.enums,
LookupScope::Message(messasge) => &messasge.enums,
}
}
fn members(&self) -> Vec<(&str, MessageOrEnum)> {
let mut r = Vec::new();
r.extend(
self.enums()
.iter()
.map(|e| (&e.name[..], MessageOrEnum::Enum)),
);
r.extend(
self.messages()
.iter()
.map(|e| (&e.name[..], MessageOrEnum::Message)),
);
r
}
fn find_member(&self, simple_name: &str) -> Option<MessageOrEnum> {
self.members()
.into_iter()
.filter_map(|(member_name, message_or_enum)| {
if member_name == simple_name {
Some(message_or_enum)
} else {
None
}
})
.next()
}
fn resolve_message_or_enum(
&self,
current_path: &AbsolutePath,
path: &RelativePath,
) -> Option<(AbsolutePath, MessageOrEnum)> {
let (first, rem) = match path.split_first_rem() {
Some(x) => x,
None => return None,
};
if rem.is_empty() {
match self.find_member(first) {
Some(message_or_enum) => {
let mut result_path = current_path.clone();
result_path.push_simple(first);
Some((result_path, message_or_enum))
}
None => None,
}
} else {
match self.find_message(first) {
Some(message) => {
let mut message_path = current_path.clone();
message_path.push_simple(&message.name);
let message_scope = LookupScope::Message(message);
message_scope.resolve_message_or_enum(&message_path, &rem)
}
None => None,
}
}
}
}
struct Resolver<'a> {
current_file: &'a model::FileDescriptor,
deps: &'a [model::FileDescriptor],
}
impl<'a> Resolver<'a> {
fn map_entry_name_for_field_name(field_name: &str) -> String {
format!("{field_name}_MapEntry")
}
fn map_entry_field(
&self,
name: &str,
number: i32,
field_type: &model::FieldType,
path_in_file: &RelativePath,
) -> protobuf::descriptor::FieldDescriptorProto {
let mut output = protobuf::descriptor::FieldDescriptorProto::new();
output.set_name(name.to_owned());
output.set_number(number);
let (t, t_name) = self.field_type(name, field_type, path_in_file);
output.set_field_type(t);
if let Some(t_name) = t_name {
output.set_type_name(t_name.path);
}
output
}
fn map_entry_message(
&self,
field_name: &str,
key: &model::FieldType,
value: &model::FieldType,
path_in_file: &RelativePath,
) -> ConvertResult<protobuf::descriptor::DescriptorProto> {
let mut output = protobuf::descriptor::DescriptorProto::new();
output.mut_options().set_map_entry(true);
output.set_name(Resolver::map_entry_name_for_field_name(field_name));
output
.mut_field()
.push(self.map_entry_field("key", 1, key, path_in_file));
output
.mut_field()
.push(self.map_entry_field("value", 2, value, path_in_file));
Ok(output)
}
fn message_options(
&self,
input: &[model::ProtobufOption],
) -> ConvertResult<protobuf::descriptor::MessageOptions> {
let mut r = protobuf::descriptor::MessageOptions::new();
self.custom_options(
input,
"google.protobuf.MessageOptions",
r.mut_unknown_fields(),
)?;
Ok(r)
}
fn message(
&self,
input: &model::Message,
path_in_file: &RelativePath,
) -> ConvertResult<protobuf::descriptor::DescriptorProto> {
let nested_path_in_file = path_in_file.append(&input.name);
let mut output = protobuf::descriptor::DescriptorProto::new();
output.set_name(input.name.clone());
let mut nested_messages = protobuf::RepeatedField::new();
for m in &input.messages {
nested_messages.push(self.message(m, &nested_path_in_file)?);
}
for f in &input.fields {
if let model::FieldType::Map(ref t) = f.typ {
nested_messages.push(self.map_entry_message(&f.name, &t.0, &t.1, path_in_file)?);
}
}
output.set_nested_type(nested_messages);
output.set_enum_type(
input
.enums
.iter()
.map(|e| self.enumeration(e))
.collect::<Result<_, _>>()?,
);
{
let mut fields = protobuf::RepeatedField::new();
for f in &input.fields {
fields.push(self.field(f, None, &nested_path_in_file)?);
}
for (oneof_index, oneof) in input.oneofs.iter().enumerate() {
let oneof_index = oneof_index as i32;
for f in &oneof.fields {
fields.push(self.field(f, Some(oneof_index), &nested_path_in_file)?);
}
}
output.set_field(fields);
}
let oneofs = input.oneofs.iter().map(|o| self.oneof(o)).collect();
output.set_oneof_decl(oneofs);
output.set_options(self.message_options(&input.options)?);
Ok(output)
}
fn service_options(
&self,
input: &[model::ProtobufOption],
) -> ConvertResult<protobuf::descriptor::ServiceOptions> {
let mut r = protobuf::descriptor::ServiceOptions::new();
self.custom_options(
input,
"google.protobuf.ServiceOptions",
r.mut_unknown_fields(),
)?;
Ok(r)
}
fn method_options(
&self,
input: &[model::ProtobufOption],
) -> ConvertResult<protobuf::descriptor::MethodOptions> {
let mut r = protobuf::descriptor::MethodOptions::new();
self.custom_options(
input,
"google.protobuf.MethodOptions",
r.mut_unknown_fields(),
)?;
Ok(r)
}
fn service(
&self,
input: &model::Service,
package: &str,
) -> ConvertResult<protobuf::descriptor::ServiceDescriptorProto> {
let mut output = protobuf::descriptor::ServiceDescriptorProto::new();
output.set_name(input.name.clone());
let mut methods = protobuf::RepeatedField::new();
for m in &input.methods {
let mut mm = protobuf::descriptor::MethodDescriptorProto::new();
mm.set_name(m.name.clone());
mm.set_input_type(to_protobuf_absolute_path(package, m.input_type.clone()));
mm.set_output_type(to_protobuf_absolute_path(package, m.output_type.clone()));
mm.set_client_streaming(m.client_streaming);
mm.set_server_streaming(m.server_streaming);
mm.set_options(self.method_options(&m.options)?);
methods.push(mm);
}
output.set_method(methods);
output.set_options(self.service_options(&input.options)?);
Ok(output)
}
fn custom_options(
&self,
input: &[model::ProtobufOption],
extendee: &'static str,
unknown_fields: &mut protobuf::UnknownFields,
) -> ConvertResult<()> {
for option in input {
// TODO: builtin options too
if !option.name.starts_with('(') {
continue;
}
let extension = match self.find_extension(&option.name) {
Ok(e) => e,
// TODO: return error
Err(_) => continue,
};
if extension.extendee != extendee {
return Err(ConvertError::WrongExtensionType(
option.name.clone(),
extendee,
));
}
let value = match Resolver::option_value_to_unknown_value(
&option.value,
&extension.field.typ,
&option.name,
) {
Ok(value) => value,
Err(_) => {
// TODO: return error
continue;
}
};
unknown_fields.add_value(extension.field.number as u32, value);
}
Ok(())
}
fn field_options(
&self,
input: &[model::ProtobufOption],
) -> ConvertResult<protobuf::descriptor::FieldOptions> {
let mut r = protobuf::descriptor::FieldOptions::new();
if let Some(deprecated) = input.by_name_bool("deprecated")? {
r.set_deprecated(deprecated);
}
if let Some(packed) = input.by_name_bool("packed")? {
r.set_packed(packed);
}
self.custom_options(
input,
"google.protobuf.FieldOptions",
r.mut_unknown_fields(),
)?;
Ok(r)
}
fn field(
&self,
input: &model::Field,
oneof_index: Option<i32>,
path_in_file: &RelativePath,
) -> ConvertResult<protobuf::descriptor::FieldDescriptorProto> {
let mut output = protobuf::descriptor::FieldDescriptorProto::new();
output.set_name(input.name.clone());
if let model::FieldType::Map(..) = input.typ {
output.set_label(protobuf::descriptor::FieldDescriptorProto_Label::LABEL_REPEATED);
} else {
output.set_label(label(input.rule));
}
let (t, t_name) = self.field_type(&input.name, &input.typ, path_in_file);
output.set_field_type(t);
if let Some(t_name) = t_name {
output.set_type_name(t_name.path);
}
output.set_number(input.number);
if let Some(default) = input.options.as_slice().by_name("default") {
let default = match output.get_field_type() {
protobuf::descriptor::FieldDescriptorProto_Type::TYPE_STRING => {
if let model::ProtobufConstant::String(ref s) = *default {
s.decode_utf8()?
} else {
return Err(ConvertError::DefaultValueIsNotStringLiteral);
}
}
protobuf::descriptor::FieldDescriptorProto_Type::TYPE_BYTES => {
if let model::ProtobufConstant::String(ref s) = *default {
s.escaped.clone()
} else {
return Err(ConvertError::DefaultValueIsNotStringLiteral);
}
}
_ => default.format(),
};
output.set_default_value(default);
}
output.set_options(self.field_options(&input.options)?);
if let Some(oneof_index) = oneof_index {
output.set_oneof_index(oneof_index);
}
Ok(output)
}
fn all_files(&self) -> Vec<&model::FileDescriptor> {
iter::once(self.current_file).chain(self.deps).collect()
}
fn package_files(&self, package: &str) -> Vec<&model::FileDescriptor> {
self.all_files()
.into_iter()
.filter(|f| f.package == package)
.collect()
}
fn current_file_package_files(&self) -> Vec<&model::FileDescriptor> {
self.package_files(&self.current_file.package)
}
fn resolve_message_or_enum(
&self,
name: &str,
path_in_file: &RelativePath,
) -> (AbsolutePath, MessageOrEnum) {
// find message or enum in current package
if !name.starts_with('.') {
for p in path_in_file.self_and_parents() {
let relative_path_with_name = p.clone();
let relative_path_with_name = relative_path_with_name.append(name);
for file in self.current_file_package_files() {
if let Some((n, t)) = LookupScope::File(file).resolve_message_or_enum(
&AbsolutePath::from_path_without_dot(&file.package),
&relative_path_with_name,
) {
return (n, t);
}
}
}
}
// find message or enum in root package
{
let absolute_path = AbsolutePath::from_path_maybe_dot(name);
for file in self.all_files() {
let file_package = AbsolutePath::from_path_without_dot(&file.package);
if let Some(relative) = absolute_path.remove_prefix(&file_package) {
if let Some((n, t)) =
LookupScope::File(file).resolve_message_or_enum(&file_package, &relative)
{
return (n, t);
}
}
}
}
panic!(
"couldn't find message or enum {} when parsing {}",
name, self.current_file.package
);
}
fn field_type(
&self,
name: &str,
input: &model::FieldType,
path_in_file: &RelativePath,
) -> (
protobuf::descriptor::FieldDescriptorProto_Type,
Option<AbsolutePath>,
) {
match *input {
model::FieldType::Bool => (
protobuf::descriptor::FieldDescriptorProto_Type::TYPE_BOOL,
None,
),
model::FieldType::Int32 => (
protobuf::descriptor::FieldDescriptorProto_Type::TYPE_INT32,
None,
),
model::FieldType::Int64 => (
protobuf::descriptor::FieldDescriptorProto_Type::TYPE_INT64,
None,
),
model::FieldType::Uint32 => (
protobuf::descriptor::FieldDescriptorProto_Type::TYPE_UINT32,
None,
),
model::FieldType::Uint64 => (
protobuf::descriptor::FieldDescriptorProto_Type::TYPE_UINT64,
None,
),
model::FieldType::Sint32 => (
protobuf::descriptor::FieldDescriptorProto_Type::TYPE_SINT32,
None,
),
model::FieldType::Sint64 => (
protobuf::descriptor::FieldDescriptorProto_Type::TYPE_SINT64,
None,
),
model::FieldType::Fixed32 => (
protobuf::descriptor::FieldDescriptorProto_Type::TYPE_FIXED32,
None,
),
model::FieldType::Fixed64 => (
protobuf::descriptor::FieldDescriptorProto_Type::TYPE_FIXED64,
None,
),
model::FieldType::Sfixed32 => (
protobuf::descriptor::FieldDescriptorProto_Type::TYPE_SFIXED32,
None,
),
model::FieldType::Sfixed64 => (
protobuf::descriptor::FieldDescriptorProto_Type::TYPE_SFIXED64,
None,
),
model::FieldType::Float => (
protobuf::descriptor::FieldDescriptorProto_Type::TYPE_FLOAT,
None,
),
model::FieldType::Double => (
protobuf::descriptor::FieldDescriptorProto_Type::TYPE_DOUBLE,
None,
),
model::FieldType::String => (
protobuf::descriptor::FieldDescriptorProto_Type::TYPE_STRING,
None,
),
model::FieldType::Bytes => (
protobuf::descriptor::FieldDescriptorProto_Type::TYPE_BYTES,
None,
),
model::FieldType::MessageOrEnum(ref name) => {
let (name, me) = self.resolve_message_or_enum(name, path_in_file);
(me.descriptor_type(), Some(name))
}
model::FieldType::Map(..) => {
let mut type_name = AbsolutePath::from_path_without_dot(&self.current_file.package);
type_name.push_relative(path_in_file);
type_name.push_simple(&Resolver::map_entry_name_for_field_name(name));
(
protobuf::descriptor::FieldDescriptorProto_Type::TYPE_MESSAGE,
Some(type_name),
)
}
model::FieldType::Group(..) => (
protobuf::descriptor::FieldDescriptorProto_Type::TYPE_GROUP,
None,
),
}
}
fn enum_value(
&self,
name: &str,
number: i32,
) -> protobuf::descriptor::EnumValueDescriptorProto {
let mut output = protobuf::descriptor::EnumValueDescriptorProto::new();
output.set_name(name.to_owned());
output.set_number(number);
output
}
fn enum_options(
&self,
input: &[model::ProtobufOption],
) -> ConvertResult<protobuf::descriptor::EnumOptions> {
let mut r = protobuf::descriptor::EnumOptions::new();
if let Some(allow_alias) = input.by_name_bool("allow_alias")? {
r.set_allow_alias(allow_alias);
}
if let Some(deprecated) = input.by_name_bool("deprecated")? {
r.set_deprecated(deprecated);
}
self.custom_options(input, "google.protobuf.EnumOptions", r.mut_unknown_fields())?;
Ok(r)
}
fn enumeration(
&self,
input: &model::Enumeration,
) -> ConvertResult<protobuf::descriptor::EnumDescriptorProto> {
let mut output = protobuf::descriptor::EnumDescriptorProto::new();
output.set_name(input.name.clone());
output.set_value(
input
.values
.iter()
.map(|v| self.enum_value(&v.name, v.number))
.collect(),
);
output.set_options(self.enum_options(&input.options)?);
Ok(output)
}
fn oneof(&self, input: &model::OneOf) -> protobuf::descriptor::OneofDescriptorProto {
let mut output = protobuf::descriptor::OneofDescriptorProto::new();
output.set_name(input.name.clone());
output
}
fn find_extension_by_path(&self, path: &str) -> ConvertResult<&model::Extension> {
let (package, name) = match path.rfind('.') {
Some(dot) => (&path[..dot], &path[dot + 1..]),
None => (self.current_file.package.as_str(), path),
};
for file in self.package_files(package) {
for ext in &file.extensions {
if ext.field.name == name {
return Ok(ext);
}
}
}
Err(ConvertError::ExtensionNotFound(path.to_owned()))
}
fn find_extension(&self, option_name: &str) -> ConvertResult<&model::Extension> {
if !option_name.starts_with('(') || !option_name.ends_with(')') {
return Err(ConvertError::UnsupportedOption(option_name.to_owned()));
}
let path = &option_name[1..option_name.len() - 1];
self.find_extension_by_path(path)
}
fn option_value_to_unknown_value(
value: &model::ProtobufConstant,
field_type: &model::FieldType,
option_name: &str,
) -> ConvertResult<protobuf::UnknownValue> {
let v = match *value {
model::ProtobufConstant::Bool(b) => {
if field_type != &model::FieldType::Bool {
Err(())
} else {
Ok(protobuf::UnknownValue::Varint(u64::from(b)))
}
}
// TODO: check overflow
model::ProtobufConstant::U64(v) => match *field_type {
model::FieldType::Fixed64 | model::FieldType::Sfixed64 => {
Ok(protobuf::UnknownValue::Fixed64(v))
}
model::FieldType::Fixed32 | model::FieldType::Sfixed32 => {
Ok(protobuf::UnknownValue::Fixed32(v as u32))
}
model::FieldType::Int64
| model::FieldType::Int32
| model::FieldType::Uint64
| model::FieldType::Uint32 => Ok(protobuf::UnknownValue::Varint(v)),
model::FieldType::Sint64 => Ok(protobuf::UnknownValue::sint64(v as i64)),
model::FieldType::Sint32 => Ok(protobuf::UnknownValue::sint32(v as i32)),
_ => Err(()),
},
model::ProtobufConstant::I64(v) => match *field_type {
model::FieldType::Fixed64 | model::FieldType::Sfixed64 => {
Ok(protobuf::UnknownValue::Fixed64(v as u64))
}
model::FieldType::Fixed32 | model::FieldType::Sfixed32 => {
Ok(protobuf::UnknownValue::Fixed32(v as u32))
}
model::FieldType::Int64
| model::FieldType::Int32
| model::FieldType::Uint64
| model::FieldType::Uint32 => Ok(protobuf::UnknownValue::Varint(v as u64)),
model::FieldType::Sint64 => Ok(protobuf::UnknownValue::sint64(v)),
model::FieldType::Sint32 => Ok(protobuf::UnknownValue::sint32(v as i32)),
_ => Err(()),
},
model::ProtobufConstant::F64(f) => match *field_type {
model::FieldType::Float => {
Ok(protobuf::UnknownValue::Fixed32((f as f32).to_bits()))
}
model::FieldType::Double => Ok(protobuf::UnknownValue::Fixed64(f.to_bits())),
_ => Err(()),
},
model::ProtobufConstant::String(ref s) => {
match *field_type {
model::FieldType::String => Ok(protobuf::UnknownValue::LengthDelimited(
s.decode_utf8()?.into_bytes(),
)),
// TODO: bytes
_ => Err(()),
}
}
_ => Err(()),
};
v.map_err(|()| {
ConvertError::UnsupportedExtensionType(
option_name.to_owned(),
format!("{field_type:?}"),
)
})
}
fn file_options(
&self,
input: &[model::ProtobufOption],
) -> ConvertResult<protobuf::descriptor::FileOptions> {
let mut r = protobuf::descriptor::FileOptions::new();
self.custom_options(input, "google.protobuf.FileOptions", r.mut_unknown_fields())?;
Ok(r)
}
fn extension(
&self,
input: &model::Extension,
) -> ConvertResult<protobuf::descriptor::FieldDescriptorProto> {
let relative_path = RelativePath::new("".to_owned());
let mut field = self.field(&input.field, None, &relative_path)?;
field.set_extendee(
self.resolve_message_or_enum(&input.extendee, &relative_path)
.0
.path,
);
Ok(field)
}
}
fn to_protobuf_absolute_path(package: &str, path: String) -> String {
if !path.starts_with('.') {
if path.contains('.') {
return format!(".{}", &path);
} else {
return format!(".{}.{}", package, &path);
}
}
path
}
fn syntax(input: model::Syntax) -> String {
match input {
model::Syntax::Proto2 => "proto2".to_owned(),
model::Syntax::Proto3 => "proto3".to_owned(),
}
}
fn label(input: model::Rule) -> protobuf::descriptor::FieldDescriptorProto_Label {
match input {
model::Rule::Optional => protobuf::descriptor::FieldDescriptorProto_Label::LABEL_OPTIONAL,
model::Rule::Required => protobuf::descriptor::FieldDescriptorProto_Label::LABEL_REQUIRED,
model::Rule::Repeated => protobuf::descriptor::FieldDescriptorProto_Label::LABEL_REPEATED,
}
}
pub fn file_descriptor(
name: String,
input: &model::FileDescriptor,
deps: &[model::FileDescriptor],
) -> ConvertResult<protobuf::descriptor::FileDescriptorProto> {
let resolver = Resolver {
current_file: input,
deps,
};
let mut output = protobuf::descriptor::FileDescriptorProto::new();
output.set_name(name);
output.set_package(input.package.clone());
output.set_syntax(syntax(input.syntax));
let mut messages = protobuf::RepeatedField::new();
for m in &input.messages {
messages.push(resolver.message(m, &RelativePath::empty())?);
}
output.set_message_type(messages);
let mut services = protobuf::RepeatedField::new();
for s in &input.services {
services.push(resolver.service(s, &input.package)?);
}
output.set_service(services);
output.set_enum_type(
input
.enums
.iter()
.map(|e| resolver.enumeration(e))
.collect::<Result<_, _>>()?,
);
output.set_options(resolver.file_options(&input.options)?);
let mut extensions = protobuf::RepeatedField::new();
for e in &input.extensions {
extensions.push(resolver.extension(e)?);
}
output.set_extension(extensions);
Ok(output)
}
|
#![feature(nll)]
#![cfg_attr(feature = "cargo-clippy", allow(print_literal))]
extern crate actix;
extern crate byteorder;
extern crate bytes;
extern crate futures;
extern crate rand;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate tokio;
extern crate tokio_codec;
extern crate tokio_io;
extern crate tokio_tcp;
#[macro_use]
extern crate clap;
#[macro_use]
extern crate log;
extern crate chrono;
extern crate config;
extern crate fern;
#[macro_use]
extern crate nom;
extern crate actix_web;
extern crate chashmap;
extern crate num_traits;
extern crate quickxml_to_serde;
mod json_diff;
mod networking;
mod settings;
mod types;
mod ws;
mod ws_ads;
mod xml_to_struct;
use actix::Actor;
use actix_web::{server, App, HttpRequest, Responder};
use futures::future::Future;
use networking::ToPlcConn;
use std::path::Path;
use std::sync::{Arc, RwLock};
use ws_ads::AdsStructMap;
#[inline(always)]
fn file_exists<T: AsRef<Path>>(path: T) -> bool {
path.as_ref().exists() && path.as_ref().is_file()
}
#[inline(always)]
#[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
fn index(info: HttpRequest<Arc<ws::WsState>>) -> impl Responder {
serde_json::to_string_pretty(&*info.state().config())
}
fn init_st_ads_to_bc<T: ToString + serde_json::value::Index>(
version: &types::AdsVersion,
k: &T,
d: &mut serde_json::Value,
) -> Vec<u8> {
let key_guard: &String = &*version.search_index.get(&k.to_string()).unwrap();
let value: &types::AdsType = &*version.map.get(&*key_guard).unwrap();
let v = vec![0u8; value.len() as usize];
let data = value.as_data_struct(&mut &v[..], &version.map);
d[k] = data;
v
}
fn main() {
let system = actix::System::new("adsserver");
let matches: clap::ArgMatches = clap_app!(adsserver =>
(version: "1.0")
(author: "Lukas Binder")
(about: "rust ads server")
(@arg CONFIG: -c #{1,2} "Sets a custom config file")
(@arg INPUT: "Sets the input directory to use")
(@arg debug: -v ... "Sets the level of debugging information")
).get_matches();
let log_level = match matches.occurrences_of("debug") {
0 => (log::LevelFilter::Error, log::LevelFilter::Warn),
1 => (log::LevelFilter::Info, log::LevelFilter::Debug),
2 | _ => (log::LevelFilter::Trace, log::LevelFilter::Trace),
};
fern::Dispatch::new()
.format(|out, message, record| {
out.finish(format_args!(
"{}[{}][{}] {}",
chrono::Local::now().format("[%d.%m.%Y/%H:%M:%S]"),
record.target(),
record.level(),
message
))
})
.chain(
fern::Dispatch::new()
.level(log_level.0)
.chain(std::io::stdout()),
)
.chain(
fern::Dispatch::new()
.level(log_level.1)
.chain(fern::log_file("adsserver.log").unwrap()),
)
.apply()
.unwrap();
let mut settings = config::Config::default();
let config_file = matches.value_of("CONFIG").unwrap_or("config.json");
settings
.merge(config::File::with_name(config_file))
.unwrap()
.merge(config::Environment::with_prefix("APP"))
.unwrap();
let config = settings.try_into::<settings::Setting>().unwrap();
let sps_types: chashmap::CHashMap<u32, _> = config
.versions
.iter()
.filter_map(|version| {
let p: &Path = version.1.path.as_ref();
if file_exists(&p) {
let u: u32 = version.0.into();
Some((u, Arc::new(xml_to_struct::read_tpy(version.1))))
} else {
error!("version file {:?} does not exist", p);
None
}
})
.collect();
let sender: chashmap::CHashMap<_, _> = config
.plc
.iter()
.map(move |plc| {
let version = &*sps_types.get(&plc.version).expect("unknown version");
let mkey = version
.search_index
.get(&"ST_ADS_TO_BC".to_string())
.unwrap();
let rkey = version
.search_index
.get(&"ST_RETAIN_DATA".to_string())
.unwrap();
let m = AdsStructMap {
st_ads_to_bc: version.symbols.get(&*mkey).unwrap().clone(),
st_retain_data: version.symbols.get(&*rkey).unwrap().clone(),
};
let mut data = serde_json::Value::Object(serde_json::Map::new());
let mem = ws_ads::AdsMemory {
ST_ADS_TO_BC: init_st_ads_to_bc(&version, &"ST_ADS_TO_BC", &mut data),
ST_ADS_FROM_BC: init_st_ads_to_bc(&version, &"ST_ADS_FROM_BC", &mut data),
ST_RETAIN_DATA: init_st_ads_to_bc(&version, &"ST_RETAIN_DATA", &mut data),
data,
};
let conn = (plc.ams_net_id.clone(), plc.ams_port).as_plc_conn();
let client_addr = networking::create_client(
(plc.ip.as_str(), 48898),
&conn,
&("172.16.21.2.1.1", 801),
).wait()
.unwrap();
(
conn,
ws_ads::AdsToWsMultiplexer::new(client_addr, mem, version.clone(), m).start(),
)
})
.collect();
let ws_state = Arc::new(ws::WsState::new(RwLock::new(config.plc), sender));
server::new(move || {
App::with_state(ws_state.clone())
.middleware(actix_web::middleware::Logger::default())
.resource("/ws/{net_id}/{port}/", |r| r.with(ws::Ws::ws_index))
.resource("/", |r| r.with(index))
}).bind("127.0.0.1:8000")
.unwrap()
.start();
let _ = system.run();
}
|
extern crate mirage;
use mirage::convert::svg;
use mirage::raster::{
Image,
PixelType
};
static SVG: &str = include_str!("rect.svg");
fn main()
{
let surface = svg::into::string(SVG).unwrap();
let mut image = Image::new("pic.png", 100, 100, PixelType::Rgb);
image.write(&surface);
image.save();
}
|
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LocalizableString {
pub value: String,
#[serde(rename = "localizedValue", default, skip_serializing_if = "Option::is_none")]
pub localized_value: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BaselineMetadataValue {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<LocalizableString>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorResponse {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BaselineResponse {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<LocalizableString>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<BaselineProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BaselineProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub timespan: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub interval: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub aggregation: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub timestamps: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub baseline: Vec<Baseline>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub metadata: Vec<BaselineMetadataValue>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Baseline {
pub sensitivity: baseline::Sensitivity,
#[serde(rename = "lowThresholds")]
pub low_thresholds: Vec<f64>,
#[serde(rename = "highThresholds")]
pub high_thresholds: Vec<f64>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub timestamps: Vec<String>,
}
pub mod baseline {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Sensitivity {
Low,
Medium,
High,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TimeSeriesInformation {
pub sensitivities: Vec<String>,
pub values: Vec<f64>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub timestamps: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CalculateBaselineResponse {
#[serde(rename = "type")]
pub type_: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub timestamps: Vec<String>,
pub baseline: Vec<Baseline>,
}
|
#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Debug)]
pub enum Opcode {
IConst,
FConst,
Move,
Load,
Store,
Call(CallConv, u32),
AddOvfUI,
SubOvfUI,
MulOVfUI,
AddOvfI,
SubOvfI,
MulOvfI,
AddUI,
AddI,
SubUI,
SubI,
DivUI,
DivI,
MulUI,
MulI,
ModUI,
ModI,
RemI,
RemF,
RemD,
DivF,
DivD,
ModF,
ModD,
OrI,
OrUI,
AndI,
AndUI,
XorI,
XorUI,
LShiftUI,
LShiftI,
RShiftUI,
RShiftI,
/* value operations */
ValueAdd,
ValueSub,
ValueDiv,
ValueMul,
ValueMod,
ValueRem,
ValueLShift,
ValueRShift,
ValueURShift,
ValueBitAnd,
ValueBitOr,
ValueBitXor,
ValueCompare(Condition),
Compare(Condition),
/// Guards used in optimizing and tracing jit, all guards have index to baseline JIT code map.
GuardInt32(u32),
GuardAnyNum(u32),
GuardNum(u32),
GuardArray(u32),
GuardString(u32),
GuardObject(u32),
GuardZero(u32),
GuardNonZero(u32),
GuardType(u32, super::Type),
/// Guard fails if condition is true
GuardCmp(Condition, u32),
/// Guard fails if condition is false
GuardNCmp(Condition, u32),
}
#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Debug)]
pub enum Condition {
UnsignedLess,
UnsignedGreater,
UnsignedLessOrEqual,
UnsignedGreaterOrEqual,
Equal,
NotEqual,
Greater,
GreaterOrEqual,
Less,
LessOrEqual,
}
#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Debug)]
pub enum CallConv {
SystemV,
Win64,
FastCall,
}
/// Instruction executed at end of all basic blocks
#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Debug)]
pub enum Terminator {
Branch(u32),
ConditionalBranch(Condition, u32, u32),
TailCall(CallConv, u32),
}
|
#[doc = "Reader of register INTR"]
pub type R = crate::R<u32, super::INTR>;
#[doc = "Writer for register INTR"]
pub type W = crate::W<u32, super::INTR>;
#[doc = "Register INTR `reset()`'s with value 0"]
impl crate::ResetValue for super::INTR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `EDGE0`"]
pub type EDGE0_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `EDGE0`"]
pub struct EDGE0_W<'a> {
w: &'a mut W,
}
impl<'a> EDGE0_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) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Reader of field `EDGE1`"]
pub type EDGE1_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `EDGE1`"]
pub struct EDGE1_W<'a> {
w: &'a mut W,
}
impl<'a> EDGE1_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 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Reader of field `EDGE2`"]
pub type EDGE2_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `EDGE2`"]
pub struct EDGE2_W<'a> {
w: &'a mut W,
}
impl<'a> EDGE2_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 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Reader of field `EDGE3`"]
pub type EDGE3_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `EDGE3`"]
pub struct EDGE3_W<'a> {
w: &'a mut W,
}
impl<'a> EDGE3_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 << 3)) | (((value as u32) & 0x01) << 3);
self.w
}
}
#[doc = "Reader of field `EDGE4`"]
pub type EDGE4_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `EDGE4`"]
pub struct EDGE4_W<'a> {
w: &'a mut W,
}
impl<'a> EDGE4_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 << 4)) | (((value as u32) & 0x01) << 4);
self.w
}
}
#[doc = "Reader of field `EDGE5`"]
pub type EDGE5_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `EDGE5`"]
pub struct EDGE5_W<'a> {
w: &'a mut W,
}
impl<'a> EDGE5_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 << 5)) | (((value as u32) & 0x01) << 5);
self.w
}
}
#[doc = "Reader of field `EDGE6`"]
pub type EDGE6_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `EDGE6`"]
pub struct EDGE6_W<'a> {
w: &'a mut W,
}
impl<'a> EDGE6_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 << 6)) | (((value as u32) & 0x01) << 6);
self.w
}
}
#[doc = "Reader of field `EDGE7`"]
pub type EDGE7_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `EDGE7`"]
pub struct EDGE7_W<'a> {
w: &'a mut W,
}
impl<'a> EDGE7_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 << 7)) | (((value as u32) & 0x01) << 7);
self.w
}
}
#[doc = "Reader of field `FLT_EDGE`"]
pub type FLT_EDGE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `FLT_EDGE`"]
pub struct FLT_EDGE_W<'a> {
w: &'a mut W,
}
impl<'a> FLT_EDGE_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 << 8)) | (((value as u32) & 0x01) << 8);
self.w
}
}
#[doc = "Reader of field `IN_IN0`"]
pub type IN_IN0_R = crate::R<bool, bool>;
#[doc = "Reader of field `IN_IN1`"]
pub type IN_IN1_R = crate::R<bool, bool>;
#[doc = "Reader of field `IN_IN2`"]
pub type IN_IN2_R = crate::R<bool, bool>;
#[doc = "Reader of field `IN_IN3`"]
pub type IN_IN3_R = crate::R<bool, bool>;
#[doc = "Reader of field `IN_IN4`"]
pub type IN_IN4_R = crate::R<bool, bool>;
#[doc = "Reader of field `IN_IN5`"]
pub type IN_IN5_R = crate::R<bool, bool>;
#[doc = "Reader of field `IN_IN6`"]
pub type IN_IN6_R = crate::R<bool, bool>;
#[doc = "Reader of field `IN_IN7`"]
pub type IN_IN7_R = crate::R<bool, bool>;
#[doc = "Reader of field `FLT_IN_IN`"]
pub type FLT_IN_IN_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - Edge detect for IO pin 0 '0': No edge was detected on pin. '1': An edge was detected on pin."]
#[inline(always)]
pub fn edge0(&self) -> EDGE0_R {
EDGE0_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - Edge detect for IO pin 1"]
#[inline(always)]
pub fn edge1(&self) -> EDGE1_R {
EDGE1_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - Edge detect for IO pin 2"]
#[inline(always)]
pub fn edge2(&self) -> EDGE2_R {
EDGE2_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - Edge detect for IO pin 3"]
#[inline(always)]
pub fn edge3(&self) -> EDGE3_R {
EDGE3_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - Edge detect for IO pin 4"]
#[inline(always)]
pub fn edge4(&self) -> EDGE4_R {
EDGE4_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - Edge detect for IO pin 5"]
#[inline(always)]
pub fn edge5(&self) -> EDGE5_R {
EDGE5_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - Edge detect for IO pin 6"]
#[inline(always)]
pub fn edge6(&self) -> EDGE6_R {
EDGE6_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 7 - Edge detect for IO pin 7"]
#[inline(always)]
pub fn edge7(&self) -> EDGE7_R {
EDGE7_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 8 - Edge detected on filtered pin selected by INTR_CFG.FLT_SEL"]
#[inline(always)]
pub fn flt_edge(&self) -> FLT_EDGE_R {
FLT_EDGE_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 16 - IO pin state for pin 0"]
#[inline(always)]
pub fn in_in0(&self) -> IN_IN0_R {
IN_IN0_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bit 17 - IO pin state for pin 1"]
#[inline(always)]
pub fn in_in1(&self) -> IN_IN1_R {
IN_IN1_R::new(((self.bits >> 17) & 0x01) != 0)
}
#[doc = "Bit 18 - IO pin state for pin 2"]
#[inline(always)]
pub fn in_in2(&self) -> IN_IN2_R {
IN_IN2_R::new(((self.bits >> 18) & 0x01) != 0)
}
#[doc = "Bit 19 - IO pin state for pin 3"]
#[inline(always)]
pub fn in_in3(&self) -> IN_IN3_R {
IN_IN3_R::new(((self.bits >> 19) & 0x01) != 0)
}
#[doc = "Bit 20 - IO pin state for pin 4"]
#[inline(always)]
pub fn in_in4(&self) -> IN_IN4_R {
IN_IN4_R::new(((self.bits >> 20) & 0x01) != 0)
}
#[doc = "Bit 21 - IO pin state for pin 5"]
#[inline(always)]
pub fn in_in5(&self) -> IN_IN5_R {
IN_IN5_R::new(((self.bits >> 21) & 0x01) != 0)
}
#[doc = "Bit 22 - IO pin state for pin 6"]
#[inline(always)]
pub fn in_in6(&self) -> IN_IN6_R {
IN_IN6_R::new(((self.bits >> 22) & 0x01) != 0)
}
#[doc = "Bit 23 - IO pin state for pin 7"]
#[inline(always)]
pub fn in_in7(&self) -> IN_IN7_R {
IN_IN7_R::new(((self.bits >> 23) & 0x01) != 0)
}
#[doc = "Bit 24 - Filtered pin state for pin selected by INTR_CFG.FLT_SEL"]
#[inline(always)]
pub fn flt_in_in(&self) -> FLT_IN_IN_R {
FLT_IN_IN_R::new(((self.bits >> 24) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - Edge detect for IO pin 0 '0': No edge was detected on pin. '1': An edge was detected on pin."]
#[inline(always)]
pub fn edge0(&mut self) -> EDGE0_W {
EDGE0_W { w: self }
}
#[doc = "Bit 1 - Edge detect for IO pin 1"]
#[inline(always)]
pub fn edge1(&mut self) -> EDGE1_W {
EDGE1_W { w: self }
}
#[doc = "Bit 2 - Edge detect for IO pin 2"]
#[inline(always)]
pub fn edge2(&mut self) -> EDGE2_W {
EDGE2_W { w: self }
}
#[doc = "Bit 3 - Edge detect for IO pin 3"]
#[inline(always)]
pub fn edge3(&mut self) -> EDGE3_W {
EDGE3_W { w: self }
}
#[doc = "Bit 4 - Edge detect for IO pin 4"]
#[inline(always)]
pub fn edge4(&mut self) -> EDGE4_W {
EDGE4_W { w: self }
}
#[doc = "Bit 5 - Edge detect for IO pin 5"]
#[inline(always)]
pub fn edge5(&mut self) -> EDGE5_W {
EDGE5_W { w: self }
}
#[doc = "Bit 6 - Edge detect for IO pin 6"]
#[inline(always)]
pub fn edge6(&mut self) -> EDGE6_W {
EDGE6_W { w: self }
}
#[doc = "Bit 7 - Edge detect for IO pin 7"]
#[inline(always)]
pub fn edge7(&mut self) -> EDGE7_W {
EDGE7_W { w: self }
}
#[doc = "Bit 8 - Edge detected on filtered pin selected by INTR_CFG.FLT_SEL"]
#[inline(always)]
pub fn flt_edge(&mut self) -> FLT_EDGE_W {
FLT_EDGE_W { w: self }
}
}
|
#![deny(missing_debug_implementations)]
//! apllodb's storage engine interface.
//!
//! # Installation
//!
//! ```toml
//! [dependencies]
//! apllodb-storage-engine-interface = "0.1"
//! ```
//!
//! # Boundary of Responsibility with Storage Engine
//!
//! A storage engine is an implementation of this interface crate.
//!
//! This crate provides:
//!
//! - Access Methods traits related to:
//! - apllodb-DDL
//! - apllodb-DML
//! - Transaction
//! - Getting catalog
//! - Traits of records and record iterators.
//! - Catalog data structure with read-only APIs.
//!
//! And a storage engine MUST provide:
//!
//! - Access Methods implementation.
//! - Implementation of records and record iterators.
//! - Ways to materialize tables and records.
//!
//! # Testing support
//!
//! Testing supports are available with `"test-support"` feature.
//!
//! ```toml
//! [dependencies]
//! apllodb-storage-engine-interface = {version = "...", features = ["test-support"]}
//! ```
//!
//! List of features for testing:
//!
//! - `MockStorageEngine`, `Mock*Methods` (access methods mock) structs generated by [mockall](https://docs.rs/mockall/).
//! - Models and fixtures.
//!
//! See [test_support module level doc](crate::test_support) for detail.
#[macro_use]
extern crate derive_new;
mod access_methods;
mod alter_table_action;
mod column;
mod row_projection_query;
mod row_selection_query;
mod rows;
mod single_table_condition;
mod table;
mod table_column_name;
pub use access_methods::{
with_db_methods::WithDbMethods, with_tx_methods::WithTxMethods,
without_db_methods::WithoutDbMethods,
};
pub use alter_table_action::AlterTableAction;
pub use column::{
column_constraint_kind::ColumnConstraintKind, column_constraints::ColumnConstraints,
column_data_type::ColumnDataType, column_definition::ColumnDefinition, column_name::ColumnName,
};
pub use row_projection_query::RowProjectionQuery;
pub use row_selection_query::RowSelectionQuery;
pub use rows::{row::Row, row_schema::RowSchema, Rows};
pub use single_table_condition::SingleTableCondition;
pub use table::{
table_constraint_kind::TableConstraintKind, table_constraints::TableConstraints,
table_name::TableName,
};
pub use table_column_name::TableColumnName;
#[cfg(any(test, feature = "test-support"))]
pub mod test_support;
#[cfg(feature = "test-support")]
use mockall::automock;
#[cfg(feature = "test-support")]
use access_methods::{
with_db_methods::MockWithDbMethods, with_tx_methods::MockWithTxMethods,
without_db_methods::MockWithoutDbMethods,
};
/// Storage engine interface.
#[cfg_attr(
feature = "test-support",
automock(
type WithoutDb = MockWithoutDbMethods;
type WithDb = MockWithDbMethods;
type WithTx = MockWithTxMethods;
)
)]
pub trait StorageEngine {
/// Access methods that take [SessionWithoutDb](apllodb-shared-components::SessionWithoutDb).
type WithoutDb: WithoutDbMethods;
/// Access methods that take [SessionWithDb](apllodb-shared-components::SessionWithDb).
type WithDb: WithDbMethods;
/// Access methods that take [SessionWithTx](apllodb-shared-components::SessionWithTx).
type WithTx: WithTxMethods;
fn without_db(&self) -> Self::WithoutDb;
fn with_db(&self) -> Self::WithDb;
fn with_tx(&self) -> Self::WithTx;
}
#[cfg(test)]
mod tests {
use apllodb_test_support::setup::setup_test_logger;
use ctor::ctor;
#[cfg_attr(test, ctor)]
fn test_setup() {
setup_test_logger();
}
}
|
// ===============================================================================
// Authors: AFRL/RQQA
// Organization: Air Force Research Laboratory, Aerospace Systems Directorate, Power and Control Division
//
// Copyright (c) 2017 Government of the United State of America, as represented by
// the Secretary of the Air Force. No copyright is claimed in the United States under
// Title 17, U.S. Code. All Other Rights Reserved.
// ===============================================================================
// This file was auto-created by LmcpGen. Modifications will be overwritten.
use avtas::lmcp::{Error, ErrorType, Lmcp, LmcpSubscription, SrcLoc, Struct, StructInfo};
use std::fmt::Debug;
#[derive(Clone, Debug, Default)]
#[repr(C)]
pub struct StopMovementAction {
pub associated_task_list: Vec<i64>,
pub location: Option<Box<::afrl::cmasi::location3d::Location3DT>>,
}
impl PartialEq for StopMovementAction {
fn eq(&self, _other: &StopMovementAction) -> bool {
true
&& &self.location == &_other.location
}
}
impl LmcpSubscription for StopMovementAction {
fn subscription() -> &'static str { "afrl.cmasi.StopMovementAction" }
}
impl Struct for StopMovementAction {
fn struct_info() -> StructInfo {
StructInfo {
exist: 1,
series: 4849604199710720000u64,
version: 3,
struct_ty: 58,
}
}
}
impl Lmcp for StopMovementAction {
fn ser(&self, buf: &mut[u8]) -> Result<usize, Error> {
let mut pos = 0;
{
let x = Self::struct_info().ser(buf)?;
pos += x;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.associated_task_list.ser(r)?;
pos += writeb;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.location.ser(r)?;
pos += writeb;
}
Ok(pos)
}
fn deser(buf: &[u8]) -> Result<(StopMovementAction, usize), Error> {
let mut pos = 0;
let (si, u) = StructInfo::deser(buf)?;
pos += u;
if si == StopMovementAction::struct_info() {
let mut out: StopMovementAction = Default::default();
{
let r = get!(buf.get(pos ..));
let (x, readb): (Vec<i64>, usize) = Lmcp::deser(r)?;
out.associated_task_list = x;
pos += readb;
}
{
let r = get!(buf.get(pos ..));
let (x, readb): (Option<Box<::afrl::cmasi::location3d::Location3DT>>, usize) = Lmcp::deser(r)?;
out.location = x;
pos += readb;
}
Ok((out, pos))
} else {
Err(error!(ErrorType::InvalidStructInfo))
}
}
fn size(&self) -> usize {
let mut size = 15;
size += self.associated_task_list.size();
size += self.location.size();
size
}
}
pub trait StopMovementActionT: Debug + Send + ::afrl::cmasi::vehicle_action::VehicleActionT {
fn as_afrl_cmasi_stop_movement_action(&self) -> Option<&StopMovementAction> { None }
fn as_mut_afrl_cmasi_stop_movement_action(&mut self) -> Option<&mut StopMovementAction> { None }
fn location(&self) -> &Option<Box<::afrl::cmasi::location3d::Location3DT>>;
fn location_mut(&mut self) -> &mut Option<Box<::afrl::cmasi::location3d::Location3DT>>;
}
impl Clone for Box<StopMovementActionT> {
fn clone(&self) -> Box<StopMovementActionT> {
if let Some(x) = StopMovementActionT::as_afrl_cmasi_stop_movement_action(self.as_ref()) {
Box::new(x.clone())
} else {
unreachable!()
}
}
}
impl Default for Box<StopMovementActionT> {
fn default() -> Box<StopMovementActionT> { Box::new(StopMovementAction::default()) }
}
impl PartialEq for Box<StopMovementActionT> {
fn eq(&self, other: &Box<StopMovementActionT>) -> bool {
if let (Some(x), Some(y)) =
(StopMovementActionT::as_afrl_cmasi_stop_movement_action(self.as_ref()),
StopMovementActionT::as_afrl_cmasi_stop_movement_action(other.as_ref())) {
x == y
} else {
false
}
}
}
impl Lmcp for Box<StopMovementActionT> {
fn ser(&self, buf: &mut[u8]) -> Result<usize, Error> {
if let Some(x) = StopMovementActionT::as_afrl_cmasi_stop_movement_action(self.as_ref()) {
x.ser(buf)
} else {
unreachable!()
}
}
fn deser(buf: &[u8]) -> Result<(Box<StopMovementActionT>, usize), Error> {
let (si, _) = StructInfo::deser(buf)?;
if si == StopMovementAction::struct_info() {
let (x, readb) = StopMovementAction::deser(buf)?;
Ok((Box::new(x), readb))
} else {
Err(error!(ErrorType::InvalidStructInfo))
}
}
fn size(&self) -> usize {
if let Some(x) = StopMovementActionT::as_afrl_cmasi_stop_movement_action(self.as_ref()) {
x.size()
} else {
unreachable!()
}
}
}
impl ::afrl::cmasi::vehicle_action::VehicleActionT for StopMovementAction {
fn as_afrl_cmasi_stop_movement_action(&self) -> Option<&StopMovementAction> { Some(self) }
fn as_mut_afrl_cmasi_stop_movement_action(&mut self) -> Option<&mut StopMovementAction> { Some(self) }
fn associated_task_list(&self) -> &Vec<i64> { &self.associated_task_list }
fn associated_task_list_mut(&mut self) -> &mut Vec<i64> { &mut self.associated_task_list }
}
impl StopMovementActionT for StopMovementAction {
fn as_afrl_cmasi_stop_movement_action(&self) -> Option<&StopMovementAction> { Some(self) }
fn as_mut_afrl_cmasi_stop_movement_action(&mut self) -> Option<&mut StopMovementAction> { Some(self) }
fn location(&self) -> &Option<Box<::afrl::cmasi::location3d::Location3DT>> { &self.location }
fn location_mut(&mut self) -> &mut Option<Box<::afrl::cmasi::location3d::Location3DT>> { &mut self.location }
}
#[cfg(test)]
pub mod tests {
use super::*;
use quickcheck::*;
impl Arbitrary for StopMovementAction {
fn arbitrary<G: Gen>(_g: &mut G) -> StopMovementAction {
StopMovementAction {
associated_task_list: Arbitrary::arbitrary(_g),
location: {
if _g.gen() {
Some(Box::new(::afrl::cmasi::location3d::Location3D::arbitrary(_g)))
} else {
None
}
},
}
}
}
quickcheck! {
fn serializes(x: StopMovementAction) -> Result<TestResult, Error> {
use std::u16;
if x.associated_task_list.len() > (u16::MAX as usize) { return Ok(TestResult::discard()); }
let mut buf: Vec<u8> = vec![0; x.size()];
let sx = x.ser(&mut buf)?;
Ok(TestResult::from_bool(sx == x.size()))
}
fn roundtrips(x: StopMovementAction) -> Result<TestResult, Error> {
use std::u16;
if x.associated_task_list.len() > (u16::MAX as usize) { return Ok(TestResult::discard()); }
let mut buf: Vec<u8> = vec![0; x.size()];
let sx = x.ser(&mut buf)?;
let (y, sy) = StopMovementAction::deser(&buf)?;
Ok(TestResult::from_bool(sx == sy && x == y))
}
}
}
|
use crate::color::Color;
use crate::texture::{solidcolor::SolidColor, Texture, TextureColor};
use crate::vec::Vec3;
// CheckerTexture
#[derive(Debug, Clone)]
pub struct CheckerTexture {
pub odd: Box<Texture>,
pub even: Box<Texture>,
}
impl CheckerTexture {
pub fn new(c1: Color, c2: Color) -> Texture {
Texture::from(CheckerTexture {
odd: Box::new(SolidColor::new(c1.r, c1.g, c1.b)),
even: Box::new(SolidColor::new(c2.r, c2.g, c2.b)),
})
}
}
impl Default for CheckerTexture {
fn default() -> CheckerTexture {
CheckerTexture {
odd: Box::new(SolidColor::new(0.0, 0.0, 0.0)),
even: Box::new(SolidColor::new(1.1, 1.1, 1.1)),
}
}
}
impl TextureColor for CheckerTexture {
fn value(&self, u: f64, v: f64, p: Vec3) -> Color {
let sines = f64::sin(10.0 * p.x) * f64::sin(10.0 * p.y) * f64::sin(10.0 * p.z);
if sines < 0.0 {
self.odd.value(u, v, p)
} else {
self.even.value(u, v, p)
}
}
}
|
use std::{fs, io};
use std::sync::{Arc, Mutex, atomic::{AtomicBool, Ordering}, Condvar};
use std::collections::{HashMap, HashSet, hash_map::{Entry, DefaultHasher}};
use std::hash::{Hash, Hasher};
use std::result;
use std::thread::{ThreadId, self};
use std::time::Instant;
use futures::{FutureExt, future::BoxFuture};
use futures::channel::oneshot::{Sender as FSender, channel};
use futures::executor::ThreadPool;
use futures::lock::Mutex as FMutex;
use lsp_server::*;
use serde::ser::Serialize;
use serde_json::{from_value, to_value};
use serde_repr::{Serialize_repr, Deserialize_repr};
use lsp_types::*;
use crossbeam::{channel::{SendError, RecvError}};
use crate::util::*;
use crate::lined_string::LinedString;
use crate::parser::{AST, parse};
use crate::mmu::import::elab as mmu_elab;
use crate::elab::{ElabError, Elaborator,
environment::{ObjectKind, DeclKey, AtomData, StmtTrace, Environment},
local_context::InferSort, proof::Subst,
lisp::{LispKind, Uncons, print::FormatEnv, pretty::Pretty}};
#[derive(Debug)]
struct ServerError(BoxError);
type Result<T> = result::Result<T, ServerError>;
impl From<serde_json::Error> for ServerError {
fn from(e: serde_json::error::Error) -> Self { ServerError(Box::new(e)) }
}
impl From<ProtocolError> for ServerError {
fn from(e: ProtocolError) -> Self { ServerError(Box::new(e)) }
}
impl From<RecvError> for ServerError {
fn from(e: RecvError) -> Self { ServerError(Box::new(e)) }
}
impl<T: Send + Sync + 'static> From<SendError<T>> for ServerError {
fn from(e: SendError<T>) -> Self { ServerError(Box::new(e)) }
}
impl From<&'static str> for ServerError {
fn from(e: &'static str) -> Self { ServerError(e.into()) }
}
impl From<io::Error> for ServerError {
fn from(e: io::Error) -> Self { ServerError(Box::new(e)) }
}
impl From<BoxError> for ServerError {
fn from(e: BoxError) -> Self { ServerError(e) }
}
impl From<String> for ServerError {
fn from(e: String) -> Self { ServerError(e.into()) }
}
fn nos_id(nos: NumberOrString) -> RequestId {
match nos {
NumberOrString::Number(n) => n.into(),
NumberOrString::String(s) => s.into(),
}
}
lazy_static! {
static ref LOGGER: (Mutex<Vec<(Instant, ThreadId, String)>>, Condvar) = Default::default();
static ref SERVER: Server = Server::new().expect("Initialization failed");
}
#[allow(unused)]
pub fn log(s: String) {
LOGGER.0.lock().unwrap().push((Instant::now(), thread::current().id(), s));
LOGGER.1.notify_one();
}
#[allow(unused)]
macro_rules! log {
($($es:tt)*) => {crate::server::log(format!($($es)*))}
}
async fn elaborate(path: FileRef, start: Option<Position>,
cancel: Arc<AtomicBool>) -> Result<(u64, Arc<Environment>)> {
let Server {vfs, pool, ..} = &*SERVER;
let (path, file) = vfs.get_or_insert(path)?;
let v = file.text.lock().unwrap().0;
let (old_ast, old_env, old_deps) = {
let mut g = file.parsed.lock().await;
let (res, senders) = match &mut *g {
None => ((None, None, vec![]), vec![]),
&mut Some(FileCache::InProgress {version, ref cancel, ref mut senders}) => {
if v == version {
let (send, recv) = channel();
senders.push(send);
drop(g);
return Ok(recv.await.unwrap())
}
cancel.store(true, Ordering::SeqCst);
if let Some(FileCache::InProgress {senders, ..}) = g.take() {
((None, None, vec![]), senders)
} else {unsafe {std::hint::unreachable_unchecked()}}
}
&mut Some(FileCache::Ready {hash, ref deps, ref env, complete, ..}) => {
if complete && (|| -> bool {
let hasher = &mut DefaultHasher::new();
v.hash(hasher);
for path in deps {
if let Some(file) = vfs.get(path) {
if let Some(g) = file.parsed.try_lock() {
if let Some(FileCache::Ready {hash, ..}) = *g {
hash.hash(hasher);
} else {return false}
} else {return false}
} else {return false}
}
hasher.finish() == hash
})() {return Ok((hash, env.clone()))}
if let Some(FileCache::Ready {ast, source, errors, deps, env, ..}) = g.take() {
((start.map(|s| (s, source, ast)), Some((errors, env)), deps), vec![])
} else {unsafe {std::hint::unreachable_unchecked()}}
}
};
*g = Some(FileCache::InProgress {version: v, cancel: cancel.clone(), senders});
res
};
let (version, text) = file.text.lock().unwrap().clone();
let old_ast = old_ast.and_then(|(s, old_text, ast)|
if Arc::ptr_eq(&text, &old_text) {Some((s, ast))} else {None});
let mut hasher = DefaultHasher::new();
version.hash(&mut hasher);
let source = text.clone();
let (idx, ast) = parse(text, old_ast);
let ast = Arc::new(ast);
let mut deps = Vec::new();
let elab = Elaborator::new(ast.clone(), path.clone(), path.has_extension("mm0"), cancel.clone());
let (toks, errors, env) = if path.has_extension("mmb") {
unimplemented!()
} else if path.has_extension("mmu") {
let (errors, env) = mmu_elab(path.clone(), &ast.source);
(vec![], errors, env)
} else {
elab.as_fut(
old_env.map(|(errs, e)| (idx, errs, e)),
|path| {
let path = vfs.get_or_insert(path)?.0;
let (send, recv) = channel();
pool.spawn_ok(elaborate_and_send(path.clone(), cancel.clone(), send));
deps.push(path);
Ok(recv)
}).await
};
for tok in toks {tok.hash(&mut hasher)}
let hash = hasher.finish();
let env = Arc::new(env);
log!("elabbed {:?}", path);
let mut g = file.parsed.lock().await;
let complete = !cancel.load(Ordering::SeqCst);
if complete {
let mut srcs = HashMap::new();
let mut to_loc = |fsp: &FileSpan| -> Location {
if fsp.file.ptr_eq(&path) {
&ast.source
} else {
srcs.entry(fsp.file.ptr()).or_insert_with(||
vfs.0.lock().unwrap().get(&fsp.file).unwrap()
.text.lock().unwrap().1.clone())
}.to_loc(fsp)
};
let errs: Vec<_> = ast.errors.iter().map(|e| e.to_diag(&ast.source))
.chain(errors.iter().map(|e| e.to_diag(&ast.source, &mut to_loc))).collect();
log!("diagged {:?}, {} errors", path, errs.len());
send_diagnostics(path.url().clone(), errs)?;
}
vfs.update_downstream(&old_deps, &deps, &path);
if let Some(FileCache::InProgress {senders, ..}) = g.take() {
for s in senders {
let _ = s.send((hash, env.clone()));
}
}
*g = Some(FileCache::Ready {hash, source, ast, errors, deps, env: env.clone(), complete});
drop(g);
for d in file.downstream.lock().unwrap().iter() {
log!("{:?} affects {:?}", path, d);
pool.spawn_ok(dep_change(d.clone()));
}
Ok((hash, env))
}
async fn elaborate_and_report(path: FileRef, start: Option<Position>, cancel: Arc<AtomicBool>) {
if let Err(e) = std::panic::AssertUnwindSafe(elaborate(path, start, cancel))
.catch_unwind().await
.unwrap_or_else(|_| Err("server panic".into())) {
log_message(format!("{:?}", e).into()).unwrap();
}
}
fn elaborate_and_send(path: FileRef,
cancel: Arc<AtomicBool>, send: FSender<(u64, Arc<Environment>)>) ->
BoxFuture<'static, ()> {
async {
if let Ok(env) = elaborate(path, Some(Position::default()), cancel).await {
let _ = send.send(env);
}
}.boxed()
}
fn dep_change(path: FileRef) -> BoxFuture<'static, ()> {
elaborate_and_report(path, None, Arc::new(AtomicBool::new(false))).boxed()
}
enum FileCache {
InProgress {
version: Option<i64>,
cancel: Arc<AtomicBool>,
senders: Vec<FSender<(u64, Arc<Environment>)>>,
},
Ready {
hash: u64,
source: Arc<LinedString>,
ast: Arc<AST>,
errors: Vec<ElabError>,
env: Arc<Environment>,
deps: Vec<FileRef>,
complete: bool,
}
}
struct VirtualFile {
/// File data, saved (true) or unsaved (false)
text: Mutex<(Option<i64>, Arc<LinedString>)>,
/// File parse
parsed: FMutex<Option<FileCache>>,
/// Files that depend on this one
downstream: Mutex<HashSet<FileRef>>,
}
impl VirtualFile {
fn new(version: Option<i64>, text: String) -> VirtualFile {
VirtualFile {
text: Mutex::new((version, Arc::new(text.into()))),
parsed: FMutex::new(None),
downstream: Mutex::new(HashSet::new())
}
}
}
struct VFS(Mutex<HashMap<FileRef, Arc<VirtualFile>>>);
impl VFS {
fn get(&self, path: &FileRef) -> Option<Arc<VirtualFile>> {
self.0.lock().unwrap().get(path).cloned()
}
fn get_or_insert(&self, path: FileRef) -> io::Result<(FileRef, Arc<VirtualFile>)> {
match self.0.lock().unwrap().entry(path) {
Entry::Occupied(e) => Ok((e.key().clone(), e.get().clone())),
Entry::Vacant(e) => {
let path = e.key().clone();
let s = fs::read_to_string(path.path())?;
let val = e.insert(Arc::new(VirtualFile::new(None, s))).clone();
Ok((path, val))
}
}
}
fn source(&self, file: &FileRef) -> Arc<LinedString> {
self.0.lock().unwrap().get(&file).unwrap().text.lock().unwrap().1.clone()
}
fn open_virt(&self, path: FileRef, version: i64, text: String) -> Result<Arc<VirtualFile>> {
let pool = &SERVER.pool;
let file = Arc::new(VirtualFile::new(Some(version), text));
let file = match self.0.lock().unwrap().entry(path.clone()) {
Entry::Occupied(entry) => {
for dep in entry.get().downstream.lock().unwrap().iter() {
pool.spawn_ok(dep_change(dep.clone()));
}
file
}
Entry::Vacant(entry) => entry.insert(file).clone()
};
pool.spawn_ok(elaborate_and_report(path, Some(Position::default()),
Arc::new(AtomicBool::new(false))));
Ok(file)
}
fn close(&self, path: &FileRef) -> Result<()> {
let mut g = self.0.lock().unwrap();
if let Entry::Occupied(e) = g.entry(path.clone()) {
if e.get().downstream.lock().unwrap().is_empty() {
send_diagnostics(path.url().clone(), vec![])?;
e.remove();
} else if e.get().text.lock().unwrap().0.take().is_some() {
let file = e.get().clone();
drop(g);
let pool = &SERVER.pool;
for dep in file.downstream.lock().unwrap().clone() {
pool.spawn_ok(dep_change(dep.clone()));
}
}
}
Ok(())
}
fn update_downstream(&self, old_deps: &[FileRef], deps: &[FileRef], to: &FileRef) {
for from in old_deps {
if !deps.contains(from) {
let file = self.0.lock().unwrap().get(from).unwrap().clone();
file.downstream.lock().unwrap().remove(to);
}
}
for from in deps {
if !old_deps.contains(from) {
let file = self.0.lock().unwrap().get(from).unwrap().clone();
file.downstream.lock().unwrap().insert(to.clone());
}
}
}
}
enum RequestType {
Completion(CompletionParams),
CompletionResolve(CompletionItem),
Hover(TextDocumentPositionParams),
Definition(TextDocumentPositionParams),
DocumentSymbol(DocumentSymbolParams),
}
fn parse_request(req: Request) -> Result<Option<(RequestId, RequestType)>> {
let Request {id, method, params} = req;
match method.as_str() {
"textDocument/completion" => Ok(Some((id, RequestType::Completion(from_value(params)?)))),
"textDocument/hover" => Ok(Some((id, RequestType::Hover(from_value(params)?)))),
"textDocument/definition" => Ok(Some((id, RequestType::Definition(from_value(params)?)))),
"textDocument/documentSymbol" => Ok(Some((id, RequestType::DocumentSymbol(from_value(params)?)))),
"completionItem/resolve" => Ok(Some((id, RequestType::CompletionResolve(from_value(params)?)))),
_ => Ok(None)
}
}
fn send_message<T: Into<Message>>(t: T) -> Result<()> {
Ok(SERVER.conn.sender.send(t.into())?)
}
#[allow(unused)]
fn show_message(typ: MessageType, message: String) -> Result<()> {
send_message(Notification {
method: "window/showMessage".to_owned(),
params: to_value(ShowMessageParams {typ, message})?
})
}
#[allow(unused)]
fn log_message(message: String) -> Result<()> {
send_message(Notification {
method: "window/logMessage".to_owned(),
params: to_value(LogMessageParams {typ: MessageType::Log, message})?
})
}
fn send_diagnostics(uri: Url, diagnostics: Vec<Diagnostic>) -> Result<()> {
send_message(Notification {
method: "textDocument/publishDiagnostics".to_owned(),
params: to_value(PublishDiagnosticsParams {uri, diagnostics})?
})
}
type OpenRequests = Mutex<HashMap<RequestId, Arc<AtomicBool>>>;
struct RequestHandler {
id: RequestId,
#[allow(unused)]
cancel: Arc<AtomicBool>,
}
impl RequestHandler {
async fn handle(self, req: RequestType) -> Result<()> {
match req {
RequestType::Hover(TextDocumentPositionParams {text_document: doc, position}) =>
self.finish(hover(FileRef::from_url(doc.uri), position).await),
RequestType::Definition(TextDocumentPositionParams {text_document: doc, position}) =>
if SERVER.caps.definition_location_links {
self.finish(definition(FileRef::from_url(doc.uri), position,
|text, text2, src, &FileSpan {ref file, span}, full| LocationLink {
origin_selection_range: Some(text.to_range(src)),
target_uri: file.url().clone(),
target_range: text2.to_range(full),
target_selection_range: text2.to_range(span),
}).await)
} else {
self.finish(definition(FileRef::from_url(doc.uri), position,
|_, text2, _, &FileSpan {ref file, span}, _| Location {
uri: file.url().clone(),
range: text2.to_range(span),
}).await)
},
RequestType::DocumentSymbol(DocumentSymbolParams {text_document: doc}) =>
self.finish(document_symbol(FileRef::from_url(doc.uri)).await),
RequestType::Completion(p) => {
let doc = p.text_document_position;
self.finish(completion(FileRef::from_url(doc.text_document.uri), doc.position).await)
}
RequestType::CompletionResolve(ci) => {
self.finish(completion_resolve(ci).await)
}
}
}
fn finish<T: Serialize>(self, resp: result::Result<T, ResponseError>) -> Result<()> {
let Server {reqs, conn, ..} = &*SERVER;
reqs.lock().unwrap().remove(&self.id);
conn.sender.send(Message::Response(match resp {
Ok(val) => Response { id: self.id, result: Some(to_value(val)?), error: None },
Err(e) => Response { id: self.id, result: None, error: Some(e) }
}))?;
Ok(())
}
}
async fn hover(path: FileRef, pos: Position) -> result::Result<Option<Hover>, ResponseError> {
let Server {vfs, ..} = &*SERVER;
macro_rules! or {($ret:expr, $e:expr) => {match $e {
Some(x) => x,
None => return $ret
}}}
let file = vfs.get(&path).ok_or_else(||
response_err(ErrorCode::InvalidRequest, "hover nonexistent file"))?;
let text = file.text.lock().unwrap().1.clone();
let idx = or!(Ok(None), text.to_idx(pos));
let env = elaborate(path, Some(Position::default()), Arc::new(AtomicBool::from(false)))
.await.map_err(|e| response_err(ErrorCode::InternalError, format!("{:?}", e)))?.1;
let fe = FormatEnv {source: &text, env: &env};
let spans = or!(Ok(None), env.find(idx));
let mut res = vec![];
for &(sp, ref k) in spans.find_pos(idx) {
if let Some(r) = (|| Some(match k {
&ObjectKind::Sort(s) => (sp, format!("{}", &env.sorts[s])),
&ObjectKind::Term(t, sp1) => (sp1, format!("{}", fe.to(&env.terms[t]))),
&ObjectKind::Thm(t) => (sp, format!("{}", fe.to(&env.thms[t]))),
&ObjectKind::Var(x) => (sp, match spans.lc.as_ref().and_then(|lc| lc.vars.get(&x)) {
Some((_, InferSort::Bound {sort})) => format!("{{{}: {}}}", fe.to(&x), fe.to(sort)),
Some((_, InferSort::Reg {sort, deps})) => {
let mut s = format!("({}: {}", fe.to(&x), fe.to(sort));
for &a in deps {s += " "; s += &env.data[a].name}
s + ")"
}
_ => return None,
}),
ObjectKind::Expr(e) => {
let head = Uncons::from(e.clone()).next().unwrap_or_else(|| e.clone());
let sp1 = head.fspan().map_or(sp, |fsp| fsp.span);
let a = head.as_atom()?;
if let Some(DeclKey::Term(t)) = env.data[a].decl {
(sp1, format!("{}", fe.to(&env.terms[t].ret.0)))
} else {
let s = spans.lc.as_ref()?.vars.get(&a)?.1.sort()?;
(sp1, format!("{}", fe.to(&s)))
}
}
ObjectKind::Proof(p) => {
if let Some(e) = p.as_atom().and_then(|x|
spans.lc.as_ref().and_then(|lc|
lc.proofs.get(&x).map(|&i| &lc.proof_order[i].1))) {
let mut out = String::new();
fe.pretty(|p| p.hyps_and_ret(Pretty::nil(), std::iter::empty(), e)
.render_fmt(80, &mut out).unwrap());
(sp, out)
} else {
let mut u = Uncons::from(p.clone());
let head = u.next()?;
let sp1 = head.fspan().map_or(sp, |fsp| fsp.span);
let a = head.as_atom()?;
if let Some(DeclKey::Thm(t)) = env.data[a].decl {
let td = &env.thms[t];
res.push((sp, format!("{}", fe.to(td))));
let mut args = vec![];
if !u.extend_into(td.args.len(), &mut args) {return None}
let mut subst = Subst::new(&env, &td.heap, args);
let mut out = String::new();
let ret = subst.subst(&td.ret);
fe.pretty(|p| p.hyps_and_ret(Pretty::nil(),
td.hyps.iter().map(|(_, h)| subst.subst(h)),
&ret).render_fmt(80, &mut out).unwrap());
(sp1, out)
} else {return None}
}
}
ObjectKind::Global(_) |
ObjectKind::Import(_) => return None,
}))() {res.push(r)}
}
if res.is_empty() {return Ok(None)}
Ok(Some(Hover {
range: Some(text.to_range(res[0].0)),
contents: HoverContents::Array(res.into_iter().map(|(_, value)|
MarkedString::LanguageString(LanguageString {language: "metamath-zero".into(), value})).collect())
}))
}
async fn definition<T>(path: FileRef, pos: Position,
f: impl Fn(&LinedString, &LinedString, Span, &FileSpan, Span) -> T) ->
result::Result<Vec<T>, ResponseError> {
let Server {vfs, ..} = &*SERVER;
macro_rules! or_none {($e:expr) => {match $e {
Some(x) => x,
None => return Ok(vec![])
}}}
let file = vfs.get(&path).ok_or_else(||
response_err(ErrorCode::InvalidRequest, "goto definition nonexistent file"))?;
let text = file.text.lock().unwrap().1.clone();
let idx = or_none!(text.to_idx(pos));
let env = elaborate(path.clone(), Some(Position::default()), Arc::new(AtomicBool::from(false)))
.await.map_err(|e| response_err(ErrorCode::InternalError, format!("{:?}", e)))?.1;
let spans = or_none!(env.find(idx));
let mut res = vec![];
for &(sp, ref k) in spans.find_pos(idx) {
let g = |fsp: &FileSpan, full|
if fsp.file.ptr_eq(&path) {
f(&text, &text, sp, fsp, full)
} else {
f(&text, &vfs.source(&fsp.file), sp, fsp, full)
};
let sort = |s| {
let sd = &env.sorts[s];
g(&sd.span, sd.full)
};
let term = |t| {
let td = &env.terms[t];
g(&td.span, td.full)
};
let thm = |t| {
let td = &env.thms[t];
g(&td.span, td.full)
};
match k {
&ObjectKind::Sort(s) => res.push(sort(s)),
&ObjectKind::Term(t, _) => res.push(term(t)),
&ObjectKind::Thm(t) => res.push(thm(t)),
ObjectKind::Var(_) => {}
ObjectKind::Expr(e) => {
let head = Uncons::from(e.clone()).next().unwrap_or_else(|| e.clone());
if let Some(DeclKey::Term(t)) = head.as_atom().and_then(|a| env.data[a].decl) {
res.push(term(t))
}
},
ObjectKind::Proof(p) =>
if let Some(DeclKey::Thm(t)) = Uncons::from(p.clone()).next()
.and_then(|head| head.as_atom()).and_then(|a| env.data[a].decl) {
res.push(thm(t))
},
&ObjectKind::Global(a) => {
let ad = &env.data[a];
match ad.decl {
Some(DeclKey::Term(t)) => res.push(term(t)),
Some(DeclKey::Thm(t)) => res.push(thm(t)),
None => {}
}
if let Some(s) = ad.sort {res.push(sort(s))}
if let Some((Some((ref fsp, full)), _)) = ad.lisp {
res.push(g(&fsp, full))
}
}
ObjectKind::Import(file) => {
res.push(g(&FileSpan {file: file.clone(), span: 0.into()}, 0.into()))
},
}
}
Ok(res)
}
async fn document_symbol(path: FileRef) -> result::Result<DocumentSymbolResponse, ResponseError> {
let Server {vfs, ..} = &*SERVER;
let file = vfs.get(&path).ok_or_else(||
response_err(ErrorCode::InvalidRequest, "document symbol nonexistent file"))?;
let text = file.text.lock().unwrap().1.clone();
let env = elaborate(path, Some(Position::default()), Arc::new(AtomicBool::from(false)))
.await.map_err(|e| response_err(ErrorCode::InternalError, format!("{:?}", e)))?.1;
let fe = FormatEnv {source: &text, env: &env};
let f = |name: &ArcString, desc, sp, full, kind| DocumentSymbol {
name: (*name.0).clone(),
detail: Some(desc),
kind,
deprecated: None,
range: text.to_range(full),
selection_range: text.to_range(sp),
children: None,
};
let mut res = vec![];
for s in &env.stmts {
match s {
&StmtTrace::Sort(a) => {
let ad = &env.data[a];
let s = ad.sort.unwrap();
let sd = &env.sorts[s];
res.push(f(&ad.name, format!("{}", sd), sd.span.span, sd.full, SymbolKind::Class))
}
&StmtTrace::Decl(a) => {
let ad = &env.data[a];
match ad.decl.unwrap() {
DeclKey::Term(t) => {
let td = &env.terms[t];
res.push(f(&ad.name, format!("{}", fe.to(td)), td.span.span, td.full,
SymbolKind::Constructor))
}
DeclKey::Thm(t) => {
let td = &env.thms[t];
res.push(f(&ad.name, format!("{}", fe.to(td)), td.span.span, td.full,
SymbolKind::Method))
}
}
}
&StmtTrace::Global(a) => {
let ad = &env.data[a];
if let &Some((Some((ref fsp, full)), ref e)) = &ad.lisp {
res.push(f(&ad.name, format!("{}", fe.to(e)), fsp.span, full,
match e.unwrapped(|r| Some(match r {
LispKind::Atom(_) |
LispKind::MVar(_, _) |
LispKind::Goal(_) => SymbolKind::Constant,
LispKind::List(_) |
LispKind::DottedList(_, _) =>
if r.is_list() {SymbolKind::Array} else {SymbolKind::Object},
LispKind::Number(_) => SymbolKind::Number,
LispKind::String(_) => SymbolKind::String,
LispKind::Bool(_) => SymbolKind::Boolean,
LispKind::Syntax(_) => SymbolKind::Event,
LispKind::Undef => return None,
LispKind::Proc(_) => SymbolKind::Function,
LispKind::AtomMap(_) => SymbolKind::Object,
LispKind::Annot(_, _) |
LispKind::Ref(_) => unreachable!()
})) {
Some(sk) => sk,
None => continue,
}));
} else {unreachable!()}
}
}
}
Ok(DocumentSymbolResponse::Nested(res))
}
#[derive(Serialize_repr, Deserialize_repr)]
#[repr(u8)]
enum TraceKind {Sort, Decl, Global}
fn make_completion_item(path: &FileRef, fe: FormatEnv, ad: &AtomData, detail: bool, tk: TraceKind) -> Option<CompletionItem> {
use CompletionItemKind::*;
macro_rules! done {($desc:expr, $kind:expr) => {
Some(CompletionItem {
label: (*ad.name.0).clone(),
detail: if detail {Some($desc)} else {None},
kind: Some($kind),
data: Some(to_value((path.url(), tk)).unwrap()),
..Default::default()
})
}}
match tk {
TraceKind::Sort => ad.sort.and_then(|s| {
let sd = &fe.sorts[s];
done!(format!("{}", sd), Class)
}),
TraceKind::Decl => ad.decl.and_then(|dk| match dk {
DeclKey::Term(t) => {let td = &fe.terms[t]; done!(format!("{}", fe.to(td)), Constructor)}
DeclKey::Thm(t) => {let td = &fe.thms[t]; done!(format!("{}", fe.to(td)), Method)}
}),
TraceKind::Global => ad.lisp.as_ref().and_then(|(_, e)| {
done!(format!("{}", fe.to(e)), e.unwrapped(|r| match r {
LispKind::Atom(_) |
LispKind::MVar(_, _) |
LispKind::Goal(_) => CompletionItemKind::Constant,
LispKind::List(_) |
LispKind::DottedList(_, _) |
LispKind::Undef |
LispKind::Number(_) |
LispKind::String(_) |
LispKind::Bool(_) |
LispKind::AtomMap(_) => CompletionItemKind::Value,
LispKind::Syntax(_) => CompletionItemKind::Event,
LispKind::Proc(_) => CompletionItemKind::Function,
LispKind::Annot(_, _) |
LispKind::Ref(_) => unreachable!()
}))
})
}
}
async fn completion(path: FileRef, _pos: Position) -> result::Result<CompletionResponse, ResponseError> {
let Server {vfs, ..} = &*SERVER;
let file = vfs.get(&path).ok_or_else(||
response_err(ErrorCode::InvalidRequest, "document symbol nonexistent file"))?;
let text = file.text.lock().unwrap().1.clone();
let env = elaborate(path.clone(), Some(Position::default()), Arc::new(AtomicBool::from(false)))
.await.map_err(|e| response_err(ErrorCode::InternalError, format!("{:?}", e)))?.1;
let fe = FormatEnv {source: &text, env: &env};
let mut res = vec![];
for ad in &env.data.0 {
if let Some(ci) = make_completion_item(&path, fe, ad, false, TraceKind::Sort) {res.push(ci)}
if let Some(ci) = make_completion_item(&path, fe, ad, false, TraceKind::Decl) {res.push(ci)}
if let Some(ci) = make_completion_item(&path, fe, ad, false, TraceKind::Global) {res.push(ci)}
}
Ok(CompletionResponse::Array(res))
}
async fn completion_resolve(ci: CompletionItem) -> result::Result<CompletionItem, ResponseError> {
let Server {vfs, ..} = &*SERVER;
let data = ci.data.ok_or_else(|| response_err(ErrorCode::InvalidRequest, "missing data"))?;
let (uri, tk): (Url, TraceKind) = from_value(data).map_err(|e|
response_err(ErrorCode::InvalidRequest, format!("bad JSON {:?}", e)))?;
let path = FileRef::from_url(uri);
let file = vfs.get(&path).ok_or_else(||
response_err(ErrorCode::InvalidRequest, "document symbol nonexistent file"))?;
let text = file.text.lock().unwrap().1.clone();
let env = elaborate(path.clone(), Some(Position::default()), Arc::new(AtomicBool::from(false)))
.await.map_err(|e| response_err(ErrorCode::InternalError, format!("{:?}", e)))?.1;
let fe = FormatEnv {source: &text, env: &env};
env.atoms.get(&*ci.label).and_then(|&a| make_completion_item(&path, fe, &env.data[a], true, tk))
.ok_or_else(|| response_err(ErrorCode::ContentModified, "completion missing"))
}
struct Server {
conn: Connection,
#[allow(unused)]
params: InitializeParams,
caps: Capabilities,
reqs: OpenRequests,
vfs: VFS,
pool: ThreadPool,
}
struct Capabilities {
definition_location_links: bool,
}
impl Capabilities {
fn new(params: &InitializeParams) -> Capabilities {
Capabilities {
definition_location_links: params.capabilities.text_document.as_ref()
.and_then(|d| d.definition.as_ref())
.and_then(|g| g.link_support).unwrap_or(false)
}
}
}
impl Server {
fn new() -> Result<Server> {
let (conn, _iot) = Connection::stdio();
let params = from_value(conn.initialize(
to_value(ServerCapabilities {
text_document_sync: Some(TextDocumentSyncCapability::Kind(TextDocumentSyncKind::Incremental)),
hover_provider: Some(true),
completion_provider: Some(CompletionOptions {
resolve_provider: Some(true),
..Default::default()
}),
definition_provider: Some(true),
document_symbol_provider: Some(true),
..Default::default()
})?
)?)?;
Ok(Server {
caps: Capabilities::new(¶ms),
params,
conn,
reqs: Mutex::new(HashMap::new()),
vfs: VFS(Mutex::new(HashMap::new())),
pool: ThreadPool::new()?
})
}
fn run(&self) {
crossbeam::scope(|s| {
s.spawn(move |_| {
let mut now = Instant::now();
loop {
for (i, id, s) in LOGGER.1.wait(LOGGER.0.lock().unwrap()).unwrap().drain(..) {
let d = i.saturating_duration_since(now).as_millis();
log_message(format!("[{:?}: {:?}ms] {}", id, d, s)).unwrap();
now = i;
}
}
});
let mut count: i64 = 1;
loop {
match (|| -> Result<bool> {
let Server {conn, reqs, vfs, pool, ..} = &*SERVER;
match conn.receiver.recv()? {
Message::Request(req) => {
if conn.handle_shutdown(&req)? {
return Ok(true)
}
if let Some((id, req)) = parse_request(req)? {
let cancel = Arc::new(AtomicBool::new(false));
reqs.lock().unwrap().insert(id.clone(), cancel.clone());
pool.spawn_ok(async {
RequestHandler {id, cancel}.handle(req).await.unwrap()
});
}
}
Message::Response(resp) => {
reqs.lock().unwrap().get(&resp.id).ok_or_else(|| "response to unknown request")?
.store(true, Ordering::Relaxed);
}
Message::Notification(notif) => {
match notif.method.as_str() {
"$/cancelRequest" => {
let CancelParams {id} = from_value(notif.params)?;
if let Some(cancel) = reqs.lock().unwrap().get(&nos_id(id)) {
cancel.store(true, Ordering::Relaxed);
}
}
"textDocument/didOpen" => {
let DidOpenTextDocumentParams {text_document: doc} = from_value(notif.params)?;
let path = FileRef::from_url(doc.uri);
log!("open {:?}", path);
vfs.open_virt(path, doc.version, doc.text)?;
}
"textDocument/didChange" => {
let DidChangeTextDocumentParams {text_document: doc, content_changes} = from_value(notif.params)?;
if !content_changes.is_empty() {
let path = FileRef::from_url(doc.uri);
log!("change {:?}", path);
let start = {
let file = vfs.get(&path).ok_or("changed nonexistent file")?;
let (version, text) = &mut *file.text.lock().unwrap();
*version = Some(doc.version.unwrap_or_else(|| (count, count += 1).0));
let (start, s) = text.apply_changes(content_changes.into_iter());
*text = Arc::new(s);
start
};
pool.spawn_ok(elaborate_and_report(path, Some(start),
Arc::new(AtomicBool::new(false))));
}
}
"textDocument/didClose" => {
let DidCloseTextDocumentParams {text_document: doc} = from_value(notif.params)?;
let path = FileRef::from_url(doc.uri);
log!("close {:?}", path);
vfs.close(&path)?;
}
_ => {}
}
}
}
Ok(false)
})() {
Ok(true) => break,
Ok(false) => {},
Err(e) => eprintln!("Server panicked: {:?}", e)
}
}
}).expect("other thread panicked")
}
}
fn response_err(code: ErrorCode, message: impl Into<String>) -> ResponseError {
ResponseError {code: code as i32, message: message.into(), data: None}
}
pub fn main(mut args: impl Iterator<Item=String>) {
if args.next().map_or(false, |s| s == "--debug") {
std::env::set_var("RUST_BACKTRACE", "1");
use {simplelog::*, std::fs::File};
let _ = WriteLogger::init(LevelFilter::Debug, Config::default(), File::create("lsp.log").unwrap());
}
log_message("started".into()).unwrap();
SERVER.run()
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.