text stringlengths 8 4.13M |
|---|
mod constants;
use clap::{App, Arg};
use log::*;
use std::error::Error;
fn main() -> Result<(), Box<dyn Error>> {
let cli_matches = parse_cli();
init_log(&cli_matches);
logtopus::run(&cli_matches.value_of("config"))
}
fn init_log(matches: &clap::ArgMatches) {
let loglevel = match matches.occurrences_of("v") {
0 => "error",
1 => "warn",
2 => "info",
3 => "debug",
_ => "trace",
};
let loglevel = match matches.value_of("module") {
Some(module) => {
let mut module_loglevel = String::from(module);
module_loglevel.push_str("=");
module_loglevel.push_str(loglevel);
module_loglevel
}
_ => String::from(loglevel),
};
std::env::set_var("RUST_LOG", &loglevel);
env_logger::init();
debug!("Setting log level to {}", &loglevel);
}
fn parse_cli() -> clap::ArgMatches<'static> {
App::new("logtopus server")
.version(constants::VERSION)
.author(constants::AUTHORS)
.about(
"Provides main logtopus server gateway communicating with the tentacles in a cluster.",
)
.arg(
Arg::with_name("config")
// .required(true)
.short("c")
.long("config")
.value_name("FILE")
.help("Sets the configuration file name")
.takes_value(true),
)
.arg(Arg::with_name("v")
.short("v")
.multiple(true)
.help("Level of verbosity (error is default) if used multiple times: warn(v), info(vv), debug(vvv) and trace(vvvv)"))
.get_matches()
}
|
mod ship;
mod ocean;
use ocean::*;
use ship::*;
use std::io::{self, Write};
use text_io::read;
fn main() {
let mut ocean = Ocean::new();
ocean.place_ships_randomly();
loop {
if game_over(&ocean) {
println!("Congratulations! You've won the game!");
println!("-------------------------------------");
println!("Do you want to player another game? (Y/N)");
let answer: String = read!();
if answer.starts_with("Y") {
ocean.clear_ocean();
ocean.place_ships_randomly();
continue;
} else if answer.starts_with("N") {
return;
} else {
println!("Invalid answer... Yes or No ?");
}
}
print!("Enter row: ");
let _ = io::stdout().flush();
let row: usize = read!();
print!("Enter column: ");
let _ = io::stdout().flush();
let column: usize = read!();
if ocean.shoot_at(row, column) {
println!("BAM! HIT!!!");
} else {
println!("...You Missed... :(( ");
}
ocean.print_grid();
let _ = io::stdout().flush();
println!("-------------------------------------");
ocean.print_stats();
}
} |
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
crate::registry::base::{Command, Notifier, State},
crate::registry::service_context::ServiceContext,
crate::switchboard::base::{AccessibilityInfo, SettingRequest, SettingResponse, SettingType},
failure::format_err,
fidl::endpoints::create_proxy,
fidl_fuchsia_accessibility::{SettingsManagerMarker, SettingsManagerStatus},
fuchsia_async as fasync,
fuchsia_syslog::fx_log_err,
futures::stream::StreamExt,
futures::TryFutureExt,
std::sync::{Arc, RwLock},
};
/// Controller that handles commands for SettingType::Accessibility.
/// TODO(fxb/35252): store persistently
pub fn spawn_accessibility_controller(
service_context_handle: Arc<RwLock<ServiceContext>>,
) -> futures::channel::mpsc::UnboundedSender<Command> {
let (accessibility_handler_tx, mut accessibility_handler_rx) =
futures::channel::mpsc::unbounded::<Command>();
// TODO(fxb/35532): switch to parking_lot
let notifier_lock = Arc::<RwLock<Option<Notifier>>>::new(RwLock::new(None));
fasync::spawn(
async move {
// Locally persist audio description value.
// TODO(go/fxb/25465): persist value.
let mut stored_audio_description: bool = false;
while let Some(command) = accessibility_handler_rx.next().await {
match command {
Command::ChangeState(state) => match state {
State::Listen(notifier) => {
*notifier_lock.write().unwrap() = Some(notifier);
}
State::EndListen => {
*notifier_lock.write().unwrap() = None;
}
},
Command::HandleRequest(request, responder) => {
#[allow(unreachable_patterns)]
match request {
SettingRequest::SetAudioDescription(audio_description) => {
let service_result = service_context_handle
.read()
.unwrap()
.connect::<SettingsManagerMarker>();
let accessibility_service = match service_result {
Ok(service) => service,
Err(err) => {
let _ = responder.send(Err(format_err!(
"Error getting accessibility service: {:?}",
err
)));
return Ok(());
}
};
// Register ourselves as a provider to a11y service to write values.
let (provider_proxy, server_end) = create_proxy()?;
let register_result =
accessibility_service.register_setting_provider(server_end);
match register_result {
Ok(_) => {
let status = provider_proxy
.set_screen_reader_enabled(audio_description.into())
.await?;
match status {
SettingsManagerStatus::Ok => {
stored_audio_description = audio_description;
let _ = responder.send(Ok(None));
}
SettingsManagerStatus::Error => {
let _ = responder.send(Err(format_err!(
"error setting value in accessibility service"
)));
}
}
if let Some(notifier) =
(*notifier_lock.read().unwrap()).clone()
{
notifier.unbounded_send(SettingType::Accessibility)?;
}
}
Err(err) => {
let _ = responder.send(Err(format_err!(
"Error registering as settings provider: {:?}",
err
)));
}
}
}
SettingRequest::Get => {
let _ = responder.send(Ok(Some(SettingResponse::Accessibility(
AccessibilityInfo::AudioDescription(stored_audio_description),
))));
}
_ => panic!("Unexpected command to accessibility"),
}
}
}
}
Ok(())
}
.unwrap_or_else(|e: failure::Error| {
fx_log_err!("Error processing accessibility command: {:?}", e)
}),
);
accessibility_handler_tx
}
|
#[doc = "Register `ISR` reader"]
pub type R = crate::R<ISR_SPEC>;
#[doc = "Field `GIF1` reader - global interrupt flag for channel 1"]
pub type GIF1_R = crate::BitReader;
#[doc = "Field `TCIF1` reader - transfer complete (TC) flag for channel 1"]
pub type TCIF1_R = crate::BitReader;
#[doc = "Field `HTIF1` reader - half transfer (HT) flag for channel 1"]
pub type HTIF1_R = crate::BitReader;
#[doc = "Field `TEIF1` reader - transfer error (TE) flag for channel 1"]
pub type TEIF1_R = crate::BitReader;
#[doc = "Field `GIF2` reader - global interrupt flag for channel 2"]
pub type GIF2_R = crate::BitReader;
#[doc = "Field `TCIF2` reader - transfer complete (TC) flag for channel 2"]
pub type TCIF2_R = crate::BitReader;
#[doc = "Field `HTIF2` reader - half transfer (HT) flag for channel 2"]
pub type HTIF2_R = crate::BitReader;
#[doc = "Field `TEIF2` reader - transfer error (TE) flag for channel 2"]
pub type TEIF2_R = crate::BitReader;
#[doc = "Field `GIF3` reader - global interrupt flag for channel 3"]
pub type GIF3_R = crate::BitReader;
#[doc = "Field `TCIF3` reader - transfer complete (TC) flag for channel 3"]
pub type TCIF3_R = crate::BitReader;
#[doc = "Field `HTIF3` reader - half transfer (HT) flag for channel 3"]
pub type HTIF3_R = crate::BitReader;
#[doc = "Field `TEIF3` reader - transfer error (TE) flag for channel 3"]
pub type TEIF3_R = crate::BitReader;
impl R {
#[doc = "Bit 0 - global interrupt flag for channel 1"]
#[inline(always)]
pub fn gif1(&self) -> GIF1_R {
GIF1_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - transfer complete (TC) flag for channel 1"]
#[inline(always)]
pub fn tcif1(&self) -> TCIF1_R {
TCIF1_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - half transfer (HT) flag for channel 1"]
#[inline(always)]
pub fn htif1(&self) -> HTIF1_R {
HTIF1_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - transfer error (TE) flag for channel 1"]
#[inline(always)]
pub fn teif1(&self) -> TEIF1_R {
TEIF1_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - global interrupt flag for channel 2"]
#[inline(always)]
pub fn gif2(&self) -> GIF2_R {
GIF2_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - transfer complete (TC) flag for channel 2"]
#[inline(always)]
pub fn tcif2(&self) -> TCIF2_R {
TCIF2_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 6 - half transfer (HT) flag for channel 2"]
#[inline(always)]
pub fn htif2(&self) -> HTIF2_R {
HTIF2_R::new(((self.bits >> 6) & 1) != 0)
}
#[doc = "Bit 7 - transfer error (TE) flag for channel 2"]
#[inline(always)]
pub fn teif2(&self) -> TEIF2_R {
TEIF2_R::new(((self.bits >> 7) & 1) != 0)
}
#[doc = "Bit 8 - global interrupt flag for channel 3"]
#[inline(always)]
pub fn gif3(&self) -> GIF3_R {
GIF3_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - transfer complete (TC) flag for channel 3"]
#[inline(always)]
pub fn tcif3(&self) -> TCIF3_R {
TCIF3_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - half transfer (HT) flag for channel 3"]
#[inline(always)]
pub fn htif3(&self) -> HTIF3_R {
HTIF3_R::new(((self.bits >> 10) & 1) != 0)
}
#[doc = "Bit 11 - transfer error (TE) flag for channel 3"]
#[inline(always)]
pub fn teif3(&self) -> TEIF3_R {
TEIF3_R::new(((self.bits >> 11) & 1) != 0)
}
}
#[doc = "DMA interrupt status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`isr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct ISR_SPEC;
impl crate::RegisterSpec for ISR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`isr::R`](R) reader structure"]
impl crate::Readable for ISR_SPEC {}
#[doc = "`reset()` method sets ISR to value 0"]
impl crate::Resettable for ISR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
//! User module to handle users
use error::*;
use std::collections::HashMap;
use std::fs::File;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
/// Database of user
pub struct Users(Arc<Mutex<HashMap<String, String>>>, PathBuf);
impl Users {
/// Load a database or create a new one if path doesn't exists
pub fn load<P: AsRef<Path>>(dir: P) -> Result<Users> {
let path = dir.as_ref().join("users.db");
if !path.exists() {
return Ok(Users(Arc::new(Mutex::new(HashMap::new())), path.to_path_buf()));
}
let mut file = File::open(&path)?;
let mut buf = String::new();
file.read_to_string(&mut buf)?;
let mut db = HashMap::new();
for line in buf.split('\n') {
if line.is_empty() {
continue;
}
let line = line.trim();
let words = line.split_whitespace().map(|x| x.to_owned()).collect::<Vec<String>>();
if words.len() > 2 {
bail!(ErrorKind::InvalidUserDB);
}
db.insert(words[0].clone(), words[1].clone());
}
Ok(Users(Arc::new(Mutex::new(db)), path.to_path_buf()))
}
/// Check if the user provided is present and if his password is valid.
pub fn is_valid(&self, user: &str, pass: &str) -> bool {
let lock = self.0.lock().unwrap();
match lock.get(user) {
Some(p) => p == pass,
None => false,
}
}
/// Add a new user to database
pub fn add_user(&self, user: &str, pass: &str) {
let mut lock = self.0.lock().unwrap();
if lock.get(user).is_some() {
return;
}
lock.insert(user.to_owned(), pass.to_owned());
}
}
impl Drop for Users {
fn drop(&mut self) {
let lock = self.0.lock().unwrap();
let mut file = File::create(&self.1).unwrap();
for (key, value) in lock.iter() {
let s = format!("{} {}\n", key, value);
let _ = file.write_all(s.as_bytes());
}
}
}
|
use crate::days::day23::{parse_input, default_input, Node};
use std::collections::HashMap;
pub fn run() {
println!("{}", circle_str(default_input()).unwrap())
}
pub fn circle_str(input : &str) -> Result<i64, ()> {
circle(parse_input(input))
}
pub fn circle(circle : Vec<i64>) -> Result<i64, ()> {
let mut nodes: Vec<Node<i64>> = circle.iter().map(|n| Node::new(*n)).collect();
nodes.append(&mut (circle.len()+1..1000001).map(|n| Node::new(n as i64)).collect());
let mut nxt = HashMap::new();
for i in 0..nodes.len() -1 {
nxt.insert(&nodes[i], &nodes[i+1]);
}
nxt.insert(&nodes[nodes.len() - 1], &nodes[0]);
let lookup : HashMap<_,_> = nodes.iter().map(|n| (n.val, n)).collect();
let max = nodes[nodes.len() -1].val;
let min = *circle.iter().min().unwrap();
let mut curr = &nodes[0];
for _i in 0..10000000 {
let removed = [nxt.get(curr).unwrap().clone(), nxt.get(nxt.get(curr).unwrap()).unwrap().clone(), nxt.get(nxt.get(nxt.get(curr).unwrap()).unwrap()).unwrap().clone()];
nxt.insert(curr, nxt.get(removed[2]).unwrap());
let mut dest = curr.val - 1;
if dest == min - 1 {
dest = max;
}
while removed.iter().any(|n| n.val == dest) {
dest = dest - 1;
if dest == min - 1 {
dest = max;
}
}
let dest = lookup.get(&dest).unwrap().clone();
nxt.insert(removed[2], nxt.get(dest).unwrap());
nxt.insert(dest, removed[0]);
curr = nxt.get(curr).unwrap();
}
let node1 = lookup.get(&1).unwrap().clone();
let nxt_node = nxt.get(node1).unwrap().clone();
let nxt_nxt_node = nxt.get(nxt_node).unwrap().clone();
Ok(nxt_node.val * nxt_nxt_node.val)
}
#[cfg(test)]
pub mod tests {
use super::*;
#[ignore]
#[test]
pub fn part2_answer() {
assert_eq!(circle_str(default_input()).unwrap(), 689500518476)
}
}
|
// Copyright 2015 click2stream, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///! Network scanner for RTSP streams.
use std::io;
use std::fmt;
use std::thread;
use std::result;
use std::fs::File;
use std::sync::Arc;
use std::error::Error;
use std::collections::HashSet;
use std::collections::HashMap;
use std::io::{BufReader, BufRead};
use std::fmt::{Display, Formatter};
use std::net::{IpAddr, SocketAddr, SocketAddrV4, SocketAddrV6};
use net::http;
use net::rtsp;
use net::raw::pcap;
use net::http::Client as HttpClient;
use net::http::ResponseHeader as HttpResponseHeader;
use net::rtsp::Client as RtspClient;
use net::raw::devices::EthernetDevice;
use net::raw::ether::MacAddr;
use net::raw::arp::scanner::Ipv4ArpScanner;
use net::raw::icmp::scanner::IcmpScanner;
use net::arrow::protocol::{Service, ScanReport};
use net::arrow::protocol::{HINFO_FLAG_ARP, HINFO_FLAG_ICMP};
use net::raw::tcp::scanner::{TcpPortScanner, PortCollection};
use net::rtsp::sdp::{SessionDescription, MediaType, RTPMap, FromAttribute};
/// Discovery error.
#[derive(Debug, Clone)]
pub struct DiscoveryError {
msg: String,
}
impl Error for DiscoveryError {
fn description(&self) -> &str {
&self.msg
}
}
impl Display for DiscoveryError {
fn fmt(&self, f: &mut Formatter) -> result::Result<(), fmt::Error> {
f.write_str(&self.msg)
}
}
impl From<String> for DiscoveryError {
fn from(msg: String) -> DiscoveryError {
DiscoveryError { msg: msg }
}
}
impl<'a> From<&'a str> for DiscoveryError {
fn from(msg: &'a str) -> DiscoveryError {
DiscoveryError::from(msg.to_string())
}
}
impl From<http::HttpError> for DiscoveryError {
fn from(err: http::HttpError) -> DiscoveryError {
DiscoveryError::from(format!("HTTP client error: {}", err))
}
}
impl From<rtsp::RtspError> for DiscoveryError {
fn from(err: rtsp::RtspError) -> DiscoveryError {
DiscoveryError::from(format!("RTSP client error: {}", err))
}
}
impl From<pcap::PcapError> for DiscoveryError {
fn from(err: pcap::PcapError) -> DiscoveryError {
DiscoveryError::from(format!("pcap error: {}", err.description()))
}
}
impl From<io::Error> for DiscoveryError {
fn from(err: io::Error) -> DiscoveryError {
DiscoveryError::from(format!("IO error: {}", err))
}
}
/// Discovery result type alias.
pub type Result<T> = result::Result<T, DiscoveryError>;
/// RTSP port candidates.
static RTSP_PORT_CANDIDATES: &'static [u16] = &[
554, 88, 81, 555, 7447,
8554, 7070, 10554, 80, 6667
];
/// HTTP port candidates.
static HTTP_PORT_CANDIDATES: &'static [u16] = &[
80, 81, 8080, 8081, 8090
];
/// Find all RTSP and MJPEG streams and corresponding HTTP services in all
/// local networks.
pub fn scan_network(
rtsp_paths_file: &str,
mjpeg_paths_file: &str) -> Result<ScanReport> {
let mut port_set = HashSet::<u16>::new();
port_set.extend(RTSP_PORT_CANDIDATES);
port_set.extend(HTTP_PORT_CANDIDATES);
let port_candidates = PortCollection::new()
.add_all(port_set);
let mut report = try!(find_all_open_ports(&port_candidates));
// note: we permit only one RTSP service per host (some stupid RTSP servers
// are accessible from more than one port and they tend to crash when they
// are accessed from the "incorrect" one)
let rtsp_ports = try!(find_rtsp_ports(&report, RTSP_PORT_CANDIDATES));
let rtsp_port_priorities = get_port_priorities(RTSP_PORT_CANDIDATES);
let rtsp_ports = filter_duplicit_services(
&rtsp_ports,
&rtsp_port_priorities);
// note: we permit only one HTTP service per host
let http_ports = try!(find_http_ports(&report, HTTP_PORT_CANDIDATES));
let http_port_priorities = get_port_priorities(HTTP_PORT_CANDIDATES);
let http_ports = filter_duplicit_services(
&http_ports,
&http_port_priorities);
let rtsp_services = try!(find_rtsp_services(rtsp_paths_file, &rtsp_ports));
let mjpeg_services = try!(find_mjpeg_services(mjpeg_paths_file, &http_ports));
let mut hosts = Vec::new();
hosts.extend(get_hosts(&rtsp_services));
hosts.extend(get_hosts(&mjpeg_services));
let http_services = find_http_services(&http_ports, &hosts);
for svc in rtsp_services {
report.add_service(svc);
}
for svc in mjpeg_services {
report.add_service(svc);
}
for svc in http_services {
report.add_service(svc);
}
Ok(report)
}
/// Load all path variants from a given file.
fn load_paths(file: &str) -> Result<Vec<String>> {
let file = try!(File::open(file));
let breader = BufReader::new(file);
let mut paths = Vec::new();
for line in breader.lines() {
let path = try!(line);
if !path.starts_with('#') {
paths.push(path);
}
}
Ok(paths)
}
/// Check if a given service is an RTSP service.
fn is_rtsp_service(addr: SocketAddr) -> Result<bool> {
let host = format!("{}", addr.ip());
let port = addr.port();
// treat connection errors as error responses
if let Ok(mut client) = RtspClient::new(&host, port) {
try!(client.set_timeout(Some(1000)));
let response = client.options();
Ok(response.is_ok())
} else {
Ok(false)
}
}
/// Check if a given session description contains at least one H.264 or
/// a general MPEG4 video stream.
fn is_supported_rtsp_service(sdp: &[u8]) -> bool {
if let Ok(sdp) = SessionDescription::parse(sdp) {
let mut vcodecs = HashSet::new();
let video_streams = sdp.media_descriptions.into_iter()
.filter(|md| md.media_type == MediaType::Video);
for md in video_streams {
for attr in md.attributes {
if let Ok(rtpmap) = RTPMap::parse(&attr) {
vcodecs.insert(rtpmap.encoding.to_uppercase());
}
}
}
vcodecs.contains("H264") ||
vcodecs.contains("H264-RCDO") ||
vcodecs.contains("H264-SVC") ||
vcodecs.contains("MP4V-ES") ||
vcodecs.contains("MPEG4-GENERIC")
} else {
false
}
}
/// RTSP DESCRIBE status.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
enum DescribeStatus {
Ok,
Locked,
Unsupported,
NotFound,
Error
}
/// Get describe status for a given RTSP service and path.
fn get_rtsp_describe_status(
addr: SocketAddr,
path: &str) -> Result<DescribeStatus> {
let host = format!("{}", addr.ip());
let port = addr.port();
let mut client;
// treat connection errors as DESCRIBE errors
match RtspClient::new(&host, port) {
Err(_) => return Ok(DescribeStatus::Error),
Ok(c) => client = c
}
try!(client.set_timeout(Some(1000)));
if let Ok(response) = client.describe(path) {
let header = response.header;
let hipcam = match header.get_str("Server") {
Some("HiIpcam/V100R003 VodServer/1.0.0") => true,
Some("Hipcam RealServer/V1.0") => true,
_ => false
};
if hipcam && path != "/11" && path != "/12" {
Ok(DescribeStatus::NotFound)
} else {
match header.code {
404 => Ok(DescribeStatus::NotFound),
401 => Ok(DescribeStatus::Locked),
200 if is_supported_rtsp_service(&response.body) =>
Ok(DescribeStatus::Ok),
200 => Ok(DescribeStatus::Unsupported),
_ => Ok(DescribeStatus::Error)
}
}
} else {
Ok(DescribeStatus::Error)
}
}
/// Check if a given service is an HTTP service.
fn is_http_service(addr: SocketAddr) -> Result<bool> {
let host = format!("{}", addr.ip());
let port = addr.port();
// treat connection errors as error responses
if let Ok(mut client) = HttpClient::new(&host, port) {
try!(client.set_timeout(Some(1000)));
let response = client.get_header("/");
Ok(response.is_ok())
} else {
Ok(false)
}
}
/// Get response header for a given HTTP endpoint or None if the header cannot
/// be retreived.
fn get_http_response_header(
addr: SocketAddr,
path: &str) -> Result<Option<HttpResponseHeader>> {
let host = format!("{}", addr.ip());
let port = addr.port();
// ignore connection errors
if let Ok(mut client) = HttpClient::new(&host, port) {
try!(client.set_timeout(Some(1000)));
if let Ok(header) = client.get_header(path) {
Ok(Some(header))
} else {
Ok(None)
}
} else {
Ok(None)
}
}
/// Find open ports on all available hosts within all local networks accessible
/// directly from this host.
fn find_all_open_ports(ports: &PortCollection) -> Result<ScanReport> {
let tc = pcap::new_threading_context();
let devices = EthernetDevice::list();
let mut threads = Vec::new();
for dev in devices {
let pc = ports.clone();
let tc = tc.clone();
let handle = thread::spawn(move || {
find_open_ports_in_network(tc, &dev, &pc)
});
threads.push(handle);
}
let mut report = ScanReport::new();
for handle in threads {
if let Ok(res) = handle.join() {
report.merge(try!(res));
} else {
return Err(DiscoveryError::from("port scanner thread panicked"));
}
}
Ok(report)
}
/// Find open ports on all available hosts within a given network and port
/// range.
fn find_open_ports_in_network(
pc: pcap::ThreadingContext,
device: &EthernetDevice,
ports: &PortCollection) -> Result<ScanReport> {
let mut report = ScanReport::new();
for (mac, ip) in try!(Ipv4ArpScanner::scan_device(pc.clone(), device)) {
report.add_host(mac, IpAddr::V4(ip), HINFO_FLAG_ARP);
}
for (mac, ip) in try!(IcmpScanner::scan_device(pc.clone(), device)) {
report.add_host(mac, IpAddr::V4(ip), HINFO_FLAG_ICMP);
}
let open_ports = {
let hosts = report.hosts()
.map(|host| (host.mac_addr, host.ip_addr));
try!(find_open_ports(pc, device, hosts, ports))
};
for (mac, addr) in open_ports {
report.add_port(mac, addr.ip(), addr.port());
}
Ok(report)
}
/// Check if any of given TCP ports is open on on any host from a given set.
fn find_open_ports<H: IntoIterator<Item=(MacAddr, IpAddr)>>(
pc: pcap::ThreadingContext,
device: &EthernetDevice,
hosts: H,
ports: &PortCollection) -> Result<Vec<(MacAddr, SocketAddr)>> {
let hosts = hosts.into_iter()
.filter_map(|(mac, ip)| match ip {
IpAddr::V4(ip) => Some((mac, ip)),
_ => None
});
let res = try!(TcpPortScanner::scan_ipv4_hosts(pc, device, hosts, ports))
.into_iter()
.map(|(mac, ip, p)| (mac, SocketAddr::V4(SocketAddrV4::new(ip, p))))
.collect::<Vec<_>>();
Ok(res)
}
/// Find all RTSP services.
fn find_rtsp_ports(
report: &ScanReport,
rtsp_ports: &[u16]) -> Result<Vec<(MacAddr, SocketAddr)>> {
let mut ports = HashSet::<u16>::new();
let mut threads = Vec::new();
let mut res = Vec::new();
ports.extend(rtsp_ports);
for (mac, addr) in report.socket_addrs() {
if ports.contains(&addr.port()) {
let handle = thread::spawn(move || {
(mac, addr, is_rtsp_service(addr))
});
threads.push(handle);
}
}
for handle in threads {
if let Ok((mac, addr, rtsp)) = handle.join() {
if try!(rtsp) {
res.push((mac, addr));
}
} else {
return Err(DiscoveryError::from("RTSP service testing thread panicked"));
}
}
Ok(res)
}
/// Find the first available RTSP path for a given RTSP service.
fn find_rtsp_path(
mac: MacAddr,
addr: SocketAddr,
paths: &[String]) -> Result<Service> {
let mut service = Service::UnknownRTSP(mac, addr);
for path in paths {
let status = try!(get_rtsp_describe_status(addr, path));
if status == DescribeStatus::Ok {
service = Service::RTSP(mac, addr, path.to_string());
} else if status == DescribeStatus::Unsupported {
service = Service::UnsupportedRTSP(mac, addr, path.to_string());
} else if status == DescribeStatus::Locked {
service = Service::LockedRTSP(mac, addr);
}
match status {
DescribeStatus::Ok => break,
DescribeStatus::Locked => break,
_ => ()
}
}
Ok(service)
}
/// Find all RTSP services.
fn find_rtsp_services(
rtsp_paths_file: &str,
rtsp_ports: &[(MacAddr, SocketAddr)]) -> Result<Vec<Service>> {
let paths = Arc::new(try!(load_paths(rtsp_paths_file)));
let mut threads = Vec::new();
let mut res = Vec::new();
for &(ref mac, ref saddr) in rtsp_ports {
let mac = *mac;
let saddr = *saddr;
let paths = paths.clone();
let handle = thread::spawn(move || {
find_rtsp_path(mac, saddr, &paths)
});
threads.push(handle);
}
for handle in threads {
match handle.join() {
Err(_) => return Err(DiscoveryError::from(
"RTSP path testing thread panicked")),
Ok(svc) => res.push(try!(svc))
}
}
Ok(res)
}
/// Find all HTTP services.
fn find_http_ports(
report: &ScanReport,
http_ports: &[u16]) -> Result<Vec<(MacAddr, SocketAddr)>> {
let mut ports = HashSet::<u16>::new();
let mut threads = Vec::new();
let mut res = Vec::new();
ports.extend(http_ports);
for (mac, addr) in report.socket_addrs() {
if ports.contains(&addr.port()) {
let handle = thread::spawn(move || {
(mac, addr, is_http_service(addr))
});
threads.push(handle);
}
}
for handle in threads {
if let Ok((mac, addr, http)) = handle.join() {
if try!(http) {
res.push((mac, addr));
}
} else {
return Err(DiscoveryError::from("HTTP service testing thread panicked"));
}
}
Ok(res)
}
/// Find the first available MJPEG path for a given HTTP service.
fn find_mjpeg_path(
mac: MacAddr,
addr: SocketAddr,
paths: &[String]) -> Result<Option<Service>> {
for path in paths {
if let Some(header) = try!(get_http_response_header(addr, path)) {
if header.code == 200 {
let ctype = header.get_str("content-type")
.unwrap_or("")
.to_lowercase();
if ctype.starts_with("image/jpeg") ||
ctype.starts_with("multipart/x-mixed-replace") {
return Ok(Some(Service::MJPEG(mac, addr, path.to_string())));
}
} else if header.code == 401 {
return Ok(Some(Service::LockedMJPEG(mac, addr)));
}
}
}
Ok(None)
}
/// Find all MJPEG services.
fn find_mjpeg_services(
mjpeg_paths_file: &str,
mjpeg_ports: &[(MacAddr, SocketAddr)]) -> Result<Vec<Service>> {
let paths = Arc::new(try!(load_paths(mjpeg_paths_file)));
let mut threads = Vec::new();
let mut res = Vec::new();
for &(ref mac, ref saddr) in mjpeg_ports {
let mac = *mac;
let saddr = *saddr;
let paths = paths.clone();
let handle = thread::spawn(move || {
find_mjpeg_path(mac, saddr, &paths)
});
threads.push(handle);
}
for handle in threads {
match handle.join() {
Err(_) => return Err(DiscoveryError::from(
"MJPEG path testing thread panicked")),
Ok(svc) => if let Some(svc) = try!(svc) {
res.push(svc)
}
}
}
Ok(res)
}
/// Return all http services on given hosts.
fn find_http_services(
http_ports: &[(MacAddr, SocketAddr)],
hosts: &[IpAddr]) -> Vec<Service> {
let mut host_set = HashSet::<IpAddr>::new();
let mut res = Vec::new();
host_set.extend(hosts);
for &(ref mac, ref saddr) in http_ports {
if host_set.contains(&saddr.ip()) {
res.push(Service::HTTP(*mac, *saddr));
}
}
res
}
/// Assuming the given list of ports is sorted according to port priority
/// (from highest to lowest), get a map of port -> port_priority pairs.
fn get_port_priorities(ports: &[u16]) -> HashMap<u16, usize> {
let mut res = HashMap::new();
let len = ports.len();
for i in 0..len {
res.insert(ports[i], len - i);
}
res
}
/// Filter out duplicit services from a given list using given priorities.
fn filter_duplicit_services(
services: &[(MacAddr, SocketAddr)],
port_priorities: &HashMap<u16, usize>) -> Vec<(MacAddr, SocketAddr)> {
let mut svc_map = HashMap::new();
for &(ref mac, ref saddr) in services {
let mac = *mac;
let ip = saddr.ip();
let port = saddr.port();
if svc_map.contains_key(&ip) {
let old_port = svc_map.get(&ip)
.map(|&(_, _, ref port)| *port)
.unwrap_or(0);
let old_priority = port_priorities.get(&old_port)
.map(|priority| *priority)
.unwrap_or(0);
let new_priority = port_priorities.get(&port)
.map(|priority| *priority)
.unwrap_or(0);
if new_priority > old_priority {
svc_map.insert(ip, (mac, ip, port));
}
} else {
svc_map.insert(ip, (mac, ip, port));
}
}
svc_map.into_iter()
.map(|(_, (mac, ip, port))| match ip {
IpAddr::V4(ip) => (mac, SocketAddr::V4(SocketAddrV4::new(ip, port))),
IpAddr::V6(ip) => (mac, SocketAddr::V6(SocketAddrV6::new(ip, port, 0, 0)))
})
.collect::<_>()
}
/// Get a list of distinct hosts from a given list of services.
fn get_hosts(services: &[Service]) -> Vec<IpAddr> {
let mut hosts = HashSet::new();
for svc in services {
if let Some(saddr) = svc.address() {
hosts.insert(saddr.ip());
}
}
hosts.into_iter()
.collect::<_>()
}
#[cfg(test)]
use std::net::Ipv4Addr;
#[cfg(test)]
#[test]
/// Test the service priority filtering function.
fn test_service_filtering() {
let ports = [554, 80];
let mac = MacAddr::new(0, 0, 0, 0, 0, 0);
let ip = Ipv4Addr::new(0, 0, 0, 0);
let mut services = Vec::new();
services.push((mac, SocketAddr::V4(SocketAddrV4::new(ip, 80))));
services.push((mac, SocketAddr::V4(SocketAddrV4::new(ip, 554))));
let port_priorities = get_port_priorities(&ports);
let services = filter_duplicit_services(&services, &port_priorities);
assert_eq!(services.len(), 1);
assert_eq!(services[0].1.port(), 554);
}
|
use hex;
use single_byte_xor_cipher;
pub struct ScoredXorStrings {
pub score: i32,
pub encrypted_strings: String
}
impl ScoredXorStrings {
fn new() -> ScoredXorStrings {
ScoredXorStrings {
score: 0,
encrypted_strings: String::new()
}
}
}
pub fn detect_single_xor(data: String) -> ScoredXorStrings {
data
.lines()
.map(|line| single_byte_xor_cipher::decrypt(hex::decode(line).unwrap()))
.fold(ScoredXorStrings::new(), |acc, decrypted_line| {
let score = single_byte_xor_cipher::score_xored_hashes(decrypted_line.decoded.as_bytes().to_vec());
if score > acc.score {
return ScoredXorStrings {
score,
encrypted_strings: decrypted_line.decoded
};
}
acc
})
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
#[test]
fn test_detection() {
let data = fs::read_to_string("encrypted_strings.txt").expect("Unable to read file");
let decrypted = detect_single_xor(data);
let actual = "Now that the party is jumping\n";
assert_eq!(actual, &decrypted.encrypted_strings);
}
} |
/// Platform specific constants
///
pub use super::board::consts::*;
pub const KERNEL_OFFSET: usize = 0x80100000;
pub const MEMORY_OFFSET: usize = 0x8000_0000;
pub const USER_STACK_OFFSET: usize = 0x80000000 - USER_STACK_SIZE;
pub const USER_STACK_SIZE: usize = 0x10000;
pub const MAX_DTB_SIZE: usize = 0x2000;
|
use crate::{BoxFuture, Result};
use std::any::Any;
pub trait Provider: Any + Send + Sync {
fn cancel(&self);
fn commit(&self) -> BoxFuture<'_, Result<()>>;
}
|
use libbgmrank::{Histogram, Item, MAX_RATING};
mod init;
fn get_all_items(args: &init::Args) -> Vec<Item> {
let mut result = vec![];
for category in args.categories.iter() {
for state in args.states.iter() {
println!("fetching {}: {}/{}", args.username, category, state);
result.extend(libbgmrank::get_items(
&args.username,
category,
state,
|page| {
println!(" fetching page {}...", page);
},
));
}
}
println!();
result
}
const MAX_COL_WIDTH: usize = 70;
fn main() {
let args = init::handle_opts();
let all_items = get_all_items(&args);
let hist: Histogram = all_items.iter().collect();
for tag_stats in libbgmrank::generate_tag_stats(&all_items) {
println!(
"{} {}: {}/{}",
tag_stats.stats.rating, tag_stats.tag, tag_stats.stats.rated, tag_stats.stats.total
);
}
println!();
let (_, max_rated) = hist.get_max_rated();
let stats = hist.get_stats();
for rating in 1..(MAX_RATING + 1) {
let rated = hist[Some(rating)];
let num = (rated as f32 / max_rated as f32 * MAX_COL_WIDTH as f32).round() as usize;
let bar = "#".repeat(num) + if num > 0 { " " } else { "" };
println!("{:>2}: {}{}", rating, bar, rated);
}
println!("rated: {}/{}", stats.rated, stats.total);
println!("rating: {}", stats.rating);
}
|
use http_router::class_view::{HttpWays, ViewBuilder};
extern crate futures;
extern crate hyper;
extern crate hyper_tls;
use baidu;
use futures::{future, Future, Stream};
// use hyper::client::HttpConnector;
use http_router::constraint::{INDEX, NOTFOUND};
use hyper::client::HttpConnector;
use hyper::{Body, Chunk, Client, Method, Request, Response, Server, StatusCode};
use serde_json;
use std::str;
use std::sync::{Arc, Mutex, MutexGuard};
pub struct ImgRecog {
bd: Arc<Mutex<baidu::Baidu>>,
}
impl ViewBuilder for ImgRecog {
fn new(bd: Arc<Mutex<baidu::Baidu>>) -> ImgRecog {
ImgRecog { bd }
}
fn as_view(bd: Arc<Mutex<baidu::Baidu>>) -> Box<ImgRecog> {
Box::new(ImgRecog::new(bd))
}
}
#[derive(Debug, Serialize, Deserialize)]
struct ImgReq {
img_content: String,
top_num: i32,
}
impl HttpWays for ImgRecog {
fn post(
&self,
req: Request<Body>,
re_url_matched: &'static str,
) -> Box<Future<Item = Response<Body>, Error = hyper::Error> + Send> {
let mut response = Response::new(Body::empty());
let tt_bd = self.bd.clone();
let reversed = req
.into_body()
// A future of when we finally have the full body...
.concat2()
// `move` the `Response` into this future...
.map(|chunk| {
let body = chunk.to_vec();
let body = str::from_utf8(&body).unwrap().to_string();
println!("{:?}", body);
body
})
.and_then(
move |body| {
let mut tt_bd = tt_bd.lock().unwrap();
tt_bd.recog_proxy(body)
}
);
Box::new(reversed)
}
}
|
use super::vector::{Vec2, Vec2f, Vec2i, Vec3, Vec3f, Vec3i, Vector};
use std::io::{self, Read, Write};
use std::thread;
use termion::raw::IntoRawMode;
use termion::{clear, color, cursor};
fn render<W: Write>(out: &mut W, pixel: &PixelBuffer) {
match pixel.color {
Color::Red => write!(out, "{}#", color::Fg(color::Red)),
Color::Blue => write!(out, "{}#", color::Fg(color::Blue)),
Color::Black => write!(out, "{}#", color::Fg(color::Black)),
}
.unwrap();
}
fn rotate_y(point: &Vec3f, rad: f32) -> Vec3f {
Vec3(
point.0 * rad.cos() + point.2 * rad.sin(),
point.1,
-point.0 * rad.sin() + point.2 * rad.cos(),
)
}
fn inside(p0: &Vec2f, p1: &Vec2f, p2: &Vec2f, p: &Vec2f) -> bool {
let d_p1_x = p1.0 - p0.0;
let d_p1_y = p1.1 - p0.1;
let d_p2_x = p2.0 - p0.0;
let d_p2_y = p2.1 - p0.1;
let d_x = p.0 as f32 + 0.5 - p0.0;
let d_y = p.1 as f32 + 0.5 - p0.1;
let c1 = d_x * d_p1_y - d_y * d_p1_x;
let c2 = d_x * d_p2_y - d_y * d_p2_x;
c1 * c2 <= 0.0
}
fn basis(v0: &Vec2f, v1: &Vec2f, p: &Vec2f) -> Option<(f32, f32)> {
if v0.cross(&v1) == 0.0 {
return None;
}
if v0.0 != 0.0 {
let b = (p.1 - v0.1 * p.0 / v0.0) / (v1.1 - v0.1 * v1.0 / v0.0);
let a = (p.0 - b * v1.0) / v0.0;
return Some((a, b));
} else {
let b = (p.1 - v1.1 * p.0 / v1.0) / (v0.1 - v1.1 * v0.0 / v1.0);
let a = (p.0 - b * v0.0) / v1.0;
return Some((a, b));
}
}
#[derive(Debug, Copy, Clone)]
enum Color {
Red,
Blue,
Black,
}
struct Vertex(Vec3f, Color);
struct PixelBuffer {
color: Color,
depth: f32,
}
fn rasterize(
v0: &Vertex,
v1: &Vertex,
v2: &Vertex,
screen_buffer: &mut [Option<PixelBuffer>],
width: i32,
height: i32,
) {
let center = Vec2((width as f32) / 2.0, (height as f32) / 2.0);
let p0_proj = Vec2((v0.0).0, (v0.0).1)
.scal(100.0 / (100.0 + (v0.0).2))
.add(¢er);
let p1_proj = Vec2((v1.0).0, (v1.0).1)
.scal(100.0 / (100.0 + (v1.0).2))
.add(¢er);
let p2_proj = Vec2((v2.0).0, (v2.0).1)
.scal(100.0 / (100.0 + (v2.0).2))
.add(¢er);
let min_x = p0_proj
.0
.min(p1_proj.0)
.min(p2_proj.0)
.max(0.0)
.min(width as f32 - 1.0)
.round() as i32;
let max_x = p0_proj
.0
.max(p1_proj.0)
.max(p2_proj.0)
.max(0.0)
.min(width as f32 - 1.0)
.round() as i32;
let min_y = p0_proj
.1
.min(p1_proj.1)
.min(p2_proj.1)
.max(0.0)
.min(height as f32 - 1.0)
.round() as i32;
let max_y = p0_proj
.1
.max(p1_proj.1)
.max(p2_proj.1)
.max(0.0)
.min(height as f32 - 1.0)
.round() as i32;
for y in min_y..max_y {
for x in min_x..max_x {
let p = Vec2(x as f32 + 0.5, y as f32 + 0.5);
if inside(&p0_proj, &p1_proj, &p2_proj, &p) && inside(&p1_proj, &p2_proj, &p0_proj, &p)
{
let mut depth = -1000.0;
if let Some((a, b)) = basis(
&p1_proj.sub(&p0_proj),
&p2_proj.sub(&p0_proj),
&p.sub(&p0_proj),
) {
depth = (v0.0).2 + v1.0.sub(&v0.0).scal(a).2 + v2.0.sub(&v0.0).scal(b).2;
}
let mut pb = PixelBuffer {
color: v0.1,
depth: depth,
};
if let Some(tmp) = screen_buffer[(y * width + x) as usize].take() {
if tmp.depth < depth {
pb = tmp;
}
}
screen_buffer[(y * width + x) as usize] = Some(pb);
}
}
}
}
pub fn test() {
let stdout = io::stdout();
let stdout = stdout.lock();
let mut stdout = stdout.into_raw_mode().unwrap();
let termsize = termion::terminal_size().ok();
let width = termsize.map(|(w, _)| w - 2).unwrap_or(80);
let height = termsize.map(|(_, h)| h - 2).unwrap_or(40);
let mut buffer: Vec<Option<PixelBuffer>> = vec![];
for _ in 0..width * height {
buffer.push(None);
}
let mut vecs = [
Vertex(Vec3(-20.0, -10.0, 20.0), Color::Blue),
Vertex(Vec3(20.0, -10.0, 20.0), Color::Blue),
Vertex(Vec3(-20.0, 10.0, 20.0), Color::Blue),
Vertex(Vec3(-20.0, 10.0, 20.0), Color::Red),
Vertex(Vec3(20.0, -10.0, 20.0), Color::Red),
Vertex(Vec3(20.0, 10.0, 20.0), Color::Red),
Vertex(Vec3(-20.0, -10.0, -20.0), Color::Blue),
Vertex(Vec3(20.0, -10.0, -20.0), Color::Blue),
Vertex(Vec3(20.0, 10.0, -20.0), Color::Blue),
Vertex(Vec3(-20.0, 10.0, -20.0), Color::Red),
Vertex(Vec3(-20.0, -10.0, -20.0), Color::Red),
Vertex(Vec3(20.0, 10.0, -20.0), Color::Red),
Vertex(Vec3(-20.0, -10.0, -20.0), Color::Blue),
Vertex(Vec3(-20.0, -10.0, 20.0), Color::Blue),
Vertex(Vec3(-20.0, 10.0, -20.0), Color::Blue),
Vertex(Vec3(-20.0, -10.0, 20.0), Color::Red),
Vertex(Vec3(-20.0, 10.0, -20.0), Color::Red),
Vertex(Vec3(-20.0, 10.0, 20.0), Color::Red),
Vertex(Vec3(20.0, -10.0, -20.0), Color::Blue),
Vertex(Vec3(20.0, -10.0, 20.0), Color::Blue),
Vertex(Vec3(20.0, 10.0, 20.0), Color::Blue),
Vertex(Vec3(20.0, -10.0, -20.0), Color::Red),
Vertex(Vec3(20.0, 10.0, -20.0), Color::Red),
Vertex(Vec3(20.0, 10.0, 20.0), Color::Red),
];
let default = PixelBuffer {
color: Color::Black,
depth: 0.0,
};
print!("{}", clear::All);
for _ in 0..200 {
for i in 0..width * height {
buffer[i as usize] = None;
}
for i in 0..vecs.len() {
vecs[i] = Vertex(rotate_y(&vecs[i].0, 0.2), vecs[i].1);
}
for i in 0..vecs.len() / 3 {
rasterize(
&vecs[3 * i],
&vecs[3 * i + 1],
&vecs[3 * i + 2],
&mut buffer[..],
width as i32,
height as i32,
);
}
for i in 0..width * height {
if i % width == 0 {
write!(stdout, "{}", cursor::Goto(1, (i / width) as u16 + 1,));
}
if let Some(pixel) = &buffer[i as usize] {
render(&mut stdout, pixel);
} else {
render(&mut stdout, &default);
}
}
thread::sleep_ms(100);
}
}
|
use std::io::Write;
use std::mem;
use byteorder::{ByteOrder, WriteBytesExt};
use nom::*;
use errors::{PcapError, Result};
use pcapng::block::Block;
use pcapng::blocks::timestamp::{self, ReadTimestamp, Timestamp};
use pcapng::options::{parse_options, Opt, Options};
use traits::WriteTo;
pub const BLOCK_TYPE: u32 = 0x0000_0005;
pub const ISB_STARTTIME: u16 = 2;
pub const ISB_ENDTIME: u16 = 3;
pub const ISB_IFRECV: u16 = 4;
pub const ISB_IFDROP: u16 = 5;
pub const ISB_FILTERACCEPT: u16 = 6;
pub const ISB_OSDROP: u16 = 7;
pub const ISB_USRDELIV: u16 = 8;
/// This option specifies the time the capture started
pub fn isb_starttime<'a, T: ByteOrder>(ticks: Timestamp) -> Opt<'a> {
Opt::u64::<T>(
ISB_STARTTIME,
(u64::from(ticks as u32) << 32) + (ticks >> 32),
)
}
/// This option specifies the time the capture ended
pub fn isb_endtime<'a, T: ByteOrder>(ticks: Timestamp) -> Opt<'a> {
Opt::u64::<T>(ISB_ENDTIME, (u64::from(ticks as u32) << 32) + (ticks >> 32))
}
/// This option specifies the number of packets received from the physical interface
/// starting from the beginning of the capture.
pub fn isb_ifrecv<'a, T: ByteOrder>(count: u64) -> Opt<'a> {
Opt::u64::<T>(ISB_IFRECV, count)
}
/// This option specifies the number of packets dropped by the interface
/// due to lack of resources starting from the beginning of the capture.
pub fn isb_ifdrop<'a, T: ByteOrder>(count: u64) -> Opt<'a> {
Opt::u64::<T>(ISB_IFDROP, count)
}
/// This option specifies the number of packets accepted by filter
/// starting from the beginning of the capture.
pub fn isb_filteraccept<'a, T: ByteOrder>(count: u64) -> Opt<'a> {
Opt::u64::<T>(ISB_FILTERACCEPT, count)
}
/// This option specifies the number of packets
/// dropped by the operating system starting from the beginning of the capture.
pub fn isb_osdrop<'a, T: ByteOrder>(count: u64) -> Opt<'a> {
Opt::u64::<T>(ISB_OSDROP, count)
}
/// This option specifies the number of packets
/// delivered to the user starting from the beginning of the capture.
pub fn isb_usrdeliv<'a, T: ByteOrder>(count: u64) -> Opt<'a> {
Opt::u64::<T>(ISB_USRDELIV, count)
}
/// The Interface Statistics Block (ISB) contains the capture statistics for a given interface and it is optional.
#[derive(Clone, Debug, PartialEq)]
pub struct InterfaceStatistics<'a> {
/// specifies the interface these statistics refers to.
pub interface_id: u32,
/// the number of units of time that have elapsed since 1970-01-01 00:00:00 UTC.
pub timestamp: Timestamp,
/// optionally, a list of options
pub options: Options<'a>,
}
impl<'a> InterfaceStatistics<'a> {
pub fn block_type() -> u32 {
BLOCK_TYPE
}
pub fn size(&self) -> usize {
self.options
.iter()
.fold(mem::size_of::<u32>() * 3, |size, opt| size + opt.size())
}
pub fn parse(buf: &'a [u8], endianness: Endianness) -> Result<(&'a [u8], Self)> {
parse_interface_statistics(buf, endianness).map_err(|err| PcapError::from(err).into())
}
/// This option specifies the time the capture started
pub fn starttime<T: ByteOrder>(&self) -> Option<u64> {
self.options
.iter()
.find(|opt| opt.code == ISB_STARTTIME && opt.value.len() == mem::size_of::<u32>() * 2)
.and_then(|opt| opt.value.as_ref().read_timestamp::<T>().ok())
}
/// This option specifies the time the capture ended
pub fn endtime<T: ByteOrder>(&self) -> Option<u64> {
self.options
.iter()
.find(|opt| opt.code == ISB_ENDTIME && opt.value.len() == mem::size_of::<u32>() * 2)
.and_then(|opt| opt.value.as_ref().read_timestamp::<T>().ok())
}
/// This option specifies the number of packets received from the physical interface
/// starting from the beginning of the capture.
pub fn ifrecv<T: ByteOrder>(&self) -> Option<u64> {
self.options
.iter()
.find(|opt| opt.code == ISB_IFRECV && opt.value.len() == mem::size_of::<u64>())
.map(|opt| T::read_u64(&opt.value))
}
/// This option specifies the number of packets dropped by the interface
/// due to lack of resources starting from the beginning of the capture.
pub fn ifdrop<T: ByteOrder>(&self) -> Option<u64> {
self.options
.iter()
.find(|opt| opt.code == ISB_IFDROP && opt.value.len() == mem::size_of::<u64>())
.map(|opt| T::read_u64(&opt.value))
}
/// This option specifies the number of packets accepted by filter
/// starting from the beginning of the capture.
pub fn filteraccept<T: ByteOrder>(&self) -> Option<u64> {
self.options
.iter()
.find(|opt| opt.code == ISB_FILTERACCEPT && opt.value.len() == mem::size_of::<u64>())
.map(|opt| T::read_u64(&opt.value))
}
/// This option specifies the number of packets
/// dropped by the operating system starting from the beginning of the capture.
pub fn osdrop<T: ByteOrder>(&self) -> Option<u64> {
self.options
.iter()
.find(|opt| opt.code == ISB_OSDROP && opt.value.len() == mem::size_of::<u64>())
.map(|opt| T::read_u64(&opt.value))
}
/// This option specifies the number of packets
/// delivered to the user starting from the beginning of the capture.
pub fn usrdeliv<T: ByteOrder>(&self) -> Option<u64> {
self.options
.iter()
.find(|opt| opt.code == ISB_USRDELIV && opt.value.len() == mem::size_of::<u64>())
.map(|opt| T::read_u64(&opt.value))
}
}
/// 0 1 2 3
/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
/// +---------------------------------------------------------------+
/// 0 | Block Type = 0x00000005 |
/// +---------------------------------------------------------------+
/// 4 | Block Total Length |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// 8 | Interface ID |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// 12 | Timestamp (High) |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// 16 | Timestamp (Low) |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// 20 / /
/// / Options (variable) /
/// / /
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// | Block Total Length |
/// +---------------------------------------------------------------+
named_args!(parse_interface_statistics(endianness: Endianness)<InterfaceStatistics>,
dbg_dmp!(do_parse!(
interface_id: u32!(endianness) >>
timestamp_hi: u32!(endianness) >>
timestamp_lo: u32!(endianness) >>
options: apply!(parse_options, endianness) >>
(
InterfaceStatistics {
interface_id,
timestamp: timestamp::new(timestamp_hi, timestamp_lo),
options,
}
)
))
);
impl<'a> WriteTo for InterfaceStatistics<'a> {
fn write_to<T: ByteOrder, W: Write>(&self, w: &mut W) -> Result<usize> {
w.write_u32::<T>(self.interface_id)?;
self.timestamp.write_to::<T, _>(w)?;
self.options.write_to::<T, _>(w)?;
Ok(self.size())
}
}
impl<'a> Block<'a> {
pub fn is_interface_statistics(&self) -> bool {
self.ty == BLOCK_TYPE
}
pub fn as_interface_statistics(
&'a self,
endianness: Endianness,
) -> Option<InterfaceStatistics<'a>> {
if self.is_interface_statistics() {
InterfaceStatistics::parse(&self.body, endianness)
.map(|(_, packet)| packet)
.map_err(|err| {
warn!("fail to parse interface statistics: {:?}", err);
hexdump!(self.body);
err
})
.ok()
} else {
None
}
}
}
#[cfg(test)]
pub mod tests {
use byteorder::LittleEndian;
use super::*;
use pcapng::{comment, Block};
pub const LE_INTERFACE_STATISTICS: &[u8] = b"\x05\x00\x00\x00\
\x6C\x00\x00\x00\
\x00\x00\x00\x00\
\xAD\x72\x05\x00\xEF\x9E\x23\x23\
\x01\x00\x1C\x00Counters provided by dumpcap\
\x02\x00\x08\x00\xAD\x72\x05\x00\x03\xBD\xEA\x22\
\x03\x00\x08\x00\xAD\x72\x05\x00\xDB\x9E\x23\x23\
\x04\x00\x08\x00\x32\x00\x00\x00\x00\x00\x00\x00\
\x05\x00\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x00\x00\
\x6C\x00\x00\x00";
lazy_static! {
static ref INTERFACE_STATISTICS: InterfaceStatistics<'static> = InterfaceStatistics {
interface_id: 0,
timestamp: 0x000572ad_23239eef,
options: vec![
comment("Counters provided by dumpcap"),
isb_starttime::<LittleEndian>(0x000572AD_22EABD03),
isb_endtime::<LittleEndian>(0x000572AD_23239EDB),
isb_ifrecv::<LittleEndian>(50),
isb_ifdrop::<LittleEndian>(0),
],
};
}
#[test]
fn test_parse() {
let (remaining, block) = Block::parse(LE_INTERFACE_STATISTICS, Endianness::Little).unwrap();
assert_eq!(remaining, b"");
assert_eq!(block.ty, BLOCK_TYPE);
assert_eq!(block.size(), LE_INTERFACE_STATISTICS.len());
let interface_statistics = block.as_interface_statistics(Endianness::Little).unwrap();
assert_eq!(interface_statistics, *INTERFACE_STATISTICS);
}
#[test]
fn test_write() {
let mut buf = vec![];
let wrote = INTERFACE_STATISTICS
.write_to::<LittleEndian, _>(&mut buf)
.unwrap();
assert_eq!(wrote, INTERFACE_STATISTICS.size());
assert_eq!(
buf.as_slice(),
&LE_INTERFACE_STATISTICS[8..LE_INTERFACE_STATISTICS.len() - 4]
);
}
#[test]
fn test_options() {
let interface_statistics = InterfaceStatistics {
interface_id: 0,
timestamp: 0,
options: vec![
isb_starttime::<LittleEndian>(0x000572AD_22EABD03),
isb_endtime::<LittleEndian>(0x000572AD_23239EDB),
isb_ifrecv::<LittleEndian>(123),
isb_ifdrop::<LittleEndian>(456),
isb_filteraccept::<LittleEndian>(789),
isb_osdrop::<LittleEndian>(456),
isb_usrdeliv::<LittleEndian>(123),
],
};
let mut buf = vec![];
interface_statistics
.write_to::<LittleEndian, _>(&mut buf)
.unwrap();
let (_, interface_statistics) =
InterfaceStatistics::parse(&buf, Endianness::Little).unwrap();
assert_eq!(
interface_statistics.starttime::<LittleEndian>().unwrap(),
0x000572AD_22EABD03
);
assert_eq!(
interface_statistics.endtime::<LittleEndian>().unwrap(),
0x000572AD_23239EDB
);
assert_eq!(interface_statistics.ifrecv::<LittleEndian>().unwrap(), 123);
assert_eq!(interface_statistics.ifdrop::<LittleEndian>().unwrap(), 456);
assert_eq!(
interface_statistics.filteraccept::<LittleEndian>().unwrap(),
789
);
assert_eq!(interface_statistics.osdrop::<LittleEndian>().unwrap(), 456);
assert_eq!(
interface_statistics.usrdeliv::<LittleEndian>().unwrap(),
123
);
}
}
|
mod set_1;
mod set_2;
mod set_3;
mod set_4;
|
use sqlx::database::HasArguments;
pub type Query<'a> =
sqlx::query::Query<'a, sqlx::Sqlite, <sqlx::Sqlite as HasArguments<'a>>::Arguments>;
pub type QueryAs<'a, T> =
sqlx::query::QueryAs<'a, sqlx::Sqlite, T, <sqlx::Sqlite as HasArguments<'a>>::Arguments>;
|
use anyhow::Context;
use rusqlite::{named_params, params, OptionalExtension, Transaction};
use stark_hash::StarkHash;
use web3::types::H256;
use crate::{
consts::{GOERLI_GENESIS_HASH, MAINNET_GENESIS_HASH},
core::{
Chain, ClassHash, ContractAddress, ContractRoot, ContractStateHash, EthereumBlockHash,
EthereumBlockNumber, EthereumLogIndex, EthereumTransactionHash, EthereumTransactionIndex,
EventData, EventKey, GasPrice, GlobalRoot, SequencerAddress, StarknetBlockHash,
StarknetBlockNumber, StarknetBlockTimestamp, StarknetTransactionHash,
},
ethereum::{log::StateUpdateLog, BlockOrigin, EthOrigin, TransactionOrigin},
rpc::types::reply::StateUpdate,
sequencer::reply::transaction,
};
/// Contains the [L1 Starknet update logs](StateUpdateLog).
pub struct L1StateTable {}
/// Identifies block in some [L1StateTable] queries.
pub enum L1TableBlockId {
Number(StarknetBlockNumber),
Latest,
}
impl From<StarknetBlockNumber> for L1TableBlockId {
fn from(number: StarknetBlockNumber) -> Self {
L1TableBlockId::Number(number)
}
}
impl L1StateTable {
/// Inserts a new [update](StateUpdateLog), replaces if it already exists.
pub fn upsert(tx: &Transaction<'_>, update: &StateUpdateLog) -> anyhow::Result<()> {
tx.execute(
r"INSERT OR REPLACE INTO l1_state (
starknet_block_number,
starknet_global_root,
ethereum_block_hash,
ethereum_block_number,
ethereum_transaction_hash,
ethereum_transaction_index,
ethereum_log_index
) VALUES (
:starknet_block_number,
:starknet_global_root,
:ethereum_block_hash,
:ethereum_block_number,
:ethereum_transaction_hash,
:ethereum_transaction_index,
:ethereum_log_index
)",
named_params! {
":starknet_block_number": update.block_number,
":starknet_global_root": &update.global_root,
":ethereum_block_hash": &update.origin.block.hash.0[..],
":ethereum_block_number": update.origin.block.number.0,
":ethereum_transaction_hash": &update.origin.transaction.hash.0[..],
":ethereum_transaction_index": update.origin.transaction.index.0,
":ethereum_log_index": update.origin.log_index.0,
},
)?;
Ok(())
}
/// Deletes all rows from __head down-to reorg_tail__
/// i.e. it deletes all rows where `block number >= reorg_tail`.
pub fn reorg(tx: &Transaction<'_>, reorg_tail: StarknetBlockNumber) -> anyhow::Result<()> {
tx.execute(
"DELETE FROM l1_state WHERE starknet_block_number >= ?",
[reorg_tail],
)?;
Ok(())
}
/// Returns the [root](GlobalRoot) of the given block.
pub fn get_root(
tx: &Transaction<'_>,
block: L1TableBlockId,
) -> anyhow::Result<Option<GlobalRoot>> {
let mut statement = match block {
L1TableBlockId::Number(_) => {
tx.prepare("SELECT starknet_global_root FROM l1_state WHERE starknet_block_number = ?")
}
L1TableBlockId::Latest => tx
.prepare("SELECT starknet_global_root FROM l1_state ORDER BY starknet_block_number DESC LIMIT 1"),
}?;
let mut rows = match block {
L1TableBlockId::Number(number) => statement.query([number]),
L1TableBlockId::Latest => statement.query([]),
}?;
let row = rows.next()?;
let row = match row {
Some(row) => row,
None => return Ok(None),
};
row.get("starknet_global_root")
.map(Some)
.map_err(|e| e.into())
}
/// Returns the [update](StateUpdateLog) of the given block.
pub fn get(
tx: &Transaction<'_>,
block: L1TableBlockId,
) -> anyhow::Result<Option<StateUpdateLog>> {
let mut statement = match block {
L1TableBlockId::Number(_) => tx.prepare(
r"SELECT starknet_block_number,
starknet_global_root,
ethereum_block_hash,
ethereum_block_number,
ethereum_transaction_hash,
ethereum_transaction_index,
ethereum_log_index
FROM l1_state WHERE starknet_block_number = ?",
),
L1TableBlockId::Latest => tx.prepare(
r"SELECT starknet_block_number,
starknet_global_root,
ethereum_block_hash,
ethereum_block_number,
ethereum_transaction_hash,
ethereum_transaction_index,
ethereum_log_index
FROM l1_state ORDER BY starknet_block_number DESC LIMIT 1",
),
}?;
let mut rows = match block {
L1TableBlockId::Number(number) => statement.query([number]),
L1TableBlockId::Latest => statement.query([]),
}?;
let row = rows.next()?;
let row = match row {
Some(row) => row,
None => return Ok(None),
};
let starknet_block_number = row.get_unwrap("starknet_block_number");
let starknet_global_root = row.get_unwrap("starknet_global_root");
let ethereum_block_hash = row.get_ref_unwrap("ethereum_block_hash").as_blob().unwrap();
let ethereum_block_hash = EthereumBlockHash(H256(ethereum_block_hash.try_into().unwrap()));
let ethereum_block_number = row
.get_ref_unwrap("ethereum_block_number")
.as_i64()
.unwrap() as u64;
let ethereum_block_number = EthereumBlockNumber(ethereum_block_number);
let ethereum_transaction_hash = row
.get_ref_unwrap("ethereum_transaction_hash")
.as_blob()
.unwrap();
let ethereum_transaction_hash =
EthereumTransactionHash(H256(ethereum_transaction_hash.try_into().unwrap()));
let ethereum_transaction_index = row
.get_ref_unwrap("ethereum_transaction_index")
.as_i64()
.unwrap() as u64;
let ethereum_transaction_index = EthereumTransactionIndex(ethereum_transaction_index);
let ethereum_log_index = row.get_ref_unwrap("ethereum_log_index").as_i64().unwrap() as u64;
let ethereum_log_index = EthereumLogIndex(ethereum_log_index);
Ok(Some(StateUpdateLog {
origin: EthOrigin {
block: BlockOrigin {
hash: ethereum_block_hash,
number: ethereum_block_number,
},
transaction: TransactionOrigin {
hash: ethereum_transaction_hash,
index: ethereum_transaction_index,
},
log_index: ethereum_log_index,
},
global_root: starknet_global_root,
block_number: starknet_block_number,
}))
}
}
pub struct RefsTable {}
impl RefsTable {
/// Returns the current L1-L2 head. This indicates the latest block for which L1 and L2 agree.
pub fn get_l1_l2_head(tx: &Transaction<'_>) -> anyhow::Result<Option<StarknetBlockNumber>> {
// This table always contains exactly one row.
tx.query_row("SELECT l1_l2_head FROM refs WHERE idx = 1", [], |row| {
row.get::<_, Option<_>>(0)
})
.map_err(|e| e.into())
}
/// Sets the current L1-L2 head. This should indicate the latest block for which L1 and L2 agree.
pub fn set_l1_l2_head(
tx: &Transaction<'_>,
head: Option<StarknetBlockNumber>,
) -> anyhow::Result<()> {
tx.execute("UPDATE refs SET l1_l2_head = ? WHERE idx = 1", [head])?;
Ok(())
}
}
/// Stores all known [StarknetBlocks][StarknetBlock].
pub struct StarknetBlocksTable {}
impl StarknetBlocksTable {
/// Insert a new [StarknetBlock]. Fails if the block number is not unique.
///
/// Version is the [`crate::sequencer::reply::Block::starknet_version`].
pub fn insert(
tx: &Transaction<'_>,
block: &StarknetBlock,
version: Option<&str>,
) -> anyhow::Result<()> {
let version_id = if let Some(version) = version {
Some(StarknetVersionsTable::intern(tx, version)?)
} else {
None
};
tx.execute(
r"INSERT INTO starknet_blocks ( number, hash, root, timestamp, gas_price, sequencer_address, version_id)
VALUES (:number, :hash, :root, :timestamp, :gas_price, :sequencer_address, :version_id)",
named_params! {
":number": block.number,
":hash": block.hash,
":root": block.root,
":timestamp": block.timestamp,
":gas_price": &block.gas_price.to_be_bytes(),
":sequencer_address": block.sequencer_address,
":version_id": version_id,
},
)?;
Ok(())
}
/// Returns the requested [StarknetBlock].
pub fn get(
tx: &Transaction<'_>,
block: StarknetBlocksBlockId,
) -> anyhow::Result<Option<StarknetBlock>> {
let mut statement = match block {
StarknetBlocksBlockId::Number(_) => tx.prepare(
"SELECT hash, number, root, timestamp, gas_price, sequencer_address
FROM starknet_blocks WHERE number = ?",
),
StarknetBlocksBlockId::Hash(_) => tx.prepare(
"SELECT hash, number, root, timestamp, gas_price, sequencer_address
FROM starknet_blocks WHERE hash = ?",
),
StarknetBlocksBlockId::Latest => tx.prepare(
"SELECT hash, number, root, timestamp, gas_price, sequencer_address
FROM starknet_blocks ORDER BY number DESC LIMIT 1",
),
}?;
let mut rows = match block {
StarknetBlocksBlockId::Number(number) => statement.query([number]),
StarknetBlocksBlockId::Hash(hash) => statement.query([hash]),
StarknetBlocksBlockId::Latest => statement.query([]),
}?;
let row = rows.next().context("Iterate rows")?;
match row {
Some(row) => {
let number = row.get_unwrap("number");
let hash = row.get_unwrap("hash");
let root = row.get_unwrap("root");
let timestamp = row.get_unwrap("timestamp");
let gas_price = row.get_ref_unwrap("gas_price").as_blob().unwrap();
let gas_price = GasPrice::from_be_slice(gas_price).unwrap();
let sequencer_address = row.get_unwrap("sequencer_address");
let block = StarknetBlock {
number,
hash,
root,
timestamp,
gas_price,
sequencer_address,
};
Ok(Some(block))
}
None => Ok(None),
}
}
/// Returns the [root](GlobalRoot) of the given block.
pub fn get_root(
tx: &Transaction<'_>,
block: StarknetBlocksBlockId,
) -> anyhow::Result<Option<GlobalRoot>> {
match block {
StarknetBlocksBlockId::Number(number) => tx.query_row(
"SELECT root FROM starknet_blocks WHERE number = ?",
[number],
|row| row.get(0),
),
StarknetBlocksBlockId::Hash(hash) => tx.query_row(
"SELECT root FROM starknet_blocks WHERE hash = ?",
[hash],
|row| row.get(0),
),
StarknetBlocksBlockId::Latest => tx.query_row(
"SELECT root FROM starknet_blocks ORDER BY number DESC LIMIT 1",
[],
|row| row.get(0),
),
}
.optional()
.map_err(|e| e.into())
}
/// Deletes all rows from __head down-to reorg_tail__
/// i.e. it deletes all rows where `block number >= reorg_tail`.
pub fn reorg(tx: &Transaction<'_>, reorg_tail: StarknetBlockNumber) -> anyhow::Result<()> {
tx.execute(
"DELETE FROM starknet_blocks WHERE number >= ?",
[reorg_tail],
)?;
Ok(())
}
/// Returns the [number](StarknetBlockNumber) of the latest block.
pub fn get_latest_number(tx: &Transaction<'_>) -> anyhow::Result<Option<StarknetBlockNumber>> {
let maybe = tx
.query_row(
"SELECT number FROM starknet_blocks ORDER BY number DESC LIMIT 1",
[],
|row| Ok(row.get_unwrap(0)),
)
.optional()?;
Ok(maybe)
}
/// Returns the [hash](StarknetBlockHash) and [number](StarknetBlockNumber) of the latest block.
pub fn get_latest_hash_and_number(
tx: &Transaction<'_>,
) -> anyhow::Result<Option<(StarknetBlockHash, StarknetBlockNumber)>> {
let maybe = tx
.query_row(
"SELECT hash, number FROM starknet_blocks ORDER BY number DESC LIMIT 1",
[],
|row| {
let hash = row.get_unwrap(0);
let num = row.get_unwrap(1);
Ok((hash, num))
},
)
.optional()?;
Ok(maybe)
}
pub fn get_number(
tx: &Transaction<'_>,
hash: StarknetBlockHash,
) -> anyhow::Result<Option<StarknetBlockNumber>> {
tx.query_row(
"SELECT number FROM starknet_blocks WHERE hash = ? LIMIT 1",
[hash],
|row| row.get(0),
)
.optional()
.map_err(|e| e.into())
}
/// Returns the [chain](crate::core::Chain) based on genesis block hash stored in the DB.
pub fn get_chain(tx: &Transaction<'_>) -> anyhow::Result<Option<Chain>> {
let genesis = Self::get_hash(tx, StarknetBlockNumber(0).into())
.context("Read genesis block from database")?;
match genesis {
None => Ok(None),
Some(hash) if hash == GOERLI_GENESIS_HASH => Ok(Some(Chain::Goerli)),
Some(hash) if hash == MAINNET_GENESIS_HASH => Ok(Some(Chain::Mainnet)),
Some(hash) => Err(anyhow::anyhow!("Unknown genesis block hash {}", hash.0)),
}
}
/// Returns hash of a given block number or `latest`
pub fn get_hash(
tx: &Transaction<'_>,
block: StarknetBlocksNumberOrLatest,
) -> anyhow::Result<Option<StarknetBlockHash>> {
match block {
StarknetBlocksNumberOrLatest::Number(n) => tx.query_row(
"SELECT hash FROM starknet_blocks WHERE number = ?",
[n],
|row| row.get(0),
),
StarknetBlocksNumberOrLatest::Latest => tx.query_row(
"SELECT hash FROM starknet_blocks ORDER BY number DESC LIMIT 1",
[],
|row| row.get(0),
),
}
.optional()
.map_err(|e| e.into())
}
}
/// Identifies block in some [StarknetBlocksTable] queries.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StarknetBlocksBlockId {
Number(StarknetBlockNumber),
Hash(StarknetBlockHash),
Latest,
}
impl From<StarknetBlockNumber> for StarknetBlocksBlockId {
fn from(number: StarknetBlockNumber) -> Self {
StarknetBlocksBlockId::Number(number)
}
}
impl From<StarknetBlockHash> for StarknetBlocksBlockId {
fn from(hash: StarknetBlockHash) -> Self {
StarknetBlocksBlockId::Hash(hash)
}
}
/// Identifies block in some [StarknetBlocksTable] queries.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StarknetBlocksNumberOrLatest {
Number(StarknetBlockNumber),
Latest,
}
impl From<StarknetBlockNumber> for StarknetBlocksNumberOrLatest {
fn from(number: StarknetBlockNumber) -> Self {
Self::Number(number)
}
}
#[derive(Debug, thiserror::Error)]
#[error("expected starknet block number or `latest`, got starknet block hash {0}")]
pub struct FromStarknetBlocksBlockIdError(StarknetBlockHash);
impl TryFrom<StarknetBlocksBlockId> for StarknetBlocksNumberOrLatest {
type Error = FromStarknetBlocksBlockIdError;
fn try_from(value: StarknetBlocksBlockId) -> Result<Self, Self::Error> {
match value {
StarknetBlocksBlockId::Number(n) => Ok(Self::Number(n)),
StarknetBlocksBlockId::Hash(h) => Err(FromStarknetBlocksBlockIdError(h)),
StarknetBlocksBlockId::Latest => Ok(Self::Latest),
}
}
}
/// Stores all known starknet transactions
pub struct StarknetTransactionsTable {}
impl StarknetTransactionsTable {
/// Inserts a Starknet block's transactions and transaction receipts into the [StarknetTransactionsTable].
///
/// overwrites existing data if the transaction hash already exists.
pub fn upsert(
tx: &Transaction<'_>,
block_hash: StarknetBlockHash,
block_number: StarknetBlockNumber,
transaction_data: &[(transaction::Transaction, transaction::Receipt)],
) -> anyhow::Result<()> {
if transaction_data.is_empty() {
return Ok(());
}
let mut compressor = zstd::bulk::Compressor::new(10).context("Create zstd compressor")?;
for (i, (transaction, receipt)) in transaction_data.iter().enumerate() {
// Serialize and compress transaction data.
let tx_data =
serde_json::ser::to_vec(&transaction).context("Serialize Starknet transaction")?;
let tx_data = compressor
.compress(&tx_data)
.context("Compress Starknet transaction")?;
let serialized_receipt = serde_json::ser::to_vec(&receipt)
.context("Serialize Starknet transaction receipt")?;
let serialized_receipt = compressor
.compress(&serialized_receipt)
.context("Compress Starknet transaction receipt")?;
tx.execute(r"INSERT OR REPLACE INTO starknet_transactions (hash, idx, block_hash, tx, receipt) VALUES (:hash, :idx, :block_hash, :tx, :receipt)",
named_params![
":hash": transaction.hash(),
":idx": i,
":block_hash": block_hash,
":tx": &tx_data,
":receipt": &serialized_receipt,
]).context("Insert transaction data into transactions table")?;
// insert events from receipt
StarknetEventsTable::insert_events(tx, block_number, transaction, &receipt.events)?;
}
Ok(())
}
pub fn get_transaction_data_for_block(
tx: &Transaction<'_>,
block: StarknetBlocksBlockId,
) -> anyhow::Result<Vec<(transaction::Transaction, transaction::Receipt)>> {
// Identify block hash
let block_hash = match block {
StarknetBlocksBlockId::Number(number) => {
match StarknetBlocksTable::get(tx, number.into())? {
Some(block) => block.hash,
None => return Ok(Vec::new()),
}
}
StarknetBlocksBlockId::Hash(hash) => hash,
StarknetBlocksBlockId::Latest => {
match StarknetBlocksTable::get(tx, StarknetBlocksBlockId::Latest)? {
Some(block) => block.hash,
None => return Ok(Vec::new()),
}
}
};
let mut stmt = tx
.prepare(
"SELECT tx, receipt FROM starknet_transactions WHERE block_hash = ? ORDER BY idx ASC",
)
.context("Preparing statement")?;
let mut rows = stmt.query([block_hash]).context("Executing query")?;
let mut data = Vec::new();
while let Some(row) = rows.next()? {
let receipt = row
.get_ref_unwrap("receipt")
.as_blob_or_null()?
.context("Receipt data missing")?;
let receipt = zstd::decode_all(receipt).context("Decompressing transaction receipt")?;
let receipt =
serde_json::from_slice(&receipt).context("Deserializing transaction receipt")?;
let transaction = row
.get_ref_unwrap("tx")
.as_blob_or_null()?
.context("Transaction data missing")?;
let transaction = zstd::decode_all(transaction).context("Decompressing transaction")?;
let transaction =
serde_json::from_slice(&transaction).context("Deserializing transaction")?;
data.push((transaction, receipt));
}
Ok(data)
}
pub fn get_transactions_for_latest_block(
sqlite_tx: &Transaction<'_>,
) -> anyhow::Result<Vec<transaction::Transaction>> {
let mut stmt = sqlite_tx
.prepare(
r"SELECT tx FROM starknet_transactions
WHERE starknet_transactions.block_hash =
(SELECT hash FROM starknet_blocks b WHERE b.number = (SELECT MAX(number) FROM starknet_blocks))
ORDER BY starknet_transactions.idx",
)
.context("Preparing statement")?;
let mut rows = stmt.query([]).context("Executing query")?;
let mut data = Vec::new();
while let Some(row) = rows.next()? {
let starknet_tx = row
.get_ref_unwrap("tx")
.as_blob_or_null()?
.context("Transaction data missing")?;
let starknet_tx = zstd::decode_all(starknet_tx).context("Decompressing transaction")?;
let starknet_tx =
serde_json::from_slice(&starknet_tx).context("Deserializing transaction")?;
data.push(starknet_tx);
}
Ok(data)
}
pub fn get_transaction_at_block(
tx: &Transaction<'_>,
block: StarknetBlocksBlockId,
index: usize,
) -> anyhow::Result<Option<transaction::Transaction>> {
// Identify block hash
let block_hash = match block {
StarknetBlocksBlockId::Number(number) => {
match StarknetBlocksTable::get(tx, number.into())? {
Some(block) => block.hash,
None => return Ok(None),
}
}
StarknetBlocksBlockId::Hash(hash) => hash,
StarknetBlocksBlockId::Latest => {
match StarknetBlocksTable::get(tx, StarknetBlocksBlockId::Latest)? {
Some(block) => block.hash,
None => return Ok(None),
}
}
};
let mut stmt = tx
.prepare("SELECT tx FROM starknet_transactions WHERE block_hash = ? AND idx = ?")
.context("Preparing statement")?;
let mut rows = stmt
.query(params![block_hash, index])
.context("Executing query")?;
let row = match rows.next()? {
Some(row) => row,
None => return Ok(None),
};
let transaction = match row.get_ref_unwrap(0).as_blob_or_null()? {
Some(data) => data,
None => return Ok(None),
};
let transaction = zstd::decode_all(transaction).context("Decompressing transaction")?;
let transaction =
serde_json::from_slice(&transaction).context("Deserializing transaction")?;
Ok(Some(transaction))
}
pub fn get_receipt(
tx: &Transaction<'_>,
transaction: StarknetTransactionHash,
) -> anyhow::Result<Option<(transaction::Receipt, StarknetBlockHash)>> {
let mut stmt = tx
.prepare("SELECT receipt, block_hash FROM starknet_transactions WHERE hash = ?1")
.context("Preparing statement")?;
let mut rows = stmt
.query(params![transaction.0.as_be_bytes()])
.context("Executing query")?;
let row = match rows.next()? {
Some(row) => row,
None => return Ok(None),
};
let receipt = match row.get_ref_unwrap("receipt").as_blob_or_null()? {
Some(data) => data,
None => return Ok(None),
};
let receipt = zstd::decode_all(receipt).context("Decompressing transaction")?;
let receipt = serde_json::from_slice(&receipt).context("Deserializing transaction")?;
let block_hash = row.get_unwrap("block_hash");
Ok(Some((receipt, block_hash)))
}
pub fn get_transaction(
tx: &Transaction<'_>,
transaction: StarknetTransactionHash,
) -> anyhow::Result<Option<transaction::Transaction>> {
let mut stmt = tx
.prepare("SELECT tx FROM starknet_transactions WHERE hash = ?1")
.context("Preparing statement")?;
let mut rows = stmt.query([transaction]).context("Executing query")?;
let row = match rows.next()? {
Some(row) => row,
None => return Ok(None),
};
let transaction = row.get_ref_unwrap(0).as_blob()?;
let transaction = zstd::decode_all(transaction).context("Decompressing transaction")?;
let transaction =
serde_json::from_slice(&transaction).context("Deserializing transaction")?;
Ok(Some(transaction))
}
pub fn get_transaction_count(
tx: &Transaction<'_>,
block: StarknetBlocksBlockId,
) -> anyhow::Result<usize> {
match block {
StarknetBlocksBlockId::Number(number) => tx
.query_row(
"SELECT COUNT(*) FROM starknet_transactions
JOIN starknet_blocks ON starknet_transactions.block_hash = starknet_blocks.hash
WHERE number = ?1",
[number],
|row| row.get(0),
)
.context("Counting transactions"),
StarknetBlocksBlockId::Hash(hash) => tx
.query_row(
"SELECT COUNT(*) FROM starknet_transactions WHERE block_hash = ?1",
[hash],
|row| row.get(0),
)
.context("Counting transactions"),
StarknetBlocksBlockId::Latest => {
// First get the latest block
let block = match StarknetBlocksTable::get(tx, StarknetBlocksBlockId::Latest)? {
Some(block) => block.number,
None => return Ok(0),
};
Self::get_transaction_count(tx, block.into())
}
}
}
}
pub struct StarknetEventFilter {
pub from_block: Option<StarknetBlockNumber>,
pub to_block: Option<StarknetBlockNumber>,
pub contract_address: Option<ContractAddress>,
pub keys: Vec<EventKey>,
pub page_size: usize,
pub page_number: usize,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StarknetEmittedEvent {
pub from_address: ContractAddress,
pub data: Vec<EventData>,
pub keys: Vec<EventKey>,
pub block_hash: StarknetBlockHash,
pub block_number: StarknetBlockNumber,
pub transaction_hash: StarknetTransactionHash,
}
#[derive(Copy, Clone, Debug, thiserror::Error, PartialEq, Eq)]
pub enum EventFilterError {
#[error("requested page size is too big, supported maximum is {0}")]
PageSizeTooBig(usize),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PageOfEvents {
pub events: Vec<StarknetEmittedEvent>,
pub is_last_page: bool,
}
pub struct StarknetEventsTable {}
impl StarknetEventsTable {
pub fn encode_event_data_to_bytes(data: &[EventData], buffer: &mut Vec<u8>) {
buffer.extend(data.iter().flat_map(|e| (*e.0.as_be_bytes()).into_iter()))
}
fn encode_event_key_to_base64(key: &EventKey, buf: &mut String) {
base64::encode_config_buf(key.0.as_be_bytes(), base64::STANDARD, buf);
}
pub fn event_keys_to_base64_strings(keys: &[EventKey], out: &mut String) {
// with padding it seems 44 bytes are needed for each
let needed = (keys.len() * (" ".len() + 44)).saturating_sub(" ".len());
if let Some(more) = needed.checked_sub(out.capacity() - out.len()) {
out.reserve(more);
}
let _capacity = out.capacity();
keys.iter().enumerate().for_each(|(i, x)| {
Self::encode_event_key_to_base64(x, out);
if i != keys.len() - 1 {
out.push(' ');
}
});
debug_assert_eq!(_capacity, out.capacity(), "pre-reservation was not enough");
}
pub fn insert_events(
tx: &Transaction<'_>,
block_number: StarknetBlockNumber,
transaction: &transaction::Transaction,
events: &[transaction::Event],
) -> anyhow::Result<()> {
match transaction {
transaction::Transaction::Declare(_) => {
anyhow::ensure!(
events.is_empty(),
"Declare transactions cannot emit events: block {}, transaction {}",
block_number,
transaction.hash().0
);
Ok(())
}
transaction::Transaction::Deploy(transaction::DeployTransaction {
transaction_hash,
..
})
| transaction::Transaction::Invoke(transaction::InvokeTransaction {
transaction_hash,
..
}) => {
let mut stmt = tx.prepare(
r"INSERT INTO starknet_events ( block_number, idx, transaction_hash, from_address, keys, data)
VALUES (:block_number, :idx, :transaction_hash, :from_address, :keys, :data)")?;
let mut keys = String::new();
let mut buffer = Vec::new();
for (idx, event) in events.iter().enumerate() {
keys.clear();
Self::event_keys_to_base64_strings(&event.keys, &mut keys);
buffer.clear();
Self::encode_event_data_to_bytes(&event.data, &mut buffer);
stmt.execute(named_params![
":block_number": block_number,
":idx": idx,
":transaction_hash": &transaction_hash,
":from_address": &event.from_address,
":keys": &keys,
":data": &buffer,
])
.context("Insert events into events table")?;
}
Ok(())
}
}
}
pub(crate) const PAGE_SIZE_LIMIT: usize = 1024;
fn event_query<'query, 'arg>(
base: &'query str,
from_block: Option<&'arg StarknetBlockNumber>,
to_block: Option<&'arg StarknetBlockNumber>,
contract_address: Option<&'arg ContractAddress>,
keys: &'arg [EventKey],
key_fts_expression: &'arg mut String,
) -> (
std::borrow::Cow<'query, str>,
Vec<(&'static str, &'arg dyn rusqlite::ToSql)>,
) {
let mut base_query = std::borrow::Cow::Borrowed(base);
let mut where_statement_parts: Vec<&'static str> = Vec::new();
let mut params: Vec<(&str, &dyn rusqlite::ToSql)> = Vec::new();
// filter on block range
match (from_block, to_block) {
(Some(from_block), Some(to_block)) => {
where_statement_parts.push("block_number BETWEEN :from_block AND :to_block");
params.push((":from_block", from_block));
params.push((":to_block", to_block));
}
(Some(from_block), None) => {
where_statement_parts.push("block_number >= :from_block");
params.push((":from_block", from_block));
}
(None, Some(to_block)) => {
where_statement_parts.push("block_number <= :to_block");
params.push((":to_block", to_block));
}
(None, None) => {}
}
// on contract address
if let Some(contract_address) = contract_address {
where_statement_parts.push("from_address = :contract_address");
params.push((":contract_address", contract_address))
}
// Filter on keys: this is using an FTS5 full-text index (virtual table) on the keys.
// The idea is that we convert keys to a space-separated list of Bas64 encoded string
// representation and then use the full-text index to find events matching the events.
if !keys.is_empty() {
let needed =
(keys.len() * (" OR ".len() + "\"\"".len() + 44)).saturating_sub(" OR ".len());
if let Some(more) = needed.checked_sub(key_fts_expression.capacity()) {
key_fts_expression.reserve(more);
}
let _capacity = key_fts_expression.capacity();
keys.iter().enumerate().for_each(|(i, key)| {
key_fts_expression.push('"');
Self::encode_event_key_to_base64(key, key_fts_expression);
key_fts_expression.push('"');
if i != keys.len() - 1 {
key_fts_expression.push_str(" OR ");
}
});
debug_assert_eq!(
_capacity,
key_fts_expression.capacity(),
"pre-reservation was not enough"
);
base_query.to_mut().push_str(" INNER JOIN starknet_events_keys ON starknet_events.rowid = starknet_events_keys.rowid");
where_statement_parts.push("starknet_events_keys.keys MATCH :events_match");
params.push((":events_match", &*key_fts_expression));
}
if !where_statement_parts.is_empty() {
let needed = " WHERE ".len()
+ where_statement_parts.len() * " AND ".len()
+ where_statement_parts.iter().map(|x| x.len()).sum::<usize>();
let q = base_query.to_mut();
if let Some(more) = needed.checked_sub(q.capacity() - q.len()) {
q.reserve(more);
}
let _capacity = q.capacity();
q.push_str(" WHERE ");
let total = where_statement_parts.len();
where_statement_parts
.into_iter()
.enumerate()
.for_each(|(i, part)| {
q.push_str(part);
if i != total - 1 {
q.push_str(" AND ");
}
});
debug_assert_eq!(_capacity, q.capacity(), "pre-reservation was not enough");
}
(base_query, params)
}
pub fn event_count(
tx: &Transaction<'_>,
from_block: Option<StarknetBlockNumber>,
to_block: Option<StarknetBlockNumber>,
contract_address: Option<ContractAddress>,
keys: Vec<EventKey>,
) -> anyhow::Result<usize> {
let mut key_fts_expression = String::new();
let (query, params) = Self::event_query(
"SELECT COUNT(1) FROM starknet_events",
from_block.as_ref(),
to_block.as_ref(),
contract_address.as_ref(),
&keys,
&mut key_fts_expression,
);
let count: usize = tx.query_row(&query, params.as_slice(), |row| row.get(0))?;
Ok(count)
}
pub fn get_events(
tx: &Transaction<'_>,
filter: &StarknetEventFilter,
) -> anyhow::Result<PageOfEvents> {
if filter.page_size > Self::PAGE_SIZE_LIMIT {
return Err(EventFilterError::PageSizeTooBig(Self::PAGE_SIZE_LIMIT).into());
}
if filter.page_size < 1 {
anyhow::bail!("Invalid page size");
}
let base_query = r#"SELECT
block_number,
starknet_blocks.hash as block_hash,
transaction_hash,
starknet_transactions.idx as transaction_idx,
from_address,
data,
starknet_events.keys as keys
FROM starknet_events
INNER JOIN starknet_transactions ON (starknet_transactions.hash = starknet_events.transaction_hash)
INNER JOIN starknet_blocks ON (starknet_blocks.number = starknet_events.block_number)"#;
let mut key_fts_expression = String::new();
let (mut base_query, mut params) = Self::event_query(
base_query,
filter.from_block.as_ref(),
filter.to_block.as_ref(),
filter.contract_address.as_ref(),
&filter.keys,
&mut key_fts_expression,
);
let offset = filter.page_number * filter.page_size;
// We have to be able to decide if there are more events. We request one extra event
// above the requested page size, so that we can decide.
let limit = filter.page_size + 1;
params.push((":limit", &limit));
params.push((":offset", &offset));
base_query.to_mut().push_str(" ORDER BY block_number, transaction_idx, starknet_events.idx LIMIT :limit OFFSET :offset");
let mut statement = tx.prepare(&base_query).context("Preparing SQL query")?;
let mut rows = statement
.query(params.as_slice())
.context("Executing SQL query")?;
let mut is_last_page = true;
let mut emitted_events = Vec::new();
while let Some(row) = rows.next().context("Fetching next event")? {
if emitted_events.len() == filter.page_size {
// We already have a full page, and are just fetching the extra event
// This means that there are more pages.
is_last_page = false;
} else {
let block_number = row.get_unwrap("block_number");
let block_hash = row.get_unwrap("block_hash");
let transaction_hash = row.get_unwrap("transaction_hash");
let from_address = row.get_unwrap("from_address");
let data = row.get_ref_unwrap("data").as_blob().unwrap();
let data: Vec<_> = data
.chunks_exact(32)
.map(|data| {
let data = StarkHash::from_be_slice(data).unwrap();
EventData(data)
})
.collect();
let keys = row.get_ref_unwrap("keys").as_str().unwrap();
// no need to allocate a vec for this in loop
let mut temp = [0u8; 32];
let keys: Vec<_> = keys
.split(' ')
.map(|key| {
let used =
base64::decode_config_slice(key, base64::STANDARD, &mut temp).unwrap();
let key = StarkHash::from_be_slice(&temp[..used]).unwrap();
EventKey(key)
})
.collect();
let event = StarknetEmittedEvent {
data,
from_address,
keys,
block_hash,
block_number,
transaction_hash,
};
emitted_events.push(event);
}
}
Ok(PageOfEvents {
events: emitted_events,
is_last_page,
})
}
}
/// Describes a Starknet block.
///
/// While the sequencer version on each block (when present) is stored since starknet 0.9.1, it is
/// not yet read.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StarknetBlock {
pub number: StarknetBlockNumber,
pub hash: StarknetBlockHash,
pub root: GlobalRoot,
pub timestamp: StarknetBlockTimestamp,
pub gas_price: GasPrice,
pub sequencer_address: SequencerAddress,
}
/// StarknetVersionsTable tracks `starknet_versions` table, which just interns the version
/// metadata on each block.
///
/// It was decided to go with interned approach, as we couldn't be sure that a semantic version
/// string format is followed. Semantic version strings may have been cheaper to just store
/// in-line.
///
/// Introduced in [`super::schema::revision_0014::migrate`].
struct StarknetVersionsTable;
impl StarknetVersionsTable {
/// Interns, or makes sure there's a unique row for each version.
///
/// These are not deleted automatically nor is a need expected due to multiple blocks being
/// generated with a single starknet version.
fn intern(transaction: &Transaction<'_>, version: &str) -> anyhow::Result<i64> {
let id: Option<i64> = transaction
.query_row(
"SELECT id FROM starknet_versions WHERE version = ?",
&[version],
|r| Ok(r.get_unwrap(0)),
)
.optional()
.context("Querying for an existing starknet_version")?;
let id = if let Some(id) = id {
id
} else {
// sqlite "autoincrement" for integer primary keys works like this: we leave it out of
// the insert, even though it's not null, it will get max(id)+1 assigned, which we can
// read back with last_insert_rowid
let rows = transaction
.execute(
"INSERT INTO starknet_versions(version) VALUES (?)",
[version],
)
.context("Inserting unique starknet_version")?;
anyhow::ensure!(rows == 1, "Unexpected number of rows inserted: {rows}");
transaction.last_insert_rowid()
};
Ok(id)
}
}
/// Stores the contract state hash along with its preimage. This is useful to
/// map between the global state tree and the contracts tree.
///
/// Specifically it stores
///
/// - [contract state hash](ContractStateHash)
/// - [class hash](ClassHash)
/// - [contract root](ContractRoot)
pub struct ContractsStateTable {}
impl ContractsStateTable {
/// Insert a state hash into the table, overwrites the data if the hash already exists.
pub fn upsert(
transaction: &Transaction<'_>,
state_hash: ContractStateHash,
hash: ClassHash,
root: ContractRoot,
) -> anyhow::Result<()> {
transaction.execute(
"INSERT OR IGNORE INTO contract_states (state_hash, hash, root) VALUES (:state_hash, :hash, :root)",
named_params! {
":state_hash": state_hash,
":hash": hash,
":root": root,
},
)?;
Ok(())
}
/// Gets the root associated with the given state hash, or [None]
/// if it does not exist.
pub fn get_root(
transaction: &Transaction<'_>,
state_hash: ContractStateHash,
) -> anyhow::Result<Option<ContractRoot>> {
transaction
.query_row(
"SELECT root FROM contract_states WHERE state_hash = :state_hash",
named_params! {
":state_hash": state_hash
},
|row| row.get("root"),
)
.optional()
.map_err(|e| e.into())
}
}
/// Stores all known [Starknet state updates][crate::rpc::types::reply::StateUpdate].
pub struct StarknetStateUpdatesTable {}
impl StarknetStateUpdatesTable {
/// Inserts a StarkNet state update accociated with a particular block into the [StarknetStateUpdatesTable].
///
/// Overwrites existing data if the block hash already exists.
pub fn insert(
tx: &Transaction<'_>,
block_hash: StarknetBlockHash,
state_update: &StateUpdate,
) -> anyhow::Result<()> {
let serialized =
serde_json::to_vec(&state_update).context("Serialize Starknet state update")?;
let mut compressor = zstd::bulk::Compressor::new(10).context("Create zstd compressor")?;
let compressed = compressor
.compress(&serialized)
.context("Compress Starknet state update")?;
tx.execute(
r"INSERT INTO starknet_state_updates (block_hash, data) VALUES (:block_hash, :data)",
named_params![":block_hash": block_hash, ":data": &compressed,],
)
.context("Insert state update data into state updates table")?;
Ok(())
}
/// Gets a StarkNet state update for block.
pub fn get(
tx: &Transaction<'_>,
block_hash: StarknetBlockHash,
) -> anyhow::Result<Option<StateUpdate>> {
let mut stmt = tx
.prepare("SELECT data FROM starknet_state_updates WHERE block_hash = ?1")
.context("Preparing statement")?;
let mut rows = stmt.query([block_hash]).context("Executing query")?;
let row = match rows.next()? {
Some(row) => row,
None => return Ok(None),
};
let state_update = row.get_ref_unwrap(0).as_blob()?;
let state_update = zstd::decode_all(state_update).context("Decompressing state update")?;
let state_update =
serde_json::from_slice(&state_update).context("Deserializing state update")?;
Ok(Some(state_update))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::storage::Storage;
mod contracts {
use super::*;
use crate::starkhash;
#[test]
fn get_root() {
let storage = Storage::in_memory().unwrap();
let mut connection = storage.connection().unwrap();
let transaction = connection.transaction().unwrap();
let state_hash = ContractStateHash(starkhash!("0abc"));
let hash = ClassHash(starkhash!("0123"));
let root = ContractRoot(starkhash!("0def"));
ContractsStateTable::upsert(&transaction, state_hash, hash, root).unwrap();
let result = ContractsStateTable::get_root(&transaction, state_hash).unwrap();
assert_eq!(result, Some(root));
}
}
mod refs {
use super::*;
mod l1_l2_head {
use super::*;
#[test]
fn fresh_is_none() {
let storage = Storage::in_memory().unwrap();
let mut connection = storage.connection().unwrap();
let tx = connection.transaction().unwrap();
let l1_l2_head = RefsTable::get_l1_l2_head(&tx).unwrap();
assert_eq!(l1_l2_head, None);
}
#[test]
fn set_get() {
let storage = Storage::in_memory().unwrap();
let mut connection = storage.connection().unwrap();
let tx = connection.transaction().unwrap();
let expected = Some(StarknetBlockNumber(22));
RefsTable::set_l1_l2_head(&tx, expected).unwrap();
assert_eq!(expected, RefsTable::get_l1_l2_head(&tx).unwrap());
let expected = Some(StarknetBlockNumber(25));
RefsTable::set_l1_l2_head(&tx, expected).unwrap();
assert_eq!(expected, RefsTable::get_l1_l2_head(&tx).unwrap());
RefsTable::set_l1_l2_head(&tx, None).unwrap();
assert_eq!(None, RefsTable::get_l1_l2_head(&tx).unwrap());
}
}
}
mod l1_state_table {
use super::*;
/// Creates a set of consecutive [StateUpdateLog]s starting from L2 genesis,
/// with arbitrary other values.
fn create_updates() -> [StateUpdateLog; 3] {
(0..3)
.map(|i| StateUpdateLog {
origin: EthOrigin {
block: BlockOrigin {
hash: EthereumBlockHash(H256::from_low_u64_le(i + 33)),
number: EthereumBlockNumber(i + 12_000),
},
transaction: TransactionOrigin {
hash: EthereumTransactionHash(H256::from_low_u64_le(i + 999)),
index: EthereumTransactionIndex(i + 20_000),
},
log_index: EthereumLogIndex(i + 500),
},
global_root: GlobalRoot(
StarkHash::from_hex_str(&"3".repeat(i as usize + 1)).unwrap(),
),
block_number: StarknetBlockNumber::GENESIS + i,
})
.collect::<Vec<_>>()
.try_into()
.unwrap()
}
mod get {
use super::*;
#[test]
fn none() {
let storage = Storage::in_memory().unwrap();
let mut connection = storage.connection().unwrap();
let tx = connection.transaction().unwrap();
let updates = create_updates();
for update in &updates {
L1StateTable::upsert(&tx, update).unwrap();
}
let non_existent = updates.last().unwrap().block_number + 1;
assert_eq!(L1StateTable::get(&tx, non_existent.into()).unwrap(), None);
}
#[test]
fn some() {
let storage = Storage::in_memory().unwrap();
let mut connection = storage.connection().unwrap();
let tx = connection.transaction().unwrap();
let updates = create_updates();
for update in &updates {
L1StateTable::upsert(&tx, update).unwrap();
}
for (idx, update) in updates.iter().enumerate() {
assert_eq!(
L1StateTable::get(&tx, update.block_number.into())
.unwrap()
.as_ref(),
Some(update),
"Update {}",
idx
);
}
}
mod latest {
use super::*;
#[test]
fn none() {
let storage = Storage::in_memory().unwrap();
let mut connection = storage.connection().unwrap();
let tx = connection.transaction().unwrap();
assert_eq!(
L1StateTable::get(&tx, L1TableBlockId::Latest).unwrap(),
None
);
}
#[test]
fn some() {
let storage = Storage::in_memory().unwrap();
let mut connection = storage.connection().unwrap();
let tx = connection.transaction().unwrap();
let updates = create_updates();
for update in &updates {
L1StateTable::upsert(&tx, update).unwrap();
}
assert_eq!(
L1StateTable::get(&tx, L1TableBlockId::Latest)
.unwrap()
.as_ref(),
updates.last()
);
}
}
}
mod get_root {
use super::*;
#[test]
fn none() {
let storage = Storage::in_memory().unwrap();
let mut connection = storage.connection().unwrap();
let tx = connection.transaction().unwrap();
let updates = create_updates();
for update in &updates {
L1StateTable::upsert(&tx, update).unwrap();
}
let non_existent = updates.last().unwrap().block_number + 1;
assert_eq!(
L1StateTable::get_root(&tx, non_existent.into()).unwrap(),
None
);
}
#[test]
fn some() {
let storage = Storage::in_memory().unwrap();
let mut connection = storage.connection().unwrap();
let tx = connection.transaction().unwrap();
let updates = create_updates();
for update in &updates {
L1StateTable::upsert(&tx, update).unwrap();
}
for (idx, update) in updates.iter().enumerate() {
assert_eq!(
L1StateTable::get_root(&tx, update.block_number.into()).unwrap(),
Some(update.global_root),
"Update {}",
idx
);
}
}
mod latest {
use super::*;
#[test]
fn none() {
let storage = Storage::in_memory().unwrap();
let mut connection = storage.connection().unwrap();
let tx = connection.transaction().unwrap();
assert_eq!(
L1StateTable::get_root(&tx, L1TableBlockId::Latest).unwrap(),
None
);
}
#[test]
fn some() {
let storage = Storage::in_memory().unwrap();
let mut connection = storage.connection().unwrap();
let tx = connection.transaction().unwrap();
let updates = create_updates();
for update in &updates {
L1StateTable::upsert(&tx, update).unwrap();
}
assert_eq!(
L1StateTable::get_root(&tx, L1TableBlockId::Latest).unwrap(),
Some(updates.last().unwrap().global_root)
);
}
}
}
mod reorg {
use super::*;
#[test]
fn full() {
let storage = Storage::in_memory().unwrap();
let mut connection = storage.connection().unwrap();
let tx = connection.transaction().unwrap();
let updates = create_updates();
for update in &updates {
L1StateTable::upsert(&tx, update).unwrap();
}
L1StateTable::reorg(&tx, StarknetBlockNumber::GENESIS).unwrap();
assert_eq!(
L1StateTable::get(&tx, L1TableBlockId::Latest).unwrap(),
None
);
}
#[test]
fn partial() {
let storage = Storage::in_memory().unwrap();
let mut connection = storage.connection().unwrap();
let tx = connection.transaction().unwrap();
let updates = create_updates();
for update in &updates {
L1StateTable::upsert(&tx, update).unwrap();
}
let reorg_tail = updates[1].block_number;
L1StateTable::reorg(&tx, reorg_tail).unwrap();
assert_eq!(
L1StateTable::get(&tx, L1TableBlockId::Latest)
.unwrap()
.as_ref(),
Some(&updates[0])
);
}
}
}
mod starknet_blocks {
use super::*;
use crate::storage::test_utils;
fn create_blocks() -> [StarknetBlock; test_utils::NUM_BLOCKS] {
test_utils::create_blocks()
}
fn with_default_blocks<F>(f: F)
where
F: FnOnce(&Transaction<'_>, [StarknetBlock; test_utils::NUM_BLOCKS]),
{
let storage = Storage::in_memory().unwrap();
let mut connection = storage.connection().unwrap();
let tx = connection.transaction().unwrap();
let blocks = create_blocks();
for block in &blocks {
StarknetBlocksTable::insert(&tx, block, None).unwrap();
}
f(&tx, blocks)
}
mod get {
use super::*;
mod by_number {
use super::*;
#[test]
fn some() {
with_default_blocks(|tx, blocks| {
for block in blocks {
let result = StarknetBlocksTable::get(tx, block.number.into())
.unwrap()
.unwrap();
assert_eq!(result, block);
}
})
}
#[test]
fn none() {
with_default_blocks(|tx, blocks| {
let non_existent = blocks.last().unwrap().number + 1;
assert_eq!(
StarknetBlocksTable::get(tx, non_existent.into()).unwrap(),
None
);
});
}
}
mod by_hash {
use super::*;
#[test]
fn some() {
with_default_blocks(|tx, blocks| {
for block in blocks {
let result = StarknetBlocksTable::get(tx, block.hash.into())
.unwrap()
.unwrap();
assert_eq!(result, block);
}
});
}
#[test]
fn none() {
with_default_blocks(|tx, _blocks| {
let non_existent =
StarknetBlockHash(StarkHash::from_hex_str(&"b".repeat(10)).unwrap());
assert_eq!(
StarknetBlocksTable::get(tx, non_existent.into()).unwrap(),
None
);
});
}
}
mod latest {
use super::*;
#[test]
fn some() {
with_default_blocks(|tx, blocks| {
let expected = blocks.last().unwrap();
let latest = StarknetBlocksTable::get(tx, StarknetBlocksBlockId::Latest)
.unwrap()
.unwrap();
assert_eq!(&latest, expected);
})
}
#[test]
fn none() {
let storage = Storage::in_memory().unwrap();
let mut connection = storage.connection().unwrap();
let tx = connection.transaction().unwrap();
let latest =
StarknetBlocksTable::get(&tx, StarknetBlocksBlockId::Latest).unwrap();
assert_eq!(latest, None);
}
}
mod number_by_hash {
use super::*;
#[test]
fn some() {
with_default_blocks(|tx, blocks| {
for block in blocks {
let result = StarknetBlocksTable::get_number(tx, block.hash)
.unwrap()
.unwrap();
assert_eq!(result, block.number);
}
});
}
#[test]
fn none() {
with_default_blocks(|tx, _blocks| {
let non_existent =
StarknetBlockHash(StarkHash::from_hex_str(&"b".repeat(10)).unwrap());
assert_eq!(
StarknetBlocksTable::get_number(tx, non_existent).unwrap(),
None
);
});
}
}
}
mod get_root {
use super::*;
mod by_number {
use super::*;
#[test]
fn some() {
with_default_blocks(|tx, blocks| {
for block in blocks {
let root = StarknetBlocksTable::get_root(tx, block.number.into())
.unwrap()
.unwrap();
assert_eq!(root, block.root);
}
})
}
#[test]
fn none() {
with_default_blocks(|tx, blocks| {
let non_existent = blocks.last().unwrap().number + 1;
assert_eq!(
StarknetBlocksTable::get_root(tx, non_existent.into()).unwrap(),
None
);
})
}
}
mod by_hash {
use super::*;
#[test]
fn some() {
with_default_blocks(|tx, blocks| {
for block in blocks {
let root = StarknetBlocksTable::get_root(tx, block.hash.into())
.unwrap()
.unwrap();
assert_eq!(root, block.root);
}
})
}
#[test]
fn none() {
with_default_blocks(|tx, _blocks| {
let non_existent =
StarknetBlockHash(StarkHash::from_hex_str(&"b".repeat(10)).unwrap());
assert_eq!(
StarknetBlocksTable::get_root(tx, non_existent.into()).unwrap(),
None
);
})
}
}
mod latest {
use super::*;
#[test]
fn some() {
with_default_blocks(|tx, blocks| {
let expected = blocks.last().map(|block| block.root).unwrap();
let latest =
StarknetBlocksTable::get_root(tx, StarknetBlocksBlockId::Latest)
.unwrap()
.unwrap();
assert_eq!(latest, expected);
})
}
#[test]
fn none() {
let storage = Storage::in_memory().unwrap();
let mut connection = storage.connection().unwrap();
let tx = connection.transaction().unwrap();
let latest_root =
StarknetBlocksTable::get_root(&tx, StarknetBlocksBlockId::Latest).unwrap();
assert_eq!(latest_root, None);
}
}
}
mod reorg {
use super::*;
#[test]
fn full() {
with_default_blocks(|tx, _blocks| {
// reorg to genesis expected to wipe the blocks
StarknetBlocksTable::reorg(tx, StarknetBlockNumber::GENESIS).unwrap();
assert_eq!(
StarknetBlocksTable::get(tx, StarknetBlocksBlockId::Latest).unwrap(),
None
);
})
}
#[test]
fn partial() {
with_default_blocks(|tx, blocks| {
let reorg_tail = blocks[1].number;
StarknetBlocksTable::reorg(tx, reorg_tail).unwrap();
let expected = StarknetBlock {
number: blocks[0].number,
hash: blocks[0].hash,
root: blocks[0].root,
timestamp: blocks[0].timestamp,
gas_price: blocks[0].gas_price,
sequencer_address: blocks[0].sequencer_address,
};
assert_eq!(
StarknetBlocksTable::get(tx, StarknetBlocksBlockId::Latest).unwrap(),
Some(expected)
);
})
}
}
mod interned_version {
use super::super::Storage;
use super::StarknetBlocksTable;
#[test]
fn duplicate_versions_interned() {
let storage = Storage::in_memory().unwrap();
let mut connection = storage.connection().unwrap();
let tx = connection.transaction().unwrap();
let blocks = super::create_blocks();
let versions = ["0.9.1", "0.9.1"]
.into_iter()
.chain(std::iter::repeat("0.9.2"));
let mut inserted = 0;
for (block, version) in blocks.iter().zip(versions) {
StarknetBlocksTable::insert(&tx, block, Some(version)).unwrap();
inserted += 1;
}
let rows = tx.prepare("select version_id, count(1) from starknet_blocks group by version_id order by version_id")
.unwrap()
.query([])
.unwrap()
.mapped(|r| Ok((r.get::<_, Option<i64>>(0)?, r.get::<_, i64>(1)?)))
.collect::<Result<Vec<(Option<i64>, i64)>, _>>()
.unwrap();
// there should be two of 0.9.1
assert_eq!(rows.first(), Some(&(Some(1), 2)));
// there should be a few for 0.9.2 (initially the create_rows returned 3 => 1)
assert_eq!(rows.last(), Some(&(Some(2), inserted - 2)));
// we should not have any nulls
assert_eq!(rows.len(), 2, "nulls were not expected in {rows:?}");
}
}
mod get_latest_number {
use super::*;
#[test]
fn some() {
with_default_blocks(|tx, blocks| {
let latest = blocks.last().unwrap().number;
assert_eq!(
StarknetBlocksTable::get_latest_number(tx).unwrap(),
Some(latest)
);
});
}
#[test]
fn none() {
let storage = Storage::in_memory().unwrap();
let mut connection = storage.connection().unwrap();
let tx = connection.transaction().unwrap();
assert_eq!(StarknetBlocksTable::get_latest_number(&tx).unwrap(), None);
}
}
mod get_latest_hash_and_number {
use super::*;
#[test]
fn some() {
with_default_blocks(|tx, blocks| {
let latest = blocks.last().unwrap();
assert_eq!(
StarknetBlocksTable::get_latest_hash_and_number(tx).unwrap(),
Some((latest.hash, latest.number))
);
});
}
#[test]
fn none() {
let storage = Storage::in_memory().unwrap();
let mut connection = storage.connection().unwrap();
let tx = connection.transaction().unwrap();
assert_eq!(
StarknetBlocksTable::get_latest_hash_and_number(&tx).unwrap(),
None
);
}
}
mod get_hash {
use super::*;
mod by_number {
use super::*;
#[test]
fn some() {
with_default_blocks(|tx, blocks| {
for block in blocks {
let result = StarknetBlocksTable::get_hash(tx, block.number.into())
.unwrap()
.unwrap();
assert_eq!(result, block.hash);
}
})
}
#[test]
fn none() {
with_default_blocks(|tx, blocks| {
let non_existent = blocks.last().unwrap().number + 1;
assert_eq!(
StarknetBlocksTable::get(tx, non_existent.into()).unwrap(),
None
);
});
}
}
mod latest {
use super::*;
#[test]
fn some() {
with_default_blocks(|tx, blocks| {
let expected = blocks.last().unwrap().hash;
let latest =
StarknetBlocksTable::get_hash(tx, StarknetBlocksNumberOrLatest::Latest)
.unwrap()
.unwrap();
assert_eq!(latest, expected);
})
}
#[test]
fn none() {
let storage = Storage::in_memory().unwrap();
let mut connection = storage.connection().unwrap();
let tx = connection.transaction().unwrap();
let latest =
StarknetBlocksTable::get(&tx, StarknetBlocksBlockId::Latest).unwrap();
assert_eq!(latest, None);
}
}
}
}
mod starknet_events {
use web3::types::H128;
use super::*;
use crate::core::{EntryPoint, EventData, Fee};
use crate::sequencer::reply::transaction;
use crate::starkhash;
use crate::storage::test_utils;
#[test]
fn event_data_serialization() {
let data = [
EventData(starkhash!("01")),
EventData(starkhash!("02")),
EventData(starkhash!("03")),
];
let mut buffer = Vec::new();
StarknetEventsTable::encode_event_data_to_bytes(&data, &mut buffer);
assert_eq!(
&buffer,
&[
0u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3
]
);
}
#[test]
fn event_keys_to_base64_strings() {
let event = transaction::Event {
from_address: ContractAddress(starkhash!(
"06fbd460228d843b7fbef670ff15607bf72e19fa94de21e29811ada167b4ca39"
)),
data: vec![],
keys: vec![
EventKey(starkhash!("901823")),
EventKey(starkhash!("901824")),
EventKey(starkhash!("901825")),
],
};
let mut buf = String::new();
StarknetEventsTable::event_keys_to_base64_strings(&event.keys, &mut buf);
assert_eq!(buf.capacity(), buf.len());
assert_eq!(
buf,
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACQGCM= AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACQGCQ= AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACQGCU="
);
}
#[test]
fn get_events_with_fully_specified_filter() {
let (storage, emitted_events) = test_utils::setup_test_storage();
let mut connection = storage.connection().unwrap();
let tx = connection.transaction().unwrap();
let expected_event = &emitted_events[1];
let filter = StarknetEventFilter {
from_block: Some(expected_event.block_number),
to_block: Some(expected_event.block_number),
contract_address: Some(expected_event.from_address),
// we're using a key which is present in _all_ events
keys: vec![EventKey(starkhash!("deadbeef"))],
page_size: test_utils::NUM_EVENTS,
page_number: 0,
};
let events = StarknetEventsTable::get_events(&tx, &filter).unwrap();
assert_eq!(
events,
PageOfEvents {
events: vec![expected_event.clone()],
is_last_page: true
}
);
}
#[test]
fn events_are_ordered() {
// This is a regression test where events were incorrectly ordered by transaction hash
// instead of transaction index.
//
// Events should be ordered by block number, transaction index, event index.
use crate::core::StarknetTransactionHash;
use crate::sequencer::reply::transaction::Event;
// All events we are storing, arbitrarily use from_address to distinguish them.
let expected_events = (0u8..5)
.map(|idx| Event {
data: Vec::new(),
keys: Vec::new(),
from_address: ContractAddress(
StarkHash::from_be_slice(&idx.to_be_bytes()).unwrap(),
),
})
.collect::<Vec<_>>();
let block = StarknetBlock {
number: StarknetBlockNumber::GENESIS,
hash: StarknetBlockHash(starkhash!("1234")),
root: GlobalRoot(starkhash!("1234")),
timestamp: StarknetBlockTimestamp(0),
gas_price: GasPrice(0),
sequencer_address: SequencerAddress(starkhash!("1234")),
};
// Note: hashes are reverse ordered to trigger the sorting bug.
let transactions = vec![
transaction::Transaction::Invoke(transaction::InvokeTransaction {
calldata: vec![],
// Only required because event insert rejects if this is None
contract_address: ContractAddress(StarkHash::ZERO),
entry_point_type: transaction::EntryPointType::External,
entry_point_selector: EntryPoint(StarkHash::ZERO),
max_fee: Fee(H128::zero()),
signature: vec![],
transaction_hash: StarknetTransactionHash(starkhash!("0F")),
}),
transaction::Transaction::Invoke(transaction::InvokeTransaction {
calldata: vec![],
// Only required because event insert rejects if this is None
contract_address: ContractAddress(StarkHash::ZERO),
entry_point_type: transaction::EntryPointType::External,
entry_point_selector: EntryPoint(StarkHash::ZERO),
max_fee: Fee(H128::zero()),
signature: vec![],
transaction_hash: StarknetTransactionHash(starkhash!("01")),
}),
];
let receipts = vec![
transaction::Receipt {
actual_fee: None,
events: expected_events[..3].to_vec(),
execution_resources: transaction::ExecutionResources {
builtin_instance_counter:
transaction::execution_resources::BuiltinInstanceCounter::Empty(
transaction::execution_resources::EmptyBuiltinInstanceCounter {},
),
n_steps: 0,
n_memory_holes: 0,
},
l1_to_l2_consumed_message: None,
l2_to_l1_messages: Vec::new(),
transaction_hash: transactions[0].hash(),
transaction_index: crate::core::StarknetTransactionIndex(0),
},
transaction::Receipt {
actual_fee: None,
events: expected_events[3..].to_vec(),
execution_resources: transaction::ExecutionResources {
builtin_instance_counter:
transaction::execution_resources::BuiltinInstanceCounter::Empty(
transaction::execution_resources::EmptyBuiltinInstanceCounter {},
),
n_steps: 0,
n_memory_holes: 0,
},
l1_to_l2_consumed_message: None,
l2_to_l1_messages: Vec::new(),
transaction_hash: transactions[1].hash(),
transaction_index: crate::core::StarknetTransactionIndex(1),
},
];
let storage = Storage::in_memory().unwrap();
let mut connection = storage.connection().unwrap();
let tx = connection.transaction().unwrap();
StarknetBlocksTable::insert(&tx, &block, None).unwrap();
StarknetTransactionsTable::upsert(
&tx,
block.hash,
block.number,
&vec![
(transactions[0].clone(), receipts[0].clone()),
(transactions[1].clone(), receipts[1].clone()),
],
)
.unwrap();
let addresses = StarknetEventsTable::get_events(
&tx,
&StarknetEventFilter {
from_block: None,
to_block: None,
contract_address: None,
keys: vec![],
page_size: 1024,
page_number: 0,
},
)
.unwrap()
.events
.iter()
.map(|e| e.from_address)
.collect::<Vec<_>>();
let expected = expected_events
.iter()
.map(|e| e.from_address)
.collect::<Vec<_>>();
assert_eq!(addresses, expected);
}
#[test]
fn get_events_by_block() {
let (storage, emitted_events) = test_utils::setup_test_storage();
let mut connection = storage.connection().unwrap();
let tx = connection.transaction().unwrap();
const BLOCK_NUMBER: usize = 2;
let filter = StarknetEventFilter {
from_block: Some(StarknetBlockNumber(BLOCK_NUMBER as u64)),
to_block: Some(StarknetBlockNumber(BLOCK_NUMBER as u64)),
contract_address: None,
keys: vec![],
page_size: test_utils::NUM_EVENTS,
page_number: 0,
};
let expected_events = &emitted_events[test_utils::EVENTS_PER_BLOCK * BLOCK_NUMBER
..test_utils::EVENTS_PER_BLOCK * (BLOCK_NUMBER + 1)];
let events = StarknetEventsTable::get_events(&tx, &filter).unwrap();
assert_eq!(
events,
PageOfEvents {
events: expected_events.to_vec(),
is_last_page: true
}
);
}
#[test]
fn get_events_up_to_block() {
let (storage, emitted_events) = test_utils::setup_test_storage();
let mut connection = storage.connection().unwrap();
let tx = connection.transaction().unwrap();
const UNTIL_BLOCK_NUMBER: usize = 2;
let filter = StarknetEventFilter {
from_block: None,
to_block: Some(StarknetBlockNumber(UNTIL_BLOCK_NUMBER as u64)),
contract_address: None,
keys: vec![],
page_size: test_utils::NUM_EVENTS,
page_number: 0,
};
let expected_events =
&emitted_events[..test_utils::EVENTS_PER_BLOCK * (UNTIL_BLOCK_NUMBER + 1)];
let events = StarknetEventsTable::get_events(&tx, &filter).unwrap();
assert_eq!(
events,
PageOfEvents {
events: expected_events.to_vec(),
is_last_page: true
}
);
}
#[test]
fn get_events_from_block_onwards() {
let (storage, emitted_events) = test_utils::setup_test_storage();
let mut connection = storage.connection().unwrap();
let tx = connection.transaction().unwrap();
const FROM_BLOCK_NUMBER: usize = 2;
let filter = StarknetEventFilter {
from_block: Some(StarknetBlockNumber(FROM_BLOCK_NUMBER as u64)),
to_block: None,
contract_address: None,
keys: vec![],
page_size: test_utils::NUM_EVENTS,
page_number: 0,
};
let expected_events =
&emitted_events[test_utils::EVENTS_PER_BLOCK * FROM_BLOCK_NUMBER..];
let events = StarknetEventsTable::get_events(&tx, &filter).unwrap();
assert_eq!(
events,
PageOfEvents {
events: expected_events.to_vec(),
is_last_page: true
}
);
}
#[test]
fn get_events_from_contract() {
let (storage, emitted_events) = test_utils::setup_test_storage();
let mut connection = storage.connection().unwrap();
let tx = connection.transaction().unwrap();
let expected_event = &emitted_events[33];
let filter = StarknetEventFilter {
from_block: None,
to_block: None,
contract_address: Some(expected_event.from_address),
keys: vec![],
page_size: test_utils::NUM_EVENTS,
page_number: 0,
};
let events = StarknetEventsTable::get_events(&tx, &filter).unwrap();
assert_eq!(
events,
PageOfEvents {
events: vec![expected_event.clone()],
is_last_page: true
}
);
}
#[test]
fn get_events_by_key() {
let (storage, emitted_events) = test_utils::setup_test_storage();
let mut connection = storage.connection().unwrap();
let tx = connection.transaction().unwrap();
let expected_event = &emitted_events[27];
let filter = StarknetEventFilter {
from_block: None,
to_block: None,
contract_address: None,
keys: vec![expected_event.keys[0]],
page_size: test_utils::NUM_EVENTS,
page_number: 0,
};
let events = StarknetEventsTable::get_events(&tx, &filter).unwrap();
assert_eq!(
events,
PageOfEvents {
events: vec![expected_event.clone()],
is_last_page: true
}
);
}
#[test]
fn get_events_with_no_filter() {
let (storage, emitted_events) = test_utils::setup_test_storage();
let mut connection = storage.connection().unwrap();
let tx = connection.transaction().unwrap();
let filter = StarknetEventFilter {
from_block: None,
to_block: None,
contract_address: None,
keys: vec![],
page_size: test_utils::NUM_EVENTS,
page_number: 0,
};
let events = StarknetEventsTable::get_events(&tx, &filter).unwrap();
assert_eq!(
events,
PageOfEvents {
events: emitted_events,
is_last_page: true
}
);
}
#[test]
fn get_events_with_no_filter_and_paging() {
let (storage, emitted_events) = test_utils::setup_test_storage();
let mut connection = storage.connection().unwrap();
let tx = connection.transaction().unwrap();
let filter = StarknetEventFilter {
from_block: None,
to_block: None,
contract_address: None,
keys: vec![],
page_size: 10,
page_number: 0,
};
let events = StarknetEventsTable::get_events(&tx, &filter).unwrap();
assert_eq!(
events,
PageOfEvents {
events: emitted_events[..10].to_vec(),
is_last_page: false
}
);
let filter = StarknetEventFilter {
from_block: None,
to_block: None,
contract_address: None,
keys: vec![],
page_size: 10,
page_number: 1,
};
let events = StarknetEventsTable::get_events(&tx, &filter).unwrap();
assert_eq!(
events,
PageOfEvents {
events: emitted_events[10..20].to_vec(),
is_last_page: false
}
);
let filter = StarknetEventFilter {
from_block: None,
to_block: None,
contract_address: None,
keys: vec![],
page_size: 10,
page_number: 3,
};
let events = StarknetEventsTable::get_events(&tx, &filter).unwrap();
assert_eq!(
events,
PageOfEvents {
events: emitted_events[30..40].to_vec(),
is_last_page: true
}
);
}
#[test]
fn get_events_with_no_filter_and_nonexistent_page() {
let (storage, _) = test_utils::setup_test_storage();
let mut connection = storage.connection().unwrap();
let tx = connection.transaction().unwrap();
const PAGE_SIZE: usize = 10;
let filter = StarknetEventFilter {
from_block: None,
to_block: None,
contract_address: None,
keys: vec![],
page_size: PAGE_SIZE,
// one page _after_ the last one
page_number: test_utils::NUM_BLOCKS * test_utils::EVENTS_PER_BLOCK / PAGE_SIZE,
};
let events = StarknetEventsTable::get_events(&tx, &filter).unwrap();
assert_eq!(
events,
PageOfEvents {
events: vec![],
is_last_page: true
}
);
}
#[test]
fn get_events_with_invalid_page_size() {
let (storage, _) = test_utils::setup_test_storage();
let mut connection = storage.connection().unwrap();
let tx = connection.transaction().unwrap();
let filter = StarknetEventFilter {
from_block: None,
to_block: None,
contract_address: None,
keys: vec![],
page_size: 0,
page_number: 0,
};
let result = StarknetEventsTable::get_events(&tx, &filter);
assert!(result.is_err());
assert_eq!(result.unwrap_err().to_string(), "Invalid page size");
let filter = StarknetEventFilter {
from_block: None,
to_block: None,
contract_address: None,
keys: vec![],
page_size: StarknetEventsTable::PAGE_SIZE_LIMIT + 1,
page_number: 0,
};
let result = StarknetEventsTable::get_events(&tx, &filter);
assert!(result.is_err());
assert_eq!(
result.unwrap_err().downcast::<EventFilterError>().unwrap(),
EventFilterError::PageSizeTooBig(StarknetEventsTable::PAGE_SIZE_LIMIT)
);
}
#[test]
fn get_events_by_key_with_paging() {
let (storage, emitted_events) = test_utils::setup_test_storage();
let mut connection = storage.connection().unwrap();
let tx = connection.transaction().unwrap();
let expected_events = &emitted_events[27..32];
let keys_for_expected_events: Vec<_> =
expected_events.iter().map(|e| e.keys[0]).collect();
let filter = StarknetEventFilter {
from_block: None,
to_block: None,
contract_address: None,
keys: keys_for_expected_events.clone(),
page_size: 2,
page_number: 0,
};
let events = StarknetEventsTable::get_events(&tx, &filter).unwrap();
assert_eq!(
events,
PageOfEvents {
events: expected_events[..2].to_vec(),
is_last_page: false
}
);
let filter = StarknetEventFilter {
from_block: None,
to_block: None,
contract_address: None,
keys: keys_for_expected_events.clone(),
page_size: 2,
page_number: 1,
};
let events = StarknetEventsTable::get_events(&tx, &filter).unwrap();
assert_eq!(
events,
PageOfEvents {
events: expected_events[2..4].to_vec(),
is_last_page: false
}
);
let filter = StarknetEventFilter {
from_block: None,
to_block: None,
contract_address: None,
keys: keys_for_expected_events,
page_size: 2,
page_number: 2,
};
let events = StarknetEventsTable::get_events(&tx, &filter).unwrap();
assert_eq!(
events,
PageOfEvents {
events: expected_events[4..].to_vec(),
is_last_page: true
}
);
}
#[test]
fn event_count_by_block() {
let (storage, _) = test_utils::setup_test_storage();
let mut connection = storage.connection().unwrap();
let tx = connection.transaction().unwrap();
const BLOCK: Option<StarknetBlockNumber> = Some(StarknetBlockNumber(2));
let count = StarknetEventsTable::event_count(&tx, BLOCK, BLOCK, None, vec![]).unwrap();
assert_eq!(count, test_utils::EVENTS_PER_BLOCK);
}
#[test]
fn event_count_from_contract() {
let (storage, events) = test_utils::setup_test_storage();
let mut connection = storage.connection().unwrap();
let tx = connection.transaction().unwrap();
let addr = events[0].from_address;
let expected = events
.iter()
.filter(|event| event.from_address == addr)
.count();
let count = StarknetEventsTable::event_count(
&tx,
Some(StarknetBlockNumber::GENESIS),
Some(StarknetBlockNumber::MAX),
Some(addr),
vec![],
)
.unwrap();
assert_eq!(count, expected);
}
#[test]
fn event_count_by_key() {
let (storage, emitted_events) = test_utils::setup_test_storage();
let mut connection = storage.connection().unwrap();
let tx = connection.transaction().unwrap();
let key = emitted_events[27].keys[0];
let expected = emitted_events
.iter()
.filter(|event| event.keys.contains(&key))
.count();
let count = StarknetEventsTable::event_count(
&tx,
Some(StarknetBlockNumber::GENESIS),
Some(StarknetBlockNumber::MAX),
None,
vec![key],
)
.unwrap();
assert_eq!(count, expected);
}
}
mod starknet_updates {
use super::*;
use crate::storage::fixtures::with_n_state_updates;
mod get {
use super::*;
#[test]
fn some() {
with_n_state_updates(1, |_, tx, state_updates| {
for expected in state_updates {
let actual =
StarknetStateUpdatesTable::get(tx, expected.block_hash.unwrap())
.unwrap()
.unwrap();
assert_eq!(actual, expected);
}
})
}
#[test]
fn none() {
use crate::starkhash;
with_n_state_updates(1, |_, tx, _| {
let non_existent = StarknetBlockHash(starkhash!("ff"));
let actual = StarknetStateUpdatesTable::get(tx, non_existent).unwrap();
assert!(actual.is_none());
})
}
}
}
}
|
mod colors;
mod list_separator;
mod number;
mod operator;
mod quotes;
mod unit;
pub use self::colors::Rgba;
pub use self::list_separator::ListSeparator;
pub use self::number::{NumValue, Number};
pub use self::operator::Operator;
pub use self::quotes::Quotes;
pub use self::unit::{Dimension, Unit};
|
use nu_test_support::{nu, pipeline};
#[test]
fn checks_any_row_is_true() {
let actual = nu!(
cwd: ".", pipeline(
r#"
echo [ "Ecuador", "USA", "New Zealand" ]
| any $it == "New Zealand"
"#
));
assert_eq!(actual.out, "true");
}
#[test]
fn checks_any_column_of_a_table_is_true() {
let actual = nu!(
cwd: ".", pipeline(
r#"
echo [
[ first_name, last_name, rusty_at, likes ];
[ Andrés, Robalino, 10/11/2013, 1 ]
[ Jonathan, Turner, 10/12/2013, 1 ]
[ Darren, Schroeder, 10/11/2013, 1 ]
[ Yehuda, Katz, 10/11/2013, 1 ]
]
| any rusty_at == 10/12/2013
"#
));
assert_eq!(actual.out, "true");
}
#[test]
fn checks_if_any_returns_error_with_invalid_command() {
let actual = nu!(
cwd: ".", pipeline(
r#"
[red orange yellow green blue purple] | any ($it | st length) > 4
"#
));
assert!(actual.err.contains("can't run executable") || actual.err.contains("did you mean"));
}
|
mod message_destinations;
mod mvec;
mod registry;
pub(crate) mod channel;
pub(crate) mod subscribe_loop;
pub(crate) mod subscribe_loop_supervisor;
// Explicitly allow clippy::module_inception here. We just reexport everything
// from this module to list all the dependencies cleanly in a separate file.
// This nesting never appears in the API.
#[allow(clippy::module_inception)]
mod subscription;
pub use subscription::*;
|
#![allow(non_camel_case_types)]
/*!
Structural aliases for even array size up to 32.
*/
use super::names::{
I0,I1,I2,I3,I4,I5,I6,I7,
I8,I9,I10,I11,I12,I13,I14,I15,
I16,I17,I18,I19,I20,I21,I22,I23,
I24,I25,I26,I27,I28,I29,I30,I31,
};
use crate::IntoFieldMut;
/*
fn main() {
use std::fmt::Write;
const S:&'static str=" ";
let mut reg=String::new();
const MAX:usize=32;
const CHUNK_SIZE:usize=8;
const CHUNK_COUNT:usize=MAX/CHUNK_SIZE;
println!("declare_array_traits!{{");
for i in 0..CHUNK_COUNT {
let prev=i.saturating_sub(1)*8;
let curr=i*8;
let next=(i+1)*8;
let next=if next==MAX { MAX+1 }else{ next };
if next<MAX {
print!("{S}(Array_{0}_{1} [",curr,next,S=S);
if i!=0 {
print!("Array_{}_{} ",prev,curr);
}
print!("] [");
for field in curr..next {
print!("I{0} ",field);
}
println!("] )");
}
for arr_len in curr..next {
let _=write!(reg,"{S}(Array{0} [",arr_len,S=S);
if i!=0 {
let _=write!(reg,"Array_{}_{} ",prev,curr);
}
let _=write!(reg,"] [");
for field in curr..arr_len {
let _=write!(reg,"I{0} ",field);
}
let _=writeln!(reg,"] )");
}
}
println!("{}",reg);
println!("}}");
}
*/
macro_rules! declare_array_traits {
(
$((
$trait_name:ident
[$($super_trait:ident)*]
[$($field:ident)*]
))*
) => (
$(
/// A structural alias for an array of this size
pub trait $trait_name<T>:
$($super_trait<T>+)*
$(IntoFieldMut<$field,Ty=T> +)*
{}
impl<This,T> $trait_name<T> for This
where
Self:
$($super_trait<T>+)*
$(IntoFieldMut<$field,Ty=T> +)*
{}
)*
)
}
declare_array_traits!{
(Array_0_8 [] [I0 I1 I2 I3 I4 I5 I6 I7 ] )
(Array_8_16 [Array_0_8 ] [I8 I9 I10 I11 I12 I13 I14 I15 ] )
(Array_16_24 [Array_8_16 ] [I16 I17 I18 I19 I20 I21 I22 I23 ] )
(Array0 [] [] )
(Array1 [] [I0 ] )
(Array2 [] [I0 I1 ] )
(Array3 [] [I0 I1 I2 ] )
(Array4 [] [I0 I1 I2 I3 ] )
(Array5 [] [I0 I1 I2 I3 I4 ] )
(Array6 [] [I0 I1 I2 I3 I4 I5 ] )
(Array7 [] [I0 I1 I2 I3 I4 I5 I6 ] )
(Array8 [Array_0_8 ] [] )
(Array9 [Array_0_8 ] [I8 ] )
(Array10 [Array_0_8 ] [I8 I9 ] )
(Array11 [Array_0_8 ] [I8 I9 I10 ] )
(Array12 [Array_0_8 ] [I8 I9 I10 I11 ] )
(Array13 [Array_0_8 ] [I8 I9 I10 I11 I12 ] )
(Array14 [Array_0_8 ] [I8 I9 I10 I11 I12 I13 ] )
(Array15 [Array_0_8 ] [I8 I9 I10 I11 I12 I13 I14 ] )
(Array16 [Array_8_16 ] [] )
(Array17 [Array_8_16 ] [I16 ] )
(Array18 [Array_8_16 ] [I16 I17 ] )
(Array19 [Array_8_16 ] [I16 I17 I18 ] )
(Array20 [Array_8_16 ] [I16 I17 I18 I19 ] )
(Array21 [Array_8_16 ] [I16 I17 I18 I19 I20 ] )
(Array22 [Array_8_16 ] [I16 I17 I18 I19 I20 I21 ] )
(Array23 [Array_8_16 ] [I16 I17 I18 I19 I20 I21 I22 ] )
(Array24 [Array_16_24 ] [] )
(Array25 [Array_16_24 ] [I24 ] )
(Array26 [Array_16_24 ] [I24 I25 ] )
(Array27 [Array_16_24 ] [I24 I25 I26 ] )
(Array28 [Array_16_24 ] [I24 I25 I26 I27 ] )
(Array29 [Array_16_24 ] [I24 I25 I26 I27 I28 ] )
(Array30 [Array_16_24 ] [I24 I25 I26 I27 I28 I29 ] )
(Array31 [Array_16_24 ] [I24 I25 I26 I27 I28 I29 I30 ] )
(Array32 [Array_16_24 ] [I24 I25 I26 I27 I28 I29 I30 I31 ] )
}
|
// Graphic manager of subte
extern crate pancurses as curses;
use std::cmp::*;
use std::collections::*;
use fourthrail::*;
/* */
pub const INNER_HEIGHT : i32 = 24;
pub const INNER_WIDTH : i32 = 80;
/* */
pub const MAP_DISPLAY_WIDTH : i32 = 60;
pub const MAP_DISPLAY_HEIGHT : i32 = 22;
pub const MAP_DISPLAY_STEP : i32 = 8 ;
const DISPLAY_NONE : i16 = 0;
const DISPLAY_MAP_NAME_COLOUR : i16 = 21;
const DISPLAY_STAT_NAME_COLOUR : i16 = 31;
const DISPLAY_STAT_CAL_COLOUR : i16 = 32;
const DISPLAY_STAT_CAP_COLOUR : i16 = 33;
const DISPLAY_COHERENCY_COLOUR : i16 = 34;
/* */
pub fn init_display() {
curses::init_pair(
DISPLAY_NONE,
-1,
-1
);
curses::init_pair(
DISPLAY_MAP_NAME_COLOUR,
curses::COLOR_YELLOW,
-1
);
curses::init_pair(
DISPLAY_COHERENCY_COLOUR,
curses::COLOR_CYAN,
-1
);
}
pub fn put_tile(win: &curses::Window, t: &Tile) {
let (p, c) = t.display();
win.color_set(p);
win.addch(c);
}
pub fn put_agent<T: Display + Position>(win: &curses::Window, start: Coord, cr: &T) {
let (sr, sc) = start;
let (p, s) = cr.display();
let (y, x) = cr.pos();
let r = y - sr;
let c = x - sc;
if r >= MAP_DISPLAY_HEIGHT
|| r < 0
|| c >= MAP_DISPLAY_WIDTH
|| c < 0 {
return;
}
win.mv(r, c);
win.color_set(p);
win.addch(s);
}
pub fn put_map(win: &curses::Window,
start: Coord,
map: &Map<&Tile>,
mem: &Map<Visibility>) {
let (sr, sc) = start;
for r in 0..min(MAP_HEIGHT - sr, MAP_DISPLAY_HEIGHT) {
win.mv(r, 0);
for c in 0..min(MAP_WIDTH - sc, MAP_DISPLAY_WIDTH) {
if mem.get_tile((r + sr, c + sc)) == Visibility::Unseen {
win.color_set(DISPLAY_NONE);
win.addch(' ');
} else {
put_tile(win, map.get_tile((r + sr, c + sc)));
}
}
}
}
pub fn put_stats(win: &curses::Window, coh: &i32) {
let s_coh = coh.to_string();
let start = MAP_DISPLAY_WIDTH + 1;
win.attron(curses::A_BOLD);
win.color_set(DISPLAY_COHERENCY_COLOUR);
win.mvaddstr(1, start, langue::COHERENCY);
win.mvaddstr(2, start, &s_coh);
win.mvaddstr(4, start, langue::STAMINA);
}
pub fn put_message(win: &curses::Window, msg: &Message) {
for block in msg {
let (p, ref s) = *block;
win.color_set(p);
win.addstr(&s);
win.addstr(langue::MESSAGE_BLOCK_CONNECTOR);
}
}
pub fn put_last_message(win: &curses::Window, msg: &Message) {
win.mv(INNER_HEIGHT - 1, 0);
win.deleteln();
put_message(win, msg);
}
pub fn put_all_messages(win: &curses::Window, msgs: &VecDeque<Message>) {
let mut i = (*msgs).iter();
for r in 0..INNER_HEIGHT {
win.mv(INNER_HEIGHT - r - 1, 0);
win.clrtoeol();
if let Some(msg) = i.next() {
put_message(win, msg);
}
}
}
|
#[doc = "Reader of register CTRL"]
pub type R = crate::R<u32, super::CTRL>;
#[doc = "Writer for register CTRL"]
pub type W = crate::W<u32, super::CTRL>;
#[doc = "Register CTRL `reset()`'s with value 0x00f8_0000"]
impl crate::ResetValue for super::CTRL {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0x00f8_0000
}
}
#[doc = "Reader of field `TX_CLK_EDGE`"]
pub type TX_CLK_EDGE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TX_CLK_EDGE`"]
pub struct TX_CLK_EDGE_W<'a> {
w: &'a mut W,
}
impl<'a> TX_CLK_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 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Reader of field `RX_CLK_EDGE`"]
pub type RX_CLK_EDGE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `RX_CLK_EDGE`"]
pub struct RX_CLK_EDGE_W<'a> {
w: &'a mut W,
}
impl<'a> RX_CLK_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 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Reader of field `RX_CLK_SRC`"]
pub type RX_CLK_SRC_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `RX_CLK_SRC`"]
pub struct RX_CLK_SRC_W<'a> {
w: &'a mut W,
}
impl<'a> RX_CLK_SRC_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 `SCLK_CONTINUOUS`"]
pub type SCLK_CONTINUOUS_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SCLK_CONTINUOUS`"]
pub struct SCLK_CONTINUOUS_W<'a> {
w: &'a mut W,
}
impl<'a> SCLK_CONTINUOUS_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 `SSEL_POLARITY`"]
pub type SSEL_POLARITY_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SSEL_POLARITY`"]
pub struct SSEL_POLARITY_W<'a> {
w: &'a mut W,
}
impl<'a> SSEL_POLARITY_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 `LEAD`"]
pub type LEAD_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `LEAD`"]
pub struct LEAD_W<'a> {
w: &'a mut W,
}
impl<'a> LEAD_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 8)) | (((value as u32) & 0x03) << 8);
self.w
}
}
#[doc = "Reader of field `LAG`"]
pub type LAG_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `LAG`"]
pub struct LAG_W<'a> {
w: &'a mut W,
}
impl<'a> LAG_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 10)) | (((value as u32) & 0x03) << 10);
self.w
}
}
#[doc = "Reader of field `DIV_ENABLED`"]
pub type DIV_ENABLED_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DIV_ENABLED`"]
pub struct DIV_ENABLED_W<'a> {
w: &'a mut W,
}
impl<'a> DIV_ENABLED_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 << 12)) | (((value as u32) & 0x01) << 12);
self.w
}
}
#[doc = "Reader of field `DIV`"]
pub type DIV_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `DIV`"]
pub struct DIV_W<'a> {
w: &'a mut W,
}
impl<'a> DIV_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 & !(0x3f << 13)) | (((value as u32) & 0x3f) << 13);
self.w
}
}
#[doc = "Reader of field `ADDR_WIDTH`"]
pub type ADDR_WIDTH_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `ADDR_WIDTH`"]
pub struct ADDR_WIDTH_W<'a> {
w: &'a mut W,
}
impl<'a> ADDR_WIDTH_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 & !(0x0f << 19)) | (((value as u32) & 0x0f) << 19);
self.w
}
}
#[doc = "Reader of field `DATA_WIDTH`"]
pub type DATA_WIDTH_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DATA_WIDTH`"]
pub struct DATA_WIDTH_W<'a> {
w: &'a mut W,
}
impl<'a> DATA_WIDTH_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 << 23)) | (((value as u32) & 0x01) << 23);
self.w
}
}
#[doc = "Reader of field `ENABLED`"]
pub type ENABLED_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `ENABLED`"]
pub struct ENABLED_W<'a> {
w: &'a mut W,
}
impl<'a> ENABLED_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 << 31)) | (((value as u32) & 0x01) << 31);
self.w
}
}
impl R {
#[doc = "Bit 1 - N/A"]
#[inline(always)]
pub fn tx_clk_edge(&self) -> TX_CLK_EDGE_R {
TX_CLK_EDGE_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - N/A"]
#[inline(always)]
pub fn rx_clk_edge(&self) -> RX_CLK_EDGE_R {
RX_CLK_EDGE_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - N/A"]
#[inline(always)]
pub fn rx_clk_src(&self) -> RX_CLK_SRC_R {
RX_CLK_SRC_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - N/A"]
#[inline(always)]
pub fn sclk_continuous(&self) -> SCLK_CONTINUOUS_R {
SCLK_CONTINUOUS_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - N/A"]
#[inline(always)]
pub fn ssel_polarity(&self) -> SSEL_POLARITY_R {
SSEL_POLARITY_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bits 8:9 - N/A"]
#[inline(always)]
pub fn lead(&self) -> LEAD_R {
LEAD_R::new(((self.bits >> 8) & 0x03) as u8)
}
#[doc = "Bits 10:11 - N/A"]
#[inline(always)]
pub fn lag(&self) -> LAG_R {
LAG_R::new(((self.bits >> 10) & 0x03) as u8)
}
#[doc = "Bit 12 - N/A"]
#[inline(always)]
pub fn div_enabled(&self) -> DIV_ENABLED_R {
DIV_ENABLED_R::new(((self.bits >> 12) & 0x01) != 0)
}
#[doc = "Bits 13:18 - N/A"]
#[inline(always)]
pub fn div(&self) -> DIV_R {
DIV_R::new(((self.bits >> 13) & 0x3f) as u8)
}
#[doc = "Bits 19:22 - N/A"]
#[inline(always)]
pub fn addr_width(&self) -> ADDR_WIDTH_R {
ADDR_WIDTH_R::new(((self.bits >> 19) & 0x0f) as u8)
}
#[doc = "Bit 23 - N/A"]
#[inline(always)]
pub fn data_width(&self) -> DATA_WIDTH_R {
DATA_WIDTH_R::new(((self.bits >> 23) & 0x01) != 0)
}
#[doc = "Bit 31 - N/A"]
#[inline(always)]
pub fn enabled(&self) -> ENABLED_R {
ENABLED_R::new(((self.bits >> 31) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 1 - N/A"]
#[inline(always)]
pub fn tx_clk_edge(&mut self) -> TX_CLK_EDGE_W {
TX_CLK_EDGE_W { w: self }
}
#[doc = "Bit 2 - N/A"]
#[inline(always)]
pub fn rx_clk_edge(&mut self) -> RX_CLK_EDGE_W {
RX_CLK_EDGE_W { w: self }
}
#[doc = "Bit 3 - N/A"]
#[inline(always)]
pub fn rx_clk_src(&mut self) -> RX_CLK_SRC_W {
RX_CLK_SRC_W { w: self }
}
#[doc = "Bit 4 - N/A"]
#[inline(always)]
pub fn sclk_continuous(&mut self) -> SCLK_CONTINUOUS_W {
SCLK_CONTINUOUS_W { w: self }
}
#[doc = "Bit 5 - N/A"]
#[inline(always)]
pub fn ssel_polarity(&mut self) -> SSEL_POLARITY_W {
SSEL_POLARITY_W { w: self }
}
#[doc = "Bits 8:9 - N/A"]
#[inline(always)]
pub fn lead(&mut self) -> LEAD_W {
LEAD_W { w: self }
}
#[doc = "Bits 10:11 - N/A"]
#[inline(always)]
pub fn lag(&mut self) -> LAG_W {
LAG_W { w: self }
}
#[doc = "Bit 12 - N/A"]
#[inline(always)]
pub fn div_enabled(&mut self) -> DIV_ENABLED_W {
DIV_ENABLED_W { w: self }
}
#[doc = "Bits 13:18 - N/A"]
#[inline(always)]
pub fn div(&mut self) -> DIV_W {
DIV_W { w: self }
}
#[doc = "Bits 19:22 - N/A"]
#[inline(always)]
pub fn addr_width(&mut self) -> ADDR_WIDTH_W {
ADDR_WIDTH_W { w: self }
}
#[doc = "Bit 23 - N/A"]
#[inline(always)]
pub fn data_width(&mut self) -> DATA_WIDTH_W {
DATA_WIDTH_W { w: self }
}
#[doc = "Bit 31 - N/A"]
#[inline(always)]
pub fn enabled(&mut self) -> ENABLED_W {
ENABLED_W { w: self }
}
}
|
use super::watch::{Watch, WatchHandle};
#[cfg(feature = "admission-webhook")]
use crate::admission::WebhookFn;
use crate::operator::Watchable;
use crate::Operator;
use kube::api::ListParams;
/// Builder pattern for registering a controller or operator.
pub struct ControllerBuilder<C: Operator> {
/// The controller or operator singleton.
pub(crate) controller: C,
/// List of watch configurations for objects that will simply be cached
/// locally.
pub(crate) watches: Vec<Watch>,
/// List of watch configurations for objects that will trigger
/// notifications (based on OwnerReferences).
pub(crate) owns: Vec<Watch>,
/// Restrict our controller to act on a specific namespace.
namespace: Option<String>,
/// Restrict our controller to act on objects that match specific list
/// params.
list_params: ListParams,
/// The buffer length for Tokio channels used to communicate between
/// watcher tasks and runtime tasks.
buffer: usize,
}
impl<O: Operator> ControllerBuilder<O> {
/// Create builder from operator singleton.
pub fn new(operator: O) -> Self {
ControllerBuilder {
controller: operator,
watches: vec![],
owns: vec![],
namespace: None,
list_params: Default::default(),
buffer: 32,
}
}
/// Change the length of buffer used for internal communication channels.
pub fn with_buffer(mut self, buffer: usize) -> Self {
self.buffer = buffer;
self
}
pub(crate) fn buffer(&self) -> usize {
self.buffer
}
/// Create watcher definition for the configured managed resource.
pub(crate) fn manages(&self) -> Watch {
Watch::new::<O::Manifest>(self.namespace.clone(), self.list_params.clone())
}
/// Restrict controller to manage a specific namespace.
pub fn namespaced(mut self, namespace: &str) -> Self {
self.namespace = Some(namespace.to_string());
self
}
/// Restrict controller to manage only objects matching specific list
/// params.
pub fn with_params(mut self, list_params: ListParams) -> Self {
self.list_params = list_params;
self
}
/// Watch all objects of given kind R. Cluster scoped and no list param
/// restrictions.
pub fn watches<R>(mut self) -> Self
where
R: Watchable,
{
self.watches.push(Watch::new::<R>(None, Default::default()));
self
}
/// Watch objects of given kind R. Cluster scoped, but limited to objects
/// matching supplied list params.
pub fn watches_with_params<R>(mut self, list_params: ListParams) -> Self
where
R: Watchable,
{
self.watches.push(Watch::new::<R>(None, list_params));
self
}
/// Watch all objects of given kind R in supplied namespace, with no list
/// param restrictions.
pub fn watches_namespaced<R>(mut self, namespace: &str) -> Self
where
R: Watchable,
{
self.watches.push(Watch::new::<R>(
Some(namespace.to_string()),
Default::default(),
));
self
}
/// Watch objects of given kind R in supplied namespace, and limited to
/// objects matching supplied list params.
pub fn watches_namespaced_with_params<R>(
mut self,
namespace: &str,
list_params: ListParams,
) -> Self
where
R: Watchable,
{
self.watches
.push(Watch::new::<R>(Some(namespace.to_string()), list_params));
self
}
/// Watch and subscribe to notifications based on OwnerReferences all
/// objects of kind R. Cluster scoped and no list param restrictions.
pub fn owns<R>(mut self) -> Self
where
R: Watchable,
{
self.owns.push(Watch::new::<R>(None, Default::default()));
self
}
/// Watch and subscribe to notifications based on OwnerReferences
/// objects of kind R. Cluster scoped, but limited to objects matching
/// supplied list params.
pub fn owns_with_params<R>(mut self, list_params: ListParams) -> Self
where
R: Watchable,
{
self.owns.push(Watch::new::<R>(None, list_params));
self
}
/// Watch and subscribe to notifications based on OwnerReferences
/// objects of kind R in supplied namespace, with no list param
/// restrictions.
pub fn owns_namespaced<R>(mut self, namespace: &str) -> Self
where
R: Watchable,
{
self.owns.push(Watch::new::<R>(
Some(namespace.to_string()),
Default::default(),
));
self
}
/// Watch and subscribe to notifications based on OwnerReferences
/// objects of kind R in supplied namespace, and limited to objects
/// matching supplied list params.
pub fn owns_namespaced_with_params<R>(
mut self,
namespace: &str,
list_params: ListParams,
) -> Self
where
R: Watchable,
{
self.owns
.push(Watch::new::<R>(Some(namespace.to_string()), list_params));
self
}
/// Registers a validating webhook at the path "/$GROUP/$VERSION/$KIND".
/// Multiple webhooks can be registered, but must be at different paths.
#[cfg(feature = "admission-webhook")]
pub(crate) fn validates(self, _f: &WebhookFn<O>) -> Self {
todo!()
}
/// Registers a validating webhook at the supplied path.
#[cfg(feature = "admission-webhook")]
pub(crate) fn validates_at_path(self, _path: &str, _f: &WebhookFn<O>) -> Self {
todo!()
}
/// Registers a mutating webhook at the path "/$GROUP/$VERSION/$KIND".
/// Multiple webhooks can be registered, but must be at different paths.
#[cfg(feature = "admission-webhook")]
pub(crate) fn mutates(self, _f: &WebhookFn<O>) -> Self {
todo!()
}
/// Registers a mutating webhook at the supplied path.
#[cfg(feature = "admission-webhook")]
pub(crate) fn mutates_at_path(self, _path: &str, _f: &WebhookFn<O>) -> Self {
todo!()
}
}
#[derive(Clone)]
pub struct Controller {
pub manages: WatchHandle,
pub owns: Vec<WatchHandle>,
pub watches: Vec<WatchHandle>,
}
|
pub mod astar;
pub mod dijkstra;
pub use super::BaseMap;
|
#[doc = "Register `CCIPR` reader"]
pub type R = crate::R<CCIPR_SPEC>;
#[doc = "Register `CCIPR` writer"]
pub type W = crate::W<CCIPR_SPEC>;
#[doc = "Field `USART1SEL` reader - USART1 clock source selection"]
pub type USART1SEL_R = crate::FieldReader<USART1SEL_A>;
#[doc = "USART1 clock source selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum USART1SEL_A {
#[doc = "0: PCLK clock selected"]
Pclk = 0,
#[doc = "1: SYSCLK clock selected"]
Sysclk = 1,
#[doc = "2: HSI16 clock selected"]
Hsi16 = 2,
#[doc = "3: LSE clock selected"]
Lse = 3,
}
impl From<USART1SEL_A> for u8 {
#[inline(always)]
fn from(variant: USART1SEL_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for USART1SEL_A {
type Ux = u8;
}
impl USART1SEL_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> USART1SEL_A {
match self.bits {
0 => USART1SEL_A::Pclk,
1 => USART1SEL_A::Sysclk,
2 => USART1SEL_A::Hsi16,
3 => USART1SEL_A::Lse,
_ => unreachable!(),
}
}
#[doc = "PCLK clock selected"]
#[inline(always)]
pub fn is_pclk(&self) -> bool {
*self == USART1SEL_A::Pclk
}
#[doc = "SYSCLK clock selected"]
#[inline(always)]
pub fn is_sysclk(&self) -> bool {
*self == USART1SEL_A::Sysclk
}
#[doc = "HSI16 clock selected"]
#[inline(always)]
pub fn is_hsi16(&self) -> bool {
*self == USART1SEL_A::Hsi16
}
#[doc = "LSE clock selected"]
#[inline(always)]
pub fn is_lse(&self) -> bool {
*self == USART1SEL_A::Lse
}
}
#[doc = "Field `USART1SEL` writer - USART1 clock source selection"]
pub type USART1SEL_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 2, O, USART1SEL_A>;
impl<'a, REG, const O: u8> USART1SEL_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "PCLK clock selected"]
#[inline(always)]
pub fn pclk(self) -> &'a mut crate::W<REG> {
self.variant(USART1SEL_A::Pclk)
}
#[doc = "SYSCLK clock selected"]
#[inline(always)]
pub fn sysclk(self) -> &'a mut crate::W<REG> {
self.variant(USART1SEL_A::Sysclk)
}
#[doc = "HSI16 clock selected"]
#[inline(always)]
pub fn hsi16(self) -> &'a mut crate::W<REG> {
self.variant(USART1SEL_A::Hsi16)
}
#[doc = "LSE clock selected"]
#[inline(always)]
pub fn lse(self) -> &'a mut crate::W<REG> {
self.variant(USART1SEL_A::Lse)
}
}
#[doc = "Field `USART2SEL` reader - USART2 clock source selection"]
pub use USART1SEL_R as USART2SEL_R;
#[doc = "Field `USART2SEL` writer - USART2 clock source selection"]
pub use USART1SEL_W as USART2SEL_W;
#[doc = "Field `SPI2S2SEL` reader - SPI2S2 I2S clock source selection"]
pub type SPI2S2SEL_R = crate::FieldReader<SPI2S2SEL_A>;
#[doc = "SPI2S2 I2S clock source selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum SPI2S2SEL_A {
#[doc = "1: PLLQ clock selected"]
Pllq = 1,
#[doc = "2: HSI16 clock selected"]
Hsi16 = 2,
#[doc = "3: External input I2S_CKIN selected"]
I2s = 3,
}
impl From<SPI2S2SEL_A> for u8 {
#[inline(always)]
fn from(variant: SPI2S2SEL_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for SPI2S2SEL_A {
type Ux = u8;
}
impl SPI2S2SEL_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<SPI2S2SEL_A> {
match self.bits {
1 => Some(SPI2S2SEL_A::Pllq),
2 => Some(SPI2S2SEL_A::Hsi16),
3 => Some(SPI2S2SEL_A::I2s),
_ => None,
}
}
#[doc = "PLLQ clock selected"]
#[inline(always)]
pub fn is_pllq(&self) -> bool {
*self == SPI2S2SEL_A::Pllq
}
#[doc = "HSI16 clock selected"]
#[inline(always)]
pub fn is_hsi16(&self) -> bool {
*self == SPI2S2SEL_A::Hsi16
}
#[doc = "External input I2S_CKIN selected"]
#[inline(always)]
pub fn is_i2s(&self) -> bool {
*self == SPI2S2SEL_A::I2s
}
}
#[doc = "Field `SPI2S2SEL` writer - SPI2S2 I2S clock source selection"]
pub type SPI2S2SEL_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O, SPI2S2SEL_A>;
impl<'a, REG, const O: u8> SPI2S2SEL_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "PLLQ clock selected"]
#[inline(always)]
pub fn pllq(self) -> &'a mut crate::W<REG> {
self.variant(SPI2S2SEL_A::Pllq)
}
#[doc = "HSI16 clock selected"]
#[inline(always)]
pub fn hsi16(self) -> &'a mut crate::W<REG> {
self.variant(SPI2S2SEL_A::Hsi16)
}
#[doc = "External input I2S_CKIN selected"]
#[inline(always)]
pub fn i2s(self) -> &'a mut crate::W<REG> {
self.variant(SPI2S2SEL_A::I2s)
}
}
#[doc = "Field `LPUART1SEL` reader - LPUART1 clock source selection"]
pub type LPUART1SEL_R = crate::FieldReader<LPUART1SEL_A>;
#[doc = "LPUART1 clock source selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum LPUART1SEL_A {
#[doc = "0: PCLK clock selected"]
Pclk = 0,
#[doc = "1: SYSCLK clock selected"]
Sysclk = 1,
#[doc = "2: HSI16 clock selected"]
Hsi16 = 2,
#[doc = "3: LSE clock selected"]
Lse = 3,
}
impl From<LPUART1SEL_A> for u8 {
#[inline(always)]
fn from(variant: LPUART1SEL_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for LPUART1SEL_A {
type Ux = u8;
}
impl LPUART1SEL_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> LPUART1SEL_A {
match self.bits {
0 => LPUART1SEL_A::Pclk,
1 => LPUART1SEL_A::Sysclk,
2 => LPUART1SEL_A::Hsi16,
3 => LPUART1SEL_A::Lse,
_ => unreachable!(),
}
}
#[doc = "PCLK clock selected"]
#[inline(always)]
pub fn is_pclk(&self) -> bool {
*self == LPUART1SEL_A::Pclk
}
#[doc = "SYSCLK clock selected"]
#[inline(always)]
pub fn is_sysclk(&self) -> bool {
*self == LPUART1SEL_A::Sysclk
}
#[doc = "HSI16 clock selected"]
#[inline(always)]
pub fn is_hsi16(&self) -> bool {
*self == LPUART1SEL_A::Hsi16
}
#[doc = "LSE clock selected"]
#[inline(always)]
pub fn is_lse(&self) -> bool {
*self == LPUART1SEL_A::Lse
}
}
#[doc = "Field `LPUART1SEL` writer - LPUART1 clock source selection"]
pub type LPUART1SEL_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 2, O, LPUART1SEL_A>;
impl<'a, REG, const O: u8> LPUART1SEL_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "PCLK clock selected"]
#[inline(always)]
pub fn pclk(self) -> &'a mut crate::W<REG> {
self.variant(LPUART1SEL_A::Pclk)
}
#[doc = "SYSCLK clock selected"]
#[inline(always)]
pub fn sysclk(self) -> &'a mut crate::W<REG> {
self.variant(LPUART1SEL_A::Sysclk)
}
#[doc = "HSI16 clock selected"]
#[inline(always)]
pub fn hsi16(self) -> &'a mut crate::W<REG> {
self.variant(LPUART1SEL_A::Hsi16)
}
#[doc = "LSE clock selected"]
#[inline(always)]
pub fn lse(self) -> &'a mut crate::W<REG> {
self.variant(LPUART1SEL_A::Lse)
}
}
#[doc = "Field `I2C1SEL` reader - I2C1 clock source selection"]
pub type I2C1SEL_R = crate::FieldReader<I2C1SEL_A>;
#[doc = "I2C1 clock source selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum I2C1SEL_A {
#[doc = "0: PCLK clock selected"]
Pclk = 0,
#[doc = "1: SYSCLK clock selected"]
Sysclk = 1,
#[doc = "2: HSI16 clock selected"]
Hsi16 = 2,
}
impl From<I2C1SEL_A> for u8 {
#[inline(always)]
fn from(variant: I2C1SEL_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for I2C1SEL_A {
type Ux = u8;
}
impl I2C1SEL_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<I2C1SEL_A> {
match self.bits {
0 => Some(I2C1SEL_A::Pclk),
1 => Some(I2C1SEL_A::Sysclk),
2 => Some(I2C1SEL_A::Hsi16),
_ => None,
}
}
#[doc = "PCLK clock selected"]
#[inline(always)]
pub fn is_pclk(&self) -> bool {
*self == I2C1SEL_A::Pclk
}
#[doc = "SYSCLK clock selected"]
#[inline(always)]
pub fn is_sysclk(&self) -> bool {
*self == I2C1SEL_A::Sysclk
}
#[doc = "HSI16 clock selected"]
#[inline(always)]
pub fn is_hsi16(&self) -> bool {
*self == I2C1SEL_A::Hsi16
}
}
#[doc = "Field `I2C1SEL` writer - I2C1 clock source selection"]
pub type I2C1SEL_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O, I2C1SEL_A>;
impl<'a, REG, const O: u8> I2C1SEL_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "PCLK clock selected"]
#[inline(always)]
pub fn pclk(self) -> &'a mut crate::W<REG> {
self.variant(I2C1SEL_A::Pclk)
}
#[doc = "SYSCLK clock selected"]
#[inline(always)]
pub fn sysclk(self) -> &'a mut crate::W<REG> {
self.variant(I2C1SEL_A::Sysclk)
}
#[doc = "HSI16 clock selected"]
#[inline(always)]
pub fn hsi16(self) -> &'a mut crate::W<REG> {
self.variant(I2C1SEL_A::Hsi16)
}
}
#[doc = "Field `I2C2SEL` reader - I2C2 clock source selection"]
pub use I2C1SEL_R as I2C2SEL_R;
#[doc = "Field `I2C3SEL` reader - I2C3 clock source selection"]
pub use I2C1SEL_R as I2C3SEL_R;
#[doc = "Field `I2C2SEL` writer - I2C2 clock source selection"]
pub use I2C1SEL_W as I2C2SEL_W;
#[doc = "Field `I2C3SEL` writer - I2C3 clock source selection"]
pub use I2C1SEL_W as I2C3SEL_W;
#[doc = "Field `LPTIM1SEL` reader - Low power timer 1 clock source selection"]
pub type LPTIM1SEL_R = crate::FieldReader<LPTIM1SEL_A>;
#[doc = "Low power timer 1 clock source selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum LPTIM1SEL_A {
#[doc = "0: PCLK clock selected"]
Pclk = 0,
#[doc = "1: LSI clock selected"]
Lsi = 1,
#[doc = "2: HSI16 clock selected"]
Hsi16 = 2,
#[doc = "3: LSE clock selected"]
Lse = 3,
}
impl From<LPTIM1SEL_A> for u8 {
#[inline(always)]
fn from(variant: LPTIM1SEL_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for LPTIM1SEL_A {
type Ux = u8;
}
impl LPTIM1SEL_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> LPTIM1SEL_A {
match self.bits {
0 => LPTIM1SEL_A::Pclk,
1 => LPTIM1SEL_A::Lsi,
2 => LPTIM1SEL_A::Hsi16,
3 => LPTIM1SEL_A::Lse,
_ => unreachable!(),
}
}
#[doc = "PCLK clock selected"]
#[inline(always)]
pub fn is_pclk(&self) -> bool {
*self == LPTIM1SEL_A::Pclk
}
#[doc = "LSI clock selected"]
#[inline(always)]
pub fn is_lsi(&self) -> bool {
*self == LPTIM1SEL_A::Lsi
}
#[doc = "HSI16 clock selected"]
#[inline(always)]
pub fn is_hsi16(&self) -> bool {
*self == LPTIM1SEL_A::Hsi16
}
#[doc = "LSE clock selected"]
#[inline(always)]
pub fn is_lse(&self) -> bool {
*self == LPTIM1SEL_A::Lse
}
}
#[doc = "Field `LPTIM1SEL` writer - Low power timer 1 clock source selection"]
pub type LPTIM1SEL_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 2, O, LPTIM1SEL_A>;
impl<'a, REG, const O: u8> LPTIM1SEL_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "PCLK clock selected"]
#[inline(always)]
pub fn pclk(self) -> &'a mut crate::W<REG> {
self.variant(LPTIM1SEL_A::Pclk)
}
#[doc = "LSI clock selected"]
#[inline(always)]
pub fn lsi(self) -> &'a mut crate::W<REG> {
self.variant(LPTIM1SEL_A::Lsi)
}
#[doc = "HSI16 clock selected"]
#[inline(always)]
pub fn hsi16(self) -> &'a mut crate::W<REG> {
self.variant(LPTIM1SEL_A::Hsi16)
}
#[doc = "LSE clock selected"]
#[inline(always)]
pub fn lse(self) -> &'a mut crate::W<REG> {
self.variant(LPTIM1SEL_A::Lse)
}
}
#[doc = "Field `LPTIM2SEL` reader - Low power timer 2 clock source selection"]
pub use LPTIM1SEL_R as LPTIM2SEL_R;
#[doc = "Field `LPTIM3SEL` reader - Low power timer 3 clock source selection"]
pub use LPTIM1SEL_R as LPTIM3SEL_R;
#[doc = "Field `LPTIM2SEL` writer - Low power timer 2 clock source selection"]
pub use LPTIM1SEL_W as LPTIM2SEL_W;
#[doc = "Field `LPTIM3SEL` writer - Low power timer 3 clock source selection"]
pub use LPTIM1SEL_W as LPTIM3SEL_W;
#[doc = "Field `ADCSEL` reader - ADC clock source selection"]
pub type ADCSEL_R = crate::FieldReader<ADCSEL_A>;
#[doc = "ADC clock source selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum ADCSEL_A {
#[doc = "0: No clock selected"]
NoClock = 0,
#[doc = "1: HSI16 clock selected"]
Hsi16 = 1,
#[doc = "2: PLLP clock selected"]
Pllp = 2,
#[doc = "3: SYSCLK clock selected"]
Sysclk = 3,
}
impl From<ADCSEL_A> for u8 {
#[inline(always)]
fn from(variant: ADCSEL_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for ADCSEL_A {
type Ux = u8;
}
impl ADCSEL_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> ADCSEL_A {
match self.bits {
0 => ADCSEL_A::NoClock,
1 => ADCSEL_A::Hsi16,
2 => ADCSEL_A::Pllp,
3 => ADCSEL_A::Sysclk,
_ => unreachable!(),
}
}
#[doc = "No clock selected"]
#[inline(always)]
pub fn is_no_clock(&self) -> bool {
*self == ADCSEL_A::NoClock
}
#[doc = "HSI16 clock selected"]
#[inline(always)]
pub fn is_hsi16(&self) -> bool {
*self == ADCSEL_A::Hsi16
}
#[doc = "PLLP clock selected"]
#[inline(always)]
pub fn is_pllp(&self) -> bool {
*self == ADCSEL_A::Pllp
}
#[doc = "SYSCLK clock selected"]
#[inline(always)]
pub fn is_sysclk(&self) -> bool {
*self == ADCSEL_A::Sysclk
}
}
#[doc = "Field `ADCSEL` writer - ADC clock source selection"]
pub type ADCSEL_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 2, O, ADCSEL_A>;
impl<'a, REG, const O: u8> ADCSEL_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "No clock selected"]
#[inline(always)]
pub fn no_clock(self) -> &'a mut crate::W<REG> {
self.variant(ADCSEL_A::NoClock)
}
#[doc = "HSI16 clock selected"]
#[inline(always)]
pub fn hsi16(self) -> &'a mut crate::W<REG> {
self.variant(ADCSEL_A::Hsi16)
}
#[doc = "PLLP clock selected"]
#[inline(always)]
pub fn pllp(self) -> &'a mut crate::W<REG> {
self.variant(ADCSEL_A::Pllp)
}
#[doc = "SYSCLK clock selected"]
#[inline(always)]
pub fn sysclk(self) -> &'a mut crate::W<REG> {
self.variant(ADCSEL_A::Sysclk)
}
}
#[doc = "Field `RNGSEL` reader - RNG clock source selection"]
pub type RNGSEL_R = crate::FieldReader<RNGSEL_A>;
#[doc = "RNG clock source selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum RNGSEL_A {
#[doc = "0: PLLQ clock selected"]
Pllq = 0,
#[doc = "1: LSI clock selected"]
Lsi = 1,
#[doc = "2: LSE clock selected"]
Lse = 2,
#[doc = "3: MSI clock selected"]
Msi = 3,
}
impl From<RNGSEL_A> for u8 {
#[inline(always)]
fn from(variant: RNGSEL_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for RNGSEL_A {
type Ux = u8;
}
impl RNGSEL_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> RNGSEL_A {
match self.bits {
0 => RNGSEL_A::Pllq,
1 => RNGSEL_A::Lsi,
2 => RNGSEL_A::Lse,
3 => RNGSEL_A::Msi,
_ => unreachable!(),
}
}
#[doc = "PLLQ clock selected"]
#[inline(always)]
pub fn is_pllq(&self) -> bool {
*self == RNGSEL_A::Pllq
}
#[doc = "LSI clock selected"]
#[inline(always)]
pub fn is_lsi(&self) -> bool {
*self == RNGSEL_A::Lsi
}
#[doc = "LSE clock selected"]
#[inline(always)]
pub fn is_lse(&self) -> bool {
*self == RNGSEL_A::Lse
}
#[doc = "MSI clock selected"]
#[inline(always)]
pub fn is_msi(&self) -> bool {
*self == RNGSEL_A::Msi
}
}
#[doc = "Field `RNGSEL` writer - RNG clock source selection"]
pub type RNGSEL_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 2, O, RNGSEL_A>;
impl<'a, REG, const O: u8> RNGSEL_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "PLLQ clock selected"]
#[inline(always)]
pub fn pllq(self) -> &'a mut crate::W<REG> {
self.variant(RNGSEL_A::Pllq)
}
#[doc = "LSI clock selected"]
#[inline(always)]
pub fn lsi(self) -> &'a mut crate::W<REG> {
self.variant(RNGSEL_A::Lsi)
}
#[doc = "LSE clock selected"]
#[inline(always)]
pub fn lse(self) -> &'a mut crate::W<REG> {
self.variant(RNGSEL_A::Lse)
}
#[doc = "MSI clock selected"]
#[inline(always)]
pub fn msi(self) -> &'a mut crate::W<REG> {
self.variant(RNGSEL_A::Msi)
}
}
impl R {
#[doc = "Bits 0:1 - USART1 clock source selection"]
#[inline(always)]
pub fn usart1sel(&self) -> USART1SEL_R {
USART1SEL_R::new((self.bits & 3) as u8)
}
#[doc = "Bits 2:3 - USART2 clock source selection"]
#[inline(always)]
pub fn usart2sel(&self) -> USART2SEL_R {
USART2SEL_R::new(((self.bits >> 2) & 3) as u8)
}
#[doc = "Bits 8:9 - SPI2S2 I2S clock source selection"]
#[inline(always)]
pub fn spi2s2sel(&self) -> SPI2S2SEL_R {
SPI2S2SEL_R::new(((self.bits >> 8) & 3) as u8)
}
#[doc = "Bits 10:11 - LPUART1 clock source selection"]
#[inline(always)]
pub fn lpuart1sel(&self) -> LPUART1SEL_R {
LPUART1SEL_R::new(((self.bits >> 10) & 3) as u8)
}
#[doc = "Bits 12:13 - I2C1 clock source selection"]
#[inline(always)]
pub fn i2c1sel(&self) -> I2C1SEL_R {
I2C1SEL_R::new(((self.bits >> 12) & 3) as u8)
}
#[doc = "Bits 14:15 - I2C2 clock source selection"]
#[inline(always)]
pub fn i2c2sel(&self) -> I2C2SEL_R {
I2C2SEL_R::new(((self.bits >> 14) & 3) as u8)
}
#[doc = "Bits 16:17 - I2C3 clock source selection"]
#[inline(always)]
pub fn i2c3sel(&self) -> I2C3SEL_R {
I2C3SEL_R::new(((self.bits >> 16) & 3) as u8)
}
#[doc = "Bits 18:19 - Low power timer 1 clock source selection"]
#[inline(always)]
pub fn lptim1sel(&self) -> LPTIM1SEL_R {
LPTIM1SEL_R::new(((self.bits >> 18) & 3) as u8)
}
#[doc = "Bits 20:21 - Low power timer 2 clock source selection"]
#[inline(always)]
pub fn lptim2sel(&self) -> LPTIM2SEL_R {
LPTIM2SEL_R::new(((self.bits >> 20) & 3) as u8)
}
#[doc = "Bits 22:23 - Low power timer 3 clock source selection"]
#[inline(always)]
pub fn lptim3sel(&self) -> LPTIM3SEL_R {
LPTIM3SEL_R::new(((self.bits >> 22) & 3) as u8)
}
#[doc = "Bits 28:29 - ADC clock source selection"]
#[inline(always)]
pub fn adcsel(&self) -> ADCSEL_R {
ADCSEL_R::new(((self.bits >> 28) & 3) as u8)
}
#[doc = "Bits 30:31 - RNG clock source selection"]
#[inline(always)]
pub fn rngsel(&self) -> RNGSEL_R {
RNGSEL_R::new(((self.bits >> 30) & 3) as u8)
}
}
impl W {
#[doc = "Bits 0:1 - USART1 clock source selection"]
#[inline(always)]
#[must_use]
pub fn usart1sel(&mut self) -> USART1SEL_W<CCIPR_SPEC, 0> {
USART1SEL_W::new(self)
}
#[doc = "Bits 2:3 - USART2 clock source selection"]
#[inline(always)]
#[must_use]
pub fn usart2sel(&mut self) -> USART2SEL_W<CCIPR_SPEC, 2> {
USART2SEL_W::new(self)
}
#[doc = "Bits 8:9 - SPI2S2 I2S clock source selection"]
#[inline(always)]
#[must_use]
pub fn spi2s2sel(&mut self) -> SPI2S2SEL_W<CCIPR_SPEC, 8> {
SPI2S2SEL_W::new(self)
}
#[doc = "Bits 10:11 - LPUART1 clock source selection"]
#[inline(always)]
#[must_use]
pub fn lpuart1sel(&mut self) -> LPUART1SEL_W<CCIPR_SPEC, 10> {
LPUART1SEL_W::new(self)
}
#[doc = "Bits 12:13 - I2C1 clock source selection"]
#[inline(always)]
#[must_use]
pub fn i2c1sel(&mut self) -> I2C1SEL_W<CCIPR_SPEC, 12> {
I2C1SEL_W::new(self)
}
#[doc = "Bits 14:15 - I2C2 clock source selection"]
#[inline(always)]
#[must_use]
pub fn i2c2sel(&mut self) -> I2C2SEL_W<CCIPR_SPEC, 14> {
I2C2SEL_W::new(self)
}
#[doc = "Bits 16:17 - I2C3 clock source selection"]
#[inline(always)]
#[must_use]
pub fn i2c3sel(&mut self) -> I2C3SEL_W<CCIPR_SPEC, 16> {
I2C3SEL_W::new(self)
}
#[doc = "Bits 18:19 - Low power timer 1 clock source selection"]
#[inline(always)]
#[must_use]
pub fn lptim1sel(&mut self) -> LPTIM1SEL_W<CCIPR_SPEC, 18> {
LPTIM1SEL_W::new(self)
}
#[doc = "Bits 20:21 - Low power timer 2 clock source selection"]
#[inline(always)]
#[must_use]
pub fn lptim2sel(&mut self) -> LPTIM2SEL_W<CCIPR_SPEC, 20> {
LPTIM2SEL_W::new(self)
}
#[doc = "Bits 22:23 - Low power timer 3 clock source selection"]
#[inline(always)]
#[must_use]
pub fn lptim3sel(&mut self) -> LPTIM3SEL_W<CCIPR_SPEC, 22> {
LPTIM3SEL_W::new(self)
}
#[doc = "Bits 28:29 - ADC clock source selection"]
#[inline(always)]
#[must_use]
pub fn adcsel(&mut self) -> ADCSEL_W<CCIPR_SPEC, 28> {
ADCSEL_W::new(self)
}
#[doc = "Bits 30:31 - RNG clock source selection"]
#[inline(always)]
#[must_use]
pub fn rngsel(&mut self) -> RNGSEL_W<CCIPR_SPEC, 30> {
RNGSEL_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 = "Peripherals independent clock configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ccipr::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 [`ccipr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct CCIPR_SPEC;
impl crate::RegisterSpec for CCIPR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`ccipr::R`](R) reader structure"]
impl crate::Readable for CCIPR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`ccipr::W`](W) writer structure"]
impl crate::Writable for CCIPR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets CCIPR to value 0"]
impl crate::Resettable for CCIPR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use std::collections::HashMap;
#[derive(Debug)]
pub enum Stmt {
PenUp,
PenDown,
Forward(i32),
Backward(i32),
Turn(i32),
ChangeColor(Color),
ChangeColorRGB(i32, i32, i32),
Label(String),
Loop(String, i32),
}
#[derive(Debug, Copy, Clone)]
pub enum Color {
Red,
Green,
Blue,
Black,
}
#[derive(Debug, Copy, Clone)]
pub struct ColorRGB {
pub r: u8,
pub g: u8,
pub b: u8,
}
pub struct Program {
statements: Vec<Stmt>,
}
impl Program {
pub fn new(statements: Vec<Stmt>) -> Self {
Program { statements }
}
pub fn dump(&self) {
for stmt in self.statements.iter() {
println!("{:?}", stmt);
}
}
pub fn interpret(&self) -> Result<Vec<Line>, String>{
return Interpreter::new(self).execute();
}
}
struct Interpreter<'program> {
source: &'program Vec<Stmt>,
}
impl<'program> Interpreter<'program> {
fn new(program: &'program Program) -> Self {
Interpreter {
source: &program.statements,
}
}
fn execute(&mut self) -> Result<Vec<Line>, String> {
let mut pc: usize = 0;
let mut labels = HashMap::new();
let mut loop_store: HashMap<usize, i32> = HashMap::new();
let mut world: Vec<Line> = Vec::new();
let mut turtle = Turtle::new(
Point {
x: 0,
y: 0,
},
0, // start_heading
ColorRGB { // start_color
r: 0,
g: 0,
b: 0,
},
true // start_pendown
);
while let Some(stmt) = self.source.get(pc) {
match stmt {
&Stmt::PenUp => turtle.pen_down = false,
&Stmt::PenDown => turtle.pen_down = true,
&Stmt::Forward(n) => match turtle.forward(n as isize) {
Some(line) => world.push(line),
None => (),
},
&Stmt::Turn(n) => turtle.heading += (n % 360) as isize,
&Stmt::ChangeColor(c) => turtle.color = match c {
Color::Red => ColorRGB{r: 255, g: 0, b: 0},
Color::Green => ColorRGB{r: 0, g: 255, b: 0},
Color::Blue => ColorRGB{r: 0, g: 0, b: 255},
Color::Black => ColorRGB{r: 0, g: 0, b: 0},
},
/*&Stmt::ChangeColorRGB(r, g, b) => turtle.color = ColorRGB{
r: r as u8,
g: g as u8,
b: b as u8
},*/
&Stmt::ChangeColorRGB(r, g, b) => {
if r == 42 {
return Err(format!("Ccnnot be 42!!11!one"));
}
turtle.color = ColorRGB{
r: r as u8,
g: g as u8,
b: b as u8,
};
},
Stmt::Label(s) => { labels.entry(s).or_insert(pc); },
Stmt::Loop(l, c) => {
*loop_store.entry(pc).or_insert(*c + 1) -= 1;
let counter = loop_store.get(&pc).unwrap();
if *counter <= 0 {
loop_store.remove(&pc);
}
else
{
pc = match labels.get(l) {
Some(v) => *v,
None => { return Err(format!("Undefined label: {}", l)); },
}
}
},
other => return Err(format!("Unimplemented statement: {:?}", other)),
}
pc += 1;
}
Ok(world)
}
}
#[derive(Debug, Copy, Clone)]
pub struct Point {
pub x: isize,
pub y: isize,
}
#[derive(Debug)]
pub struct Line {
pub start: Point,
pub end: Point,
pub color: ColorRGB,
}
struct Turtle {
location: Point,
heading: isize,
color: ColorRGB,
pen_down: bool,
}
impl Turtle {
fn new(start_location: Point, start_heading: isize, start_color: ColorRGB, start_pendown: bool) -> Self {
Turtle {
location: start_location,
heading: start_heading,
color: start_color,
pen_down: start_pendown,
}
}
fn forward(&mut self, distance: isize) -> Option<Line> {
let old_location = self.location;
self.location = Point{
x: old_location.x + ((self.heading as f64).to_radians().cos() * distance as f64) as isize,
y: old_location.y + ((self.heading as f64).to_radians().sin() * distance as f64) as isize,
};
match self.pen_down {
true => Some(Line{start: old_location, end: self.location, color: self.color}),
false => None,
}
}
}
|
use generics::{Generic, Unit};
trait Accumulate {
fn acc(self) -> u64;
}
impl Accumulate for Unit {
fn acc(self) -> u64 {
13
}
}
#[derive(Generic)]
struct Foo;
#[test]
fn struct_unit() {
let foo = Foo;
assert_eq!(foo.into_repr().acc(), 13);
}
|
use nom::number::complete::{le_i8, le_u8, le_u16, le_f32};
use serde_derive::{Serialize};
use super::parserHeader::*;
#[derive(Debug, PartialEq, Serialize)]
pub struct MarshalZone {
pub m_zoneStart: f32,
pub m_zoneFlag: i8
}
named!(pub parse_mashall_zone<&[u8], MarshalZone>,
do_parse!(
m_zoneStart: le_f32 >>
m_zoneFlag: le_i8 >>
(MarshalZone {
m_zoneStart: m_zoneStart,
m_zoneFlag: m_zoneFlag
})
)
);
named!(pub parse_marshall_zones<&[u8], Vec<MarshalZone>>,
count!(parse_mashall_zone, 20)
);
#[derive(Debug, PartialEq, Serialize)]
pub struct PacketSessionData {
pub m_header: PacketHeader,
pub m_weather: u8,
pub m_trackTemperature: i8,
pub m_airTemperature: i8,
pub m_totalLaps: u8,
pub m_trackLength: u16,
pub m_sessionType: u8,
pub m_trackId: i8,
pub m_formula: u8,
pub m_sessionTimeLeft: u16,
pub m_sessionDuration: u16,
pub m_pitSpeedLimit: u8,
pub m_gamePaused: u8,
pub m_isSpectating: u8,
pub m_spectatorCarIndex: u8,
pub m_sliProNativeSupport: u8,
pub m_numMarshalZones: u8,
pub m_marshalZones: Vec<MarshalZone>,
pub m_safetyCarStatus: u8,
pub m_networkGame: u8
}
named!(pub parse_session_data_packet<&[u8], PacketSessionData>,
do_parse!(
m_header: parse_header >>
m_weather: le_u8 >>
m_trackTemperature: le_i8 >>
m_airTemperature: le_i8 >>
m_totalLaps: le_u8 >>
m_trackLength: le_u16 >>
m_sessionType: le_u8 >>
m_trackId: le_i8 >>
m_formula: le_u8 >>
m_sessionTimeLeft: le_u16 >>
m_sessionDuration: le_u16 >>
m_pitSpeedLimit: le_u8 >>
m_gamePaused: le_u8 >>
m_isSpectating: le_u8 >>
m_spectatorCarIndex: le_u8 >>
m_sliProNativeSupport: le_u8 >>
m_numMarshalZones: le_u8 >>
m_marshalZones: parse_marshall_zones >>
m_safetyCarStatus: le_u8 >>
m_networkGame: le_u8 >>
(PacketSessionData {
m_header: m_header,
m_weather: m_weather,
m_trackTemperature: m_trackTemperature,
m_airTemperature: m_airTemperature,
m_totalLaps: m_totalLaps,
m_trackLength: m_trackLength,
m_sessionType: m_sessionType,
m_trackId: m_trackId,
m_formula: m_formula,
m_sessionTimeLeft: m_sessionTimeLeft,
m_sessionDuration: m_sessionDuration,
m_pitSpeedLimit: m_pitSpeedLimit,
m_gamePaused: m_gamePaused,
m_isSpectating: m_isSpectating,
m_spectatorCarIndex: m_spectatorCarIndex,
m_sliProNativeSupport: m_sliProNativeSupport,
m_numMarshalZones: m_numMarshalZones,
m_marshalZones: m_marshalZones,
m_safetyCarStatus: m_safetyCarStatus,
m_networkGame: m_networkGame
})
)
);
|
use std::fmt::{self, Display};
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub enum IntPredicate {
EQ,
NE,
UGT,
UGE,
ULT,
ULE,
SGT,
SGE,
SLT,
SLE,
}
impl Display for IntPredicate {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
IntPredicate::EQ => write!(f, "eq"),
IntPredicate::NE => write!(f, "ne"),
IntPredicate::UGT => write!(f, "ugt"),
IntPredicate::UGE => write!(f, "uge"),
IntPredicate::ULT => write!(f, "ult"),
IntPredicate::ULE => write!(f, "ule"),
IntPredicate::SGT => write!(f, "sgt"),
IntPredicate::SGE => write!(f, "sge"),
IntPredicate::SLT => write!(f, "slt"),
IntPredicate::SLE => write!(f, "sle"),
}
}
}
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub enum FPPredicate {
False,
OEQ,
OGT,
OGE,
OLT,
OLE,
ONE,
ORD,
UNO,
UEQ,
UGT,
UGE,
ULT,
ULE,
UNE,
True,
}
impl Display for FPPredicate {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
FPPredicate::False => write!(f, "false"),
FPPredicate::OEQ => write!(f, "oeq"),
FPPredicate::OGT => write!(f, "ogt"),
FPPredicate::OGE => write!(f, "oge"),
FPPredicate::OLT => write!(f, "olt"),
FPPredicate::OLE => write!(f, "ole"),
FPPredicate::ONE => write!(f, "one"),
FPPredicate::ORD => write!(f, "ord"),
FPPredicate::UNO => write!(f, "uno"),
FPPredicate::UEQ => write!(f, "ueq"),
FPPredicate::UGT => write!(f, "ugt"),
FPPredicate::UGE => write!(f, "uge"),
FPPredicate::ULT => write!(f, "ult"),
FPPredicate::ULE => write!(f, "ule"),
FPPredicate::UNE => write!(f, "une"),
FPPredicate::True => write!(f, "true"),
}
}
}
// ********* //
// from_llvm //
// ********* //
use crate::llvm_sys::*;
use llvm_sys::LLVMIntPredicate;
use llvm_sys::LLVMRealPredicate;
impl IntPredicate {
pub(crate) fn from_llvm(pred: LLVMIntPredicate) -> Self {
match pred {
LLVMIntPredicate::LLVMIntEQ => IntPredicate::EQ,
LLVMIntPredicate::LLVMIntNE => IntPredicate::NE,
LLVMIntPredicate::LLVMIntUGT => IntPredicate::UGT,
LLVMIntPredicate::LLVMIntUGE => IntPredicate::UGE,
LLVMIntPredicate::LLVMIntULT => IntPredicate::ULT,
LLVMIntPredicate::LLVMIntULE => IntPredicate::ULE,
LLVMIntPredicate::LLVMIntSGT => IntPredicate::SGT,
LLVMIntPredicate::LLVMIntSGE => IntPredicate::SGE,
LLVMIntPredicate::LLVMIntSLT => IntPredicate::SLT,
LLVMIntPredicate::LLVMIntSLE => IntPredicate::SLE,
}
}
}
impl FPPredicate {
pub(crate) fn from_llvm(pred: LLVMRealPredicate) -> Self {
match pred {
LLVMRealPredicate::LLVMRealPredicateFalse => FPPredicate::False,
LLVMRealPredicate::LLVMRealOEQ => FPPredicate::OEQ,
LLVMRealPredicate::LLVMRealOGT => FPPredicate::OGT,
LLVMRealPredicate::LLVMRealOGE => FPPredicate::OGE,
LLVMRealPredicate::LLVMRealOLT => FPPredicate::OLT,
LLVMRealPredicate::LLVMRealOLE => FPPredicate::OLE,
LLVMRealPredicate::LLVMRealONE => FPPredicate::ONE,
LLVMRealPredicate::LLVMRealORD => FPPredicate::ORD,
LLVMRealPredicate::LLVMRealUNO => FPPredicate::UNO,
LLVMRealPredicate::LLVMRealUEQ => FPPredicate::UEQ,
LLVMRealPredicate::LLVMRealUGT => FPPredicate::UGT,
LLVMRealPredicate::LLVMRealUGE => FPPredicate::UGE,
LLVMRealPredicate::LLVMRealULT => FPPredicate::ULT,
LLVMRealPredicate::LLVMRealULE => FPPredicate::ULE,
LLVMRealPredicate::LLVMRealUNE => FPPredicate::UNE,
LLVMRealPredicate::LLVMRealPredicateTrue => FPPredicate::True,
}
}
}
|
extern crate document;
use self::PrincipalNodeType::*;
use super::XPathEvaluationContext;
use super::node_test::XPathNodeTest;
use super::nodeset::Nodeset;
use super::nodeset::Node::ElementNode;
pub enum PrincipalNodeType {
Attribute,
Element,
}
/// A directed traversal of Nodes.
pub trait XPathAxis {
/// Applies the given node test to the nodes selected by this axis,
/// adding matching nodes to the nodeset.
fn select_nodes<'a, 'd>(&self,
context: &XPathEvaluationContext<'a, 'd>,
node_test: &XPathNodeTest,
result: &mut Nodeset<'d>);
/// Describes what node type is naturally selected by this axis.
fn principal_node_type(&self) -> PrincipalNodeType {
Element
}
}
pub type SubAxis = Box<XPathAxis + 'static>;
pub struct AxisAttribute;
impl XPathAxis for AxisAttribute {
fn select_nodes<'a, 'd>(&self,
context: &XPathEvaluationContext<'a, 'd>,
node_test: &XPathNodeTest,
result: &mut Nodeset<'d>)
{
if let ElementNode(ref e) = context.node {
for attr in e.attributes().iter() {
let mut attr_context = context.new_context_for(1);
attr_context.next(*attr);
node_test.test(&attr_context, result);
}
}
}
fn principal_node_type(&self) -> PrincipalNodeType {
Attribute
}
}
pub struct AxisChild;
impl XPathAxis for AxisChild {
fn select_nodes<'a, 'd>(&self,
context: &XPathEvaluationContext<'a, 'd>,
node_test: &XPathNodeTest,
result: &mut Nodeset<'d>)
{
let n = context.node;
for child in n.children().iter() {
let mut child_context = context.new_context_for(1);
child_context.next(*child);
node_test.test(&child_context, result);
}
}
}
pub struct AxisDescendant;
impl XPathAxis for AxisDescendant {
fn select_nodes<'a, 'd>(&self,
context: &XPathEvaluationContext<'a, 'd>,
node_test: &XPathNodeTest,
result: &mut Nodeset<'d>)
{
let n = context.node;
for child in n.children().iter() {
let mut child_context = context.new_context_for(1);
child_context.next(*child);
node_test.test(&child_context, result);
self.select_nodes(&child_context, node_test, result);
}
}
}
pub struct AxisDescendantOrSelf {
descendant: AxisDescendant,
}
impl AxisDescendantOrSelf {
pub fn new() -> SubAxis { box AxisDescendantOrSelf{descendant: AxisDescendant} }
}
impl XPathAxis for AxisDescendantOrSelf {
fn select_nodes<'a, 'd>(&self,
context: &XPathEvaluationContext<'a, 'd>,
node_test: &XPathNodeTest,
result: &mut Nodeset<'d>)
{
node_test.test(context, result);
self.descendant.select_nodes(context, node_test, result);
}
}
pub struct AxisParent;
impl XPathAxis for AxisParent {
fn select_nodes<'a, 'd>(&self,
context: &XPathEvaluationContext<'a, 'd>,
node_test: &XPathNodeTest,
result: &mut Nodeset<'d>)
{
if let Some(p) = context.node.parent() {
let mut parent_context = context.new_context_for(1);
parent_context.next(p);
node_test.test(&parent_context, result);
}
}
}
pub struct AxisSelf;
impl XPathAxis for AxisSelf {
fn select_nodes<'a, 'd>(&self,
context: &XPathEvaluationContext<'a, 'd>,
node_test: &XPathNodeTest,
result: &mut Nodeset<'d>)
{
node_test.test(context, result);
}
}
|
use std::convert::TryFrom;
use std::convert::TryInto;
use bytes::Bytes;
use http::{Method, Response, StatusCode};
use crate::service::{ServiceClient, API_VERSION};
/// Execute the request to get the twin of a module or device.
pub(crate) async fn get_twin<T>(
service_client: &ServiceClient,
device_id: String,
module_id: Option<String>,
) -> crate::Result<T>
where
T: TryFrom<Response<Bytes>, Error = crate::Error>,
{
let uri = match module_id {
Some(val) => format!(
"https://{}.azure-devices.net/twins/{}/modules/{}?api-version={}",
service_client.iot_hub_name, device_id, val, API_VERSION
),
None => format!(
"https://{}.azure-devices.net/twins/{}?api-version={}",
service_client.iot_hub_name, device_id, API_VERSION
),
};
let request = service_client.prepare_request(&uri, Method::GET);
let request = request.body(bytes::Bytes::from_static(azure_core::EMPTY_BODY))?;
Ok(service_client
.http_client()
.execute_request_check_status(request, StatusCode::OK)
.await?
.try_into()?)
}
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(rustc_private)]
#![feature(collections)]
#![feature(str_char)]
// TODO we're going to allocate a whole bunch of temp Strings, is it worth
// keeping some scratch mem for this and running our own StrPool?
// TODO for lint violations of names, emit a refactor script
#[macro_use]
extern crate log;
extern crate getopts;
extern crate rustc;
extern crate rustc_driver;
extern crate syntax;
extern crate rustc_serialize;
extern crate strings;
use rustc::session::Session;
use rustc::session::config as rustc_config;
use rustc::session::config::Input;
use rustc_driver::{driver, CompilerCalls, Compilation};
use syntax::ast;
use syntax::codemap::CodeMap;
use syntax::diagnostics;
use syntax::visit;
use std::path::PathBuf;
use std::collections::HashMap;
use std::fmt;
use issues::{BadIssueSeeker, Issue};
use changes::ChangeSet;
use visitor::FmtVisitor;
#[macro_use]
mod config;
#[macro_use]
mod utils;
mod changes;
mod visitor;
mod items;
mod missed_spans;
mod lists;
mod types;
mod expr;
mod imports;
mod issues;
const MIN_STRING: usize = 10;
// When we get scoped annotations, we should have rustfmt::skip.
const SKIP_ANNOTATION: &'static str = "rustfmt_skip";
static mut CONFIG: Option<config::Config> = None;
#[derive(Copy, Clone)]
pub enum WriteMode {
Overwrite,
// str is the extension of the new file
NewFile(&'static str),
// Write the output to stdout.
Display,
// Return the result as a mapping from filenames to StringBuffers.
Return(&'static Fn(HashMap<String, String>)),
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum NewlineStyle {
Windows, // \r\n
Unix, // \n
}
impl_enum_decodable!(NewlineStyle, Windows, Unix);
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum BraceStyle {
AlwaysNextLine,
PreferSameLine,
// Prefer same line except where there is a where clause, in which case force
// the brace to the next line.
SameLineWhere,
}
impl_enum_decodable!(BraceStyle, AlwaysNextLine, PreferSameLine, SameLineWhere);
// How to indent a function's return type.
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum ReturnIndent {
// Aligned with the arguments
WithArgs,
// Aligned with the where clause
WithWhereClause,
}
impl_enum_decodable!(ReturnIndent, WithArgs, WithWhereClause);
enum ErrorKind {
// Line has more than config!(max_width) characters
LineOverflow,
// Line ends in whitespace
TrailingWhitespace,
// TO-DO or FIX-ME item without an issue number
BadIssue(Issue),
}
impl fmt::Display for ErrorKind {
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
ErrorKind::LineOverflow => {
write!(fmt, "line exceeded maximum length")
},
ErrorKind::TrailingWhitespace => {
write!(fmt, "left behind trailing whitespace")
},
ErrorKind::BadIssue(issue) => {
write!(fmt, "found {}", issue)
},
}
}
}
// Formatting errors that are identified *after* rustfmt has run
struct FormattingError {
line: u32,
kind: ErrorKind,
}
struct FormatReport {
// Maps stringified file paths to their associated formatting errors
file_error_map: HashMap<String, Vec<FormattingError>>,
}
impl fmt::Display for FormatReport {
// Prints all the formatting errors.
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
for (file, errors) in self.file_error_map.iter() {
for error in errors {
try!(write!(fmt,
"Rustfmt failed at {}:{}: {} (sorry)\n",
file,
error.line,
error.kind));
}
}
Ok(())
}
}
// Formatting which depends on the AST.
fn fmt_ast<'a>(krate: &ast::Crate, codemap: &'a CodeMap) -> ChangeSet<'a> {
let mut visitor = FmtVisitor::from_codemap(codemap);
visit::walk_crate(&mut visitor, krate);
let files = codemap.files.borrow();
if let Some(last) = files.last() {
visitor.format_missing(last.end_pos);
}
visitor.changes
}
// Formatting done on a char by char or line by line basis.
// TODO warn on bad license
// TODO other stuff for parity with make tidy
fn fmt_lines(changes: &mut ChangeSet) -> FormatReport {
let mut truncate_todo = Vec::new();
let mut report = FormatReport { file_error_map: HashMap::new() };
// Iterate over the chars in the change set.
for (f, text) in changes.text() {
let mut trims = vec![];
let mut last_wspace: Option<usize> = None;
let mut line_len = 0;
let mut cur_line = 1;
let mut newline_count = 0;
let mut errors = vec![];
let mut issue_seeker = BadIssueSeeker::new(config!(report_todo),
config!(report_fixme));
for (c, b) in text.chars() {
if c == '\r' { continue; }
// Add warnings for bad todos/ fixmes
if let Some(issue) = issue_seeker.inspect(c) {
errors.push(FormattingError {
line: cur_line,
kind: ErrorKind::BadIssue(issue)
});
}
if c == '\n' {
// Check for (and record) trailing whitespace.
if let Some(lw) = last_wspace {
trims.push((cur_line, lw, b));
line_len -= b - lw;
}
// Check for any line width errors we couldn't correct.
if line_len > config!(max_width) {
errors.push(FormattingError {
line: cur_line,
kind: ErrorKind::LineOverflow
});
}
line_len = 0;
cur_line += 1;
newline_count += 1;
last_wspace = None;
} else {
newline_count = 0;
line_len += 1;
if c.is_whitespace() {
if last_wspace.is_none() {
last_wspace = Some(b);
}
} else {
last_wspace = None;
}
}
}
if newline_count > 1 {
debug!("track truncate: {} {} {}", f, text.len, newline_count);
truncate_todo.push((f.to_owned(), text.len - newline_count + 1))
}
for &(l, _, _) in trims.iter() {
errors.push(FormattingError {
line: l,
kind: ErrorKind::TrailingWhitespace
});
}
report.file_error_map.insert(f.to_owned(), errors);
}
for (f, l) in truncate_todo {
changes.get_mut(&f).truncate(l);
}
report
}
struct RustFmtCalls {
input_path: Option<PathBuf>,
write_mode: WriteMode,
}
impl<'a> CompilerCalls<'a> for RustFmtCalls {
fn early_callback(&mut self,
_: &getopts::Matches,
_: &diagnostics::registry::Registry)
-> Compilation {
Compilation::Continue
}
fn some_input(&mut self,
input: Input,
input_path: Option<PathBuf>)
-> (Input, Option<PathBuf>) {
match input_path {
Some(ref ip) => self.input_path = Some(ip.clone()),
_ => {
// FIXME should handle string input and write to stdout or something
panic!("No input path");
}
}
(input, input_path)
}
fn no_input(&mut self,
_: &getopts::Matches,
_: &rustc_config::Options,
_: &Option<PathBuf>,
_: &Option<PathBuf>,
_: &diagnostics::registry::Registry)
-> Option<(Input, Option<PathBuf>)> {
panic!("No input supplied to RustFmt");
}
fn late_callback(&mut self,
_: &getopts::Matches,
_: &Session,
_: &Input,
_: &Option<PathBuf>,
_: &Option<PathBuf>)
-> Compilation {
Compilation::Continue
}
fn build_controller(&mut self, _: &Session) -> driver::CompileController<'a> {
let write_mode = self.write_mode;
let mut control = driver::CompileController::basic();
control.after_parse.stop = Compilation::Stop;
control.after_parse.callback = Box::new(move |state| {
let krate = state.krate.unwrap();
let codemap = state.session.codemap();
let mut changes = fmt_ast(krate, codemap);
// For some reason, the codemap does not include terminating newlines
// so we must add one on for each file. This is sad.
changes.append_newlines();
println!("{}", fmt_lines(&mut changes));
let result = changes.write_all_files(write_mode);
match result {
Err(msg) => println!("Error writing files: {}", msg),
Ok(result) => {
if let WriteMode::Return(callback) = write_mode {
callback(result);
}
}
}
});
control
}
}
// args are the arguments passed on the command line, generally passed through
// to the compiler.
// write_mode determines what happens to the result of running rustfmt, see
// WriteMode.
// default_config is a string of toml data to be used to configure rustfmt.
pub fn run(args: Vec<String>, write_mode: WriteMode, default_config: &str) {
config::set_config(default_config);
let mut call_ctxt = RustFmtCalls { input_path: None, write_mode: write_mode };
rustc_driver::run_compiler(&args, &mut call_ctxt);
}
|
fn main() {
// Type annotated variable
let _a_float: f64 = 1.0;
// This variable is an `i32`
let mut _an_integer = 5i32;
// Error! The type of a variable can't be changed
// an_integer = true;
}
|
use nu_ansi_term::{Color, Style};
use serde::Deserialize;
#[derive(Deserialize, PartialEq, Eq, Debug)]
pub struct NuStyle {
pub fg: Option<String>,
pub bg: Option<String>,
pub attr: Option<String>,
}
pub fn parse_nustyle(nu_style: NuStyle) -> Style {
// get the nu_ansi_term::Color foreground color
let fg_color = match nu_style.fg {
Some(fg) => color_from_hex(&fg).unwrap_or_default(),
_ => None,
};
// get the nu_ansi_term::Color background color
let bg_color = match nu_style.bg {
Some(bg) => color_from_hex(&bg).unwrap_or_default(),
_ => None,
};
// get the attributes
let color_attr = match nu_style.attr {
Some(attr) => attr,
_ => "".to_string(),
};
// setup the attributes available in nu_ansi_term::Style
let mut bold = false;
let mut dimmed = false;
let mut italic = false;
let mut underline = false;
let mut blink = false;
let mut reverse = false;
let mut hidden = false;
let mut strikethrough = false;
// since we can combine styles like bold-italic, iterate through the chars
// and set the bools for later use in the nu_ansi_term::Style application
for ch in color_attr.to_lowercase().chars() {
match ch {
'l' => blink = true,
'b' => bold = true,
'd' => dimmed = true,
'h' => hidden = true,
'i' => italic = true,
'r' => reverse = true,
's' => strikethrough = true,
'u' => underline = true,
'n' => (),
_ => (),
}
}
// here's where we build the nu_ansi_term::Style
Style {
foreground: fg_color,
background: bg_color,
is_blink: blink,
is_bold: bold,
is_dimmed: dimmed,
is_hidden: hidden,
is_italic: italic,
is_reverse: reverse,
is_strikethrough: strikethrough,
is_underline: underline,
}
}
pub fn color_string_to_nustyle(color_string: String) -> Style {
// eprintln!("color_string: {}", &color_string);
if color_string.chars().count() < 1 {
Style::default()
} else {
let nu_style = match nu_json::from_str::<NuStyle>(&color_string) {
Ok(s) => s,
Err(_) => NuStyle {
fg: None,
bg: None,
attr: None,
},
};
parse_nustyle(nu_style)
}
}
pub fn color_from_hex(
hex_color: &str,
) -> std::result::Result<Option<Color>, std::num::ParseIntError> {
// right now we only allow hex colors with hashtag and 6 characters
let trimmed = hex_color.trim_matches('#');
if trimmed.len() != 6 {
Ok(None)
} else {
// make a nu_ansi_term::Color::Rgb color by converting hex to decimal
Ok(Some(Color::Rgb(
u8::from_str_radix(&trimmed[..2], 16)?,
u8::from_str_radix(&trimmed[2..4], 16)?,
u8::from_str_radix(&trimmed[4..6], 16)?,
)))
}
}
|
use crossterm::{
cursor,
event::{poll, read, Event, KeyCode},
execute, queue,
style::{Print, ResetColor},
terminal::{self, disable_raw_mode, enable_raw_mode, ClearType},
Result,
};
use std::{
io::{stdout, Write},
time::Duration,
};
fn game_loop<W>(w: &mut W) -> Result<()>
where
W: Write,
{
loop {
queue!(
w,
ResetColor,
terminal::Clear(ClearType::All),
terminal::SetTitle("Rougelike Tutorial"),
cursor::Hide,
cursor::MoveTo(1, 1),
Print("Hello Rust World")
)?;
w.flush()?;
if poll(Duration::from_millis(200))? {
let event = read()?;
if event == Event::Key(KeyCode::Esc.into()) {
break;
}
}
}
execute!(w, ResetColor, cursor::Show)?;
Ok(())
}
fn main() -> Result<()> {
enable_raw_mode()?;
let mut stdout = stdout();
game_loop(&mut stdout)?;
disable_raw_mode()
}
|
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* rpc/mod.rs *
* *
* hprose rpc module for Rust. *
* *
* LastModified: Oct 9, 2016 *
* Author: Chen Fei <cf@hprose.com> *
* *
\**********************************************************/
mod client;
mod filter;
mod base_client;
mod http_client;
mod result_mode;
pub use self::client::{InvokeSettings, InvokeResult, InvokeError, Client, Transporter, ClientContext};
pub use self::filter::{Filter, FilterManager};
pub use self::base_client::BaseClient;
pub use self::http_client::{HttpClient, HttpTransporter};
pub use self::result_mode::ResultMode;
|
mod lexer;
pub use lexer::*;
#[cfg(test)]
mod lexer_test;
|
use crate::core::authentication_password::InvitationLink;
use crate::core::{env, Account, ServiceError, ServiceResult};
use lettre::smtp::authentication::Credentials;
use lettre::{SendableEmail, SmtpClient, Transport};
use lettre_email::EmailBuilder;
fn send_standard_mail(account: &Account, subj: &str, message: String) -> ServiceResult<()> {
let mail_address = if let Some(m) = account.mail.as_ref() {
m
} else {
return Err(ServiceError::InternalServerError(
"No Mail address provided",
String::from("A mail sending context was called, but no mail address was provided."),
));
};
let email = EmailBuilder::new()
// Addresses can be specified by the tuple (email, alias)
.to((mail_address, &account.name))
.from((env::MAIL_SENDER.as_str(), env::MAIL_SENDER_NAME.as_str()))
.subject(subj)
.text(message)
.build()?;
if env::MAIL_SERVER.as_str().ends_with(".local") {
// dump the mail to the log
let m: SendableEmail = email.into();
println!(
"{}",
m.message_to_string()
.expect("This was unrealistic to happen")
);
} else {
// Open a smtp connection
let mut mailer = SmtpClient::new_simple(&env::MAIL_SERVER)?
.credentials(Credentials::new(
env::MAIL_USER.clone(),
env::MAIL_PASS.clone(),
))
.transport();
// Send the email
let _ = mailer.send(email.into())?;
}
Ok(())
}
pub fn send_invitation_link(account: &Account, invite: &InvitationLink) -> ServiceResult<()> {
let mail_text = format!("Hello {user},
you have been invited to create an account in the ascii-pay system. You can use the following link to commence account creation.
Please note that your invitation will expire at {date}.
{link}
The Ascii Pay System
----
This mail has been automatically generated. Please do not reply.",
user = account.name,
date = invite.valid_until.format("%d.%m.%Y %H:%M"),
link = invite);
send_standard_mail(
account,
"[ascii pay] You have been invited to the ascii-pay service",
mail_text,
)
}
/// Send a generated monthly report to the user
pub fn send_report_mail(account: &Account, subject: String, report: String) -> ServiceResult<()> {
send_standard_mail(account, &subject, report)
}
// TODO: Needs a route!
/// Sends a test mail to the given receiver.
pub fn send_test_mail(receiver: String) -> ServiceResult<()> {
let mail = EmailBuilder::new()
.to(receiver)
.from(env::MAIL_SENDER.as_str())
.subject("[ascii pay] Test Mail")
.text("This is a test mail to verify that the mailing system works.")
.build()?;
let mut mailer = SmtpClient::new_simple(&env::MAIL_SERVER)?
.credentials(Credentials::new(
env::MAIL_USER.clone(),
env::MAIL_PASS.clone(),
))
.transport();
// Send the email
let _ = mailer.send(mail.into())?;
Ok(())
}
|
fn main() {
println!("Hello, world!");
another_function();
parameter_function(1, 3.54);
}
fn another_function() {
println!("another function here")
}
// Parameterized functions
fn parameter_function(x: i32, y:f64) {
println!("Values of x and y are {} and {}", x, y)
}
// Function with return
fn return_function() -> i32 {
// This is a statement
let x = 5;
// This is an expression, if we want a function to return it should be of type expression
// Also expressions do not end with ;
x
}
fn return_function2() -> i32 {
// This is a statement
let x = 5;
// This will return error because of ;
return x;
} |
use sfml::window;
use sfml::window::{window_style};
use sfml::system;
use sfml::graphics::{RenderWindow, RenderTarget, View};
pub fn create(width: u32, height: u32) -> (RenderWindow, View) {
let (mut w,v) = (
create_window(width, height),
create_view(width as f32, height as f32)
);
w.set_view(&v);
w.set_mouse_cursor_visible(false);
(w,v)
}
fn create_window(width: u32, height: u32) -> RenderWindow {
match RenderWindow::new(
window::VideoMode::new_init(width, height, 32),
"Fishies",
window_style::CLOSE,
&window::ContextSettings::default()) {
Some(window) => window,
None => panic!("Too foggy!")
}
}
fn create_view(width: f32, height: f32) -> View {
match View::new_init(&system::Vector2f {
x: width / 2.,
y: height / 2.
}, &system::Vector2f {
x: width,
y: height
}) {
Some(view) => view,
None => panic!("I can't see!")
}
} |
fn main() {
let s: String = {
let mut line = String::new();
std::io::stdin().read_line(&mut line).unwrap();
line.trim_end().to_owned()
};
let mut t = String::new();
let append_txts = ["dream", "dreamer", "erase", "eraser"];
while t.len() < s.len() {
for append_txt in &append_txts {
let t_copy = format!("{}{}", t, append_txt);
if t_copy.len() > s.len() {
println!("NO");
return;
}
let s_copy = &s[0..t_copy.len()];
if t_copy == s_copy {
t = t_copy;
break;
}
}
}
if t.len() == s.len() {
println!("YES");
} else {
println!("NO");
}
}
|
use rustler::types::truthy::Truthy;
use rustler::{Encoder, Env, NifResult, Term};
use rustler::{NifMap, NifRecord, NifStruct, NifTuple, NifUnitEnum, NifUntaggedEnum};
#[derive(NifTuple)]
pub struct AddTuple {
lhs: i32,
rhs: i32,
}
pub fn tuple_echo<'a>(_env: Env<'a>, args: &[Term<'a>]) -> NifResult<AddTuple> {
let tuple: AddTuple = args[0].decode()?;
Ok(tuple)
}
#[derive(NifRecord)]
#[rustler(encode, decode)] // Added to check encode/decode attribute, #180
#[must_use] // Added to check attribute order (see similar issue #152)
#[tag = "record"]
pub struct AddRecord {
lhs: i32,
rhs: i32,
}
pub fn record_echo<'a>(_env: Env<'a>, args: &[Term<'a>]) -> NifResult<AddRecord> {
let record: AddRecord = args[0].decode()?;
Ok(record)
}
#[derive(NifMap)]
pub struct AddMap {
lhs: i32,
rhs: i32,
}
pub fn map_echo<'a>(_env: Env<'a>, args: &[Term<'a>]) -> NifResult<AddMap> {
let map: AddMap = args[0].decode()?;
Ok(map)
}
#[derive(Debug, NifStruct)]
#[must_use] // Added to test Issue #152
#[module = "AddStruct"]
pub struct AddStruct {
lhs: i32,
rhs: i32,
}
pub fn struct_echo<'a>(_env: Env<'a>, args: &[Term<'a>]) -> NifResult<AddStruct> {
let add_struct: AddStruct = args[0].decode()?;
Ok(add_struct)
}
#[derive(NifUnitEnum)]
pub enum UnitEnum {
FooBar,
Baz,
}
pub fn unit_enum_echo<'a>(_env: Env<'a>, args: &[Term<'a>]) -> NifResult<UnitEnum> {
let unit_enum: UnitEnum = args[0].decode()?;
Ok(unit_enum)
}
#[derive(NifUntaggedEnum)]
pub enum UntaggedEnum {
Foo(u32),
Bar(String),
Baz(AddStruct),
Bool(bool),
}
pub fn untagged_enum_echo<'a>(_env: Env<'a>, args: &[Term<'a>]) -> NifResult<UntaggedEnum> {
let untagged_enum: UntaggedEnum = args[0].decode()?;
Ok(untagged_enum)
}
#[derive(NifUntaggedEnum)]
pub enum UntaggedEnumWithTruthy {
Baz(AddStruct),
Truthy(Truthy),
}
pub fn untagged_enum_with_truthy<'a>(
_env: Env<'a>,
args: &[Term<'a>],
) -> NifResult<UntaggedEnumWithTruthy> {
let untagged_enum: UntaggedEnumWithTruthy = args[0].decode()?;
Ok(untagged_enum)
}
#[derive(NifTuple)]
pub struct Newtype(i64);
pub fn newtype_echo<'a>(_env: Env<'a>, args: &[Term<'a>]) -> NifResult<Newtype> {
let newtype: Newtype = args[0].decode()?;
Ok(newtype)
}
#[derive(NifTuple)]
pub struct TupleStruct(i64, i64, i64);
pub fn tuplestruct_echo<'a>(_env: Env<'a>, args: &[Term<'a>]) -> NifResult<TupleStruct> {
let tuplestruct: TupleStruct = args[0].decode()?;
Ok(tuplestruct)
}
#[derive(NifRecord)]
#[tag = "newtype"]
pub struct NewtypeRecord(i64);
pub fn newtype_record_echo<'a>(_env: Env<'a>, args: &[Term<'a>]) -> NifResult<NewtypeRecord> {
let newtype: NewtypeRecord = args[0].decode()?;
Ok(newtype)
}
#[derive(NifRecord)]
#[tag = "tuplestruct"]
pub struct TupleStructRecord(i64, i64, i64);
pub fn tuplestruct_record_echo<'a>(
_env: Env<'a>,
args: &[Term<'a>],
) -> NifResult<TupleStructRecord> {
let tuplestruct: TupleStructRecord = args[0].decode()?;
Ok(tuplestruct)
}
|
use std::{collections::HashMap, marker::PhantomData, path::Path};
use crate::{
io,
prelude::*,
shader::{ActiveShader, BindUniform},
};
use futures::future::try_join_all;
use image::{DynamicImage, GenericImageView};
// Each marker struct represents a different texture target (e.g. TEXTURE_2D)
#[derive(Clone)]
pub struct T2d;
#[derive(Clone)]
pub struct TCubemap;
pub trait TextureTarget {
const TARGET: u32;
}
// Associate the corresponding GL constant with each type
impl TextureTarget for T2d {
const TARGET: u32 = glow::TEXTURE_2D;
}
impl TextureTarget for TCubemap {
const TARGET: u32 = glow::TEXTURE_CUBE_MAP;
}
pub struct TextureBuilder<'a, Target> {
gl: &'a Context,
tex_parameters: HashMap<u32, u32>,
flip: bool,
format: u32,
alignment: u32,
_marker: PhantomData<Target>,
}
impl<'a> TextureBuilder<'a, T2d> {
pub fn new(gl: &'a Context) -> Self {
TextureBuilder {
tex_parameters: hashmap! {
glow::TEXTURE_WRAP_S => glow::REPEAT,
glow::TEXTURE_WRAP_T => glow::REPEAT,
glow::TEXTURE_MIN_FILTER => glow::LINEAR_MIPMAP_LINEAR,
glow::TEXTURE_MAG_FILTER => glow::LINEAR
},
flip: true,
format: glow::RGBA,
alignment: 4,
_marker: PhantomData,
gl,
}
}
pub unsafe fn build(self, image: DynamicImage) -> Result<Texture<T2d>> {
let target = Self::target();
let internal_format = self.internal_format();
let (image, (width, height)) = self.convert_image(image);
// Make new texture into TEXTURE_2D global slot
let gl = self.gl;
gl.pixel_store_i32(glow::UNPACK_ALIGNMENT, self.alignment as i32);
let texture = gl.create_texture().map_err(Error::msg)?;
gl.bind_texture(target, Some(texture));
// Bind raw image data to the texture and make mipmap
gl.tex_image_2d(
target,
0,
internal_format as i32,
width as i32,
height as i32,
0,
self.format,
glow::UNSIGNED_BYTE,
Some(&image),
);
gl.generate_mipmap(target);
// Set wrapping parameters
Self::apply_texture_parameters(gl, self.tex_parameters);
gl.bind_texture(target, None);
Ok(Texture {
texture,
format: self.format,
_marker: PhantomData,
})
}
pub async unsafe fn load(self, path: impl AsRef<Path>) -> Result<Texture<T2d>> {
let image = io::load_image(path).await?;
self.build(image)
}
}
impl<'a> TextureBuilder<'a, TCubemap> {
pub unsafe fn build(self, images: Vec<DynamicImage>) -> Result<Texture<TCubemap>> {
let target = Self::target();
let internal_format = self.internal_format();
// Parse every image
let images = images
.into_iter()
.map(|image| self.convert_image(image))
.collect::<Vec<_>>();
let gl = self.gl;
let texture = gl.create_texture().map_err(Error::msg)?;
gl.bind_texture(target, Some(texture));
// Apply each image to a different section of the cubemap
for (i, (image, (width, height))) in images.into_iter().enumerate() {
gl.tex_image_2d(
glow::TEXTURE_CUBE_MAP_POSITIVE_X + (i as u32),
0,
internal_format as i32,
width as i32,
height as i32,
0,
self.format,
glow::UNSIGNED_BYTE,
Some(&image),
);
}
Self::apply_texture_parameters(gl, self.tex_parameters);
gl.bind_texture(target, None);
Ok(Texture {
texture,
format: self.format,
_marker: PhantomData,
})
}
pub async unsafe fn load(self, paths: Vec<String>) -> Result<Texture<TCubemap>> {
let file_futures = paths.into_iter().map(|path| io::load_image(path));
let all_bytes = try_join_all(file_futures).await?;
self.build(all_bytes)
}
}
impl<'a, Target: TextureTarget> TextureBuilder<'a, Target> {
pub fn with_tex_parameter(mut self, parameter: u32, value: u32) -> Self {
self.tex_parameters.insert(parameter, value);
self
}
pub fn with_flip(mut self, flip: bool) -> Self {
self.flip = flip;
self
}
pub fn with_format(mut self, format: u32) -> Self {
self.format = format;
self
}
pub fn with_alignment(mut self, alignment: u32) -> Self {
self.alignment = alignment;
self
}
pub fn as_cubemap(self) -> TextureBuilder<'a, TCubemap> {
self
.with_tex_parameter(glow::TEXTURE_MIN_FILTER, glow::LINEAR)
.with_tex_parameter(glow::TEXTURE_MAG_FILTER, glow::LINEAR)
.with_tex_parameter(glow::TEXTURE_WRAP_S, glow::CLAMP_TO_EDGE)
.with_tex_parameter(glow::TEXTURE_WRAP_T, glow::CLAMP_TO_EDGE)
.with_tex_parameter(glow::TEXTURE_WRAP_R, glow::CLAMP_TO_EDGE)
.with_flip(false)
.with_target()
}
pub fn with_target<S>(self) -> TextureBuilder<'a, S> {
let TextureBuilder {
gl,
tex_parameters,
flip,
format,
alignment,
..
} = self;
TextureBuilder {
gl,
tex_parameters,
flip,
format,
alignment,
_marker: PhantomData,
}
}
fn internal_format(&self) -> u32 {
match self.format {
glow::RGB | glow::RGBA => self.format,
glow::RED => glow::R8,
_ => unimplemented!(),
}
}
fn target() -> u32 {
Target::TARGET
}
fn convert_image(&self, image: DynamicImage) -> (Vec<u8>, (u32, u32)) {
let image = if self.flip { image.flipv() } else { image };
let dimensions = image.dimensions();
let bytes = match self.format {
glow::RGB => image.into_rgb8().into_raw(),
glow::RGBA => image.into_rgba8().into_raw(),
_ => unimplemented!(),
};
(bytes, dimensions)
}
unsafe fn apply_texture_parameters(gl: &Context, tex_parameters: HashMap<u32, u32>) {
for (key, value) in tex_parameters.into_iter() {
gl.tex_parameter_i32(Target::TARGET, key, value as i32);
}
}
pub unsafe fn render_texture(self, width: u32, height: u32) -> Result<Texture<Target>> {
let target = Self::target();
let internal_format = self.internal_format();
let gl = self.gl;
gl.pixel_store_i32(glow::UNPACK_ALIGNMENT, self.alignment as i32);
let texture = gl.create_texture().map_err(Error::msg)?;
gl.bind_texture(target, Some(texture));
gl.tex_image_2d(
target,
0,
internal_format as i32,
width as i32,
height as i32,
0,
self.format,
glow::UNSIGNED_BYTE,
None,
);
Self::apply_texture_parameters(gl, self.tex_parameters);
gl.bind_texture(target, None);
Ok(Texture {
texture,
format: self.format,
_marker: PhantomData,
})
}
}
#[derive(Clone)]
pub struct Texture<Target = T2d> {
pub texture: GlTexture,
format: u32,
_marker: PhantomData<Target>,
}
impl<Target: TextureTarget> Texture<Target> {
pub unsafe fn sub_image(
&self,
gl: &Context,
x_offset: u32,
y_offset: u32,
width: u32,
height: u32,
pixels: &[u8],
) {
let target = Target::TARGET;
gl.bind_texture(target, Some(self.texture));
gl.tex_sub_image_2d(
target,
0,
x_offset as i32,
y_offset as i32,
width as i32,
height as i32,
self.format,
glow::UNSIGNED_BYTE,
glow::PixelUnpackData::Slice(pixels),
);
}
}
impl<Target: TextureTarget> BindUniform for Texture<Target> {
unsafe fn bind_uniform(&self, gl: &Context, shader: &mut ActiveShader, name: &str) {
// TODO: should we be asking for a new texture slot every time? should Target be a param?
let unit = shader.new_texture_slot();
shader.bind_uniform(gl, name, &(unit as i32));
let gl_unit = glow::TEXTURE0 + unit;
gl.active_texture(gl_unit);
gl.bind_texture(Target::TARGET, Some(self.texture));
}
}
|
use std::iter;
use std::marker::PhantomData;
use std::ops::RangeFrom;
use tll::ternary::{Nat, Pred, NatPred, Succ, NatSucc, Triple, NatTriple, Term, Zero, One, Two};
use iterator::{Iterator, NonEmpty};
pub struct Enumerate<L: Nat, I: Iterator<L>, P: Nat> {
phantom: PhantomData<(L, P)>,
iter: I,
}
impl<L: Nat, I: Iterator<L>, P: Nat> iter::IntoIterator for Enumerate<L, I, P> {
type IntoIter = iter::Zip<RangeFrom<usize>, I::IntoIter>;
type Item = (usize, I::Item);
fn into_iter(self) -> Self::IntoIter {
(P::reify()..).zip(self.iter.into_iter())
}
}
impl<L: Nat, I: Iterator<L>> Enumerate<L, I, Term> {
pub fn new(iter: I) -> Enumerate<L, I, Term> {
Enumerate {
phantom: PhantomData,
iter: iter,
}
}
}
impl<L: Nat, I: Iterator<L>, P: Nat> Iterator<L> for Enumerate<L, I, P> {}
macro_rules! enumerate_impl {
($s:expr) => {
{
let (a, iter) = $s.iter.next();
let next = Enumerate {
phantom: PhantomData,
iter: iter,
};
((P::reify(), a), next)
}
};
}
impl<L: NatPred, I: NonEmpty<Zero<L>>, P: NatSucc> NonEmpty<Zero<L>> for Enumerate<Zero<L>, I, P>
where I::Next: Iterator<Two<Pred<L>>, Item = I::Item>
{
type Next = Enumerate<Two<Pred<L>>, I::Next, Succ<P>>;
fn next(self) -> ((usize, I::Item), Self::Next) {
enumerate_impl!(self)
}
}
impl<L: NatPred + NatTriple, I: NonEmpty<One<L>>, P: NatSucc> NonEmpty<One<L>> for Enumerate<One<L>, I, P>
where I::Next: Iterator<Triple<L>, Item = I::Item>
{
type Next = Enumerate<Triple<L>, I::Next, Succ<P>>;
fn next(self) -> ((usize, I::Item), Self::Next) {
enumerate_impl!(self)
}
}
impl<L: NatPred, I: NonEmpty<Two<L>>, P: NatSucc> NonEmpty<Two<L>> for Enumerate<Two<L>, I, P>
where I::Next: Iterator<One<L>, Item = I::Item>
{
type Next = Enumerate<One<L>, I::Next, Succ<P>>;
fn next(self) -> ((usize, I::Item), Self::Next) {
enumerate_impl!(self)
}
}
|
//! Utility module
use lib::*;
pub type Hash = [u8; 32];
/// Converts u32 to right aligned array of 32 bytes.
pub fn pad_u32(value: u32) -> Hash {
let mut padded = [0u8; 32];
padded[28] = (value >> 24) as u8;
padded[29] = (value >> 16) as u8;
padded[30] = (value >> 8) as u8;
padded[31] = value as u8;
padded
}
/// Converts u64 to right aligned array of 32 bytes.
pub fn pad_u64(value: u64) -> Hash {
let mut padded = [0u8; 32];
padded[24] = (value >> 56) as u8;
padded[25] = (value >> 48) as u8;
padded[26] = (value >> 40) as u8;
padded[27] = (value >> 32) as u8;
padded[28] = (value >> 24) as u8;
padded[29] = (value >> 16) as u8;
padded[30] = (value >> 8) as u8;
padded[31] = value as u8;
padded
}
/// Converts i64 to right aligned array of 32 bytes.
pub fn pad_i64(value: i64) -> Hash {
if value >= 0 {
return pad_u64(value as u64);
}
let mut padded = [0xffu8; 32];
padded[24] = (value >> 56) as u8;
padded[25] = (value >> 48) as u8;
padded[26] = (value >> 40) as u8;
padded[27] = (value >> 32) as u8;
padded[28] = (value >> 24) as u8;
padded[29] = (value >> 16) as u8;
padded[30] = (value >> 8) as u8;
padded[31] = value as u8;
padded
}
/// Converts i32 to right aligned array of 32 bytes.
pub fn pad_i32(value: i32) -> Hash {
if value >= 0 {
return pad_u32(value as u32);
}
let mut padded = [0xffu8; 32];
padded[28] = (value >> 24) as u8;
padded[29] = (value >> 16) as u8;
padded[30] = (value >> 8) as u8;
padded[31] = value as u8;
padded
} |
use SafeWrapper;
use ir::{User, Instruction, Value, AtomicOrdering, SynchronizationScope, AtomicBinaryOp};
use sys;
pub struct AtomicRMWInst<'ctx>(Instruction<'ctx>);
impl<'ctx> AtomicRMWInst<'ctx>
{
pub fn new(op: AtomicBinaryOp,
pointer: &Value,
value: &Value,
ordering: AtomicOrdering,
sync_scope: SynchronizationScope) -> Self {
unsafe {
let inner = sys::LLVMRustCreateAtomicRMWInst(op, pointer.inner(), value.inner(),
ordering, sync_scope);
wrap_value!(inner => User => Instruction => AtomicRMWInst)
}
}
}
impl_subtype!(AtomicRMWInst => Instruction);
|
pub mod datetime;
pub mod interfaces;
pub mod util;
|
use glium::texture::{cubemap::Cubemap, CubeLayer, TextureCreationError};
use glium::{Frame, Surface, Display, BlitTarget, framebuffer::{SimpleFrameBuffer, ValidationError}, uniforms::MagnifySamplerFilter};
use derive_more::{Error, From};
use crate::textures::{load_texture, TextureLoadError};
use crate::draw::{EnvDrawInfo, ObjDef};
use crate::cube::load_cube;
use std::path::Path;
use crate::assets::find_asset;
#[derive(Debug, derive_more::Display, Error, From)]
pub enum SkyboxError {
CubemapCreateError(TextureCreationError),
TextureLoadError(TextureLoadError),
FramebufferValidationError(ValidationError)
}
pub struct Skybox {
cubemap: Cubemap,
obj_def: ObjDef,
model_mat: [[f32; 4]; 4]
}
impl Skybox {
fn load_side(&self, display: &Display, blit_target: &BlitTarget, layer: CubeLayer, skybox_name: &str, img_filename: &str, app_id: &str) -> Result<(), SkyboxError> {
let path = Path::new("./textures").join(skybox_name).join(img_filename);
let path = find_asset(path.to_str().unwrap(), app_id);
let texture = load_texture(display, path.as_path(), false)?;
let fb = SimpleFrameBuffer::new(display, self.cubemap.main_level().image(layer))?;
texture.as_surface().blit_whole_color_to(&fb, blit_target, MagnifySamplerFilter::Linear);
Ok(())
}
pub fn new(display: &Display, name: &str, app_id: &str, texture_dim: u32, cube_size: f32) -> Result<Self, SkyboxError> {
let result = Self {
obj_def: load_cube(display, &[cube_size, cube_size, cube_size], true),
cubemap: Cubemap::empty(display, texture_dim)?,
model_mat: [
[1., 0., 0., 0.],
[0., 1., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.]
]
};
let sides = [
(CubeLayer::PositiveX, "posx.jpg"),
(CubeLayer::NegativeX, "negx.jpg"),
(CubeLayer::PositiveY, "posy.jpg"),
(CubeLayer::NegativeY, "negy.jpg"),
(CubeLayer::PositiveZ, "posz.jpg"),
(CubeLayer::NegativeZ, "negz.jpg")
];
let blit_target = glium::BlitTarget {
left: 0,
bottom: 0,
width: texture_dim as i32,
height: texture_dim as i32
};
for side in &sides {
result.load_side(display, &blit_target, side.0, name, side.1, app_id)?;
}
Ok(result)
}
pub fn draw(&self, target: &mut Frame, env_info: &EnvDrawInfo, program: &glium::Program) {
let uniforms = uniform! {
model: self.model_mat,
view: env_info.view_mat,
perspective: env_info.perspective_mat,
cubemap: self.cubemap.sampled().magnify_filter(glium::uniforms::MagnifySamplerFilter::Linear)
};
target.draw(&self.obj_def.vertices, &self.obj_def.indices, program, &uniforms, env_info.params).unwrap();
}
}
|
use errors::*;
use {OutputParameters, Parameters};
use tfdeploy::analyser::Analyser;
use tfdeploy::analyser::{DimFact, ShapeFact, TensorFact};
/// Handles the `analyse` subcommand.
pub fn handle(params: Parameters, optimize: bool, output_params: OutputParameters) -> Result<()> {
let model = params.tfd_model;
let output = model.get_node_by_id(params.output_node_id)?.id;
info!("Setting up analyser.");
let mut analyser = Analyser::new(model, output)?;
// Add hints for the input nodes.
if let Some(input) = params.input {
let dims = input
.shape
.iter()
.map(|d| match d {
None => DimFact::Streamed,
Some(i) => DimFact::Only(*i),
})
.collect::<Vec<_>>();
for &i in ¶ms.input_node_ids {
analyser.hint(
i,
&TensorFact {
datatype: typefact!(input.datatype),
shape: ShapeFact::closed(dims.clone()),
value: valuefact!(_),
},
)?;
}
}
info!("Running analyse");
analyser.run()?;
if optimize {
info!(
"Size of the graph before pruning: approx. {:.2?} Ko for {:?} nodes.",
::bincode::serialize(&analyser.nodes)?.len() as f64 * 1e-3,
analyser.nodes.len()
);
analyser.propagate_constants()?;
analyser.prune_unused();
info!(
"Size of the graph after pruning: approx. {:.2?} Ko for {:?} nodes.",
::bincode::serialize(&analyser.nodes)?.len() as f64 * 1e-3,
analyser.nodes.len()
);
}
let nodes: Vec<_> = analyser.nodes.iter().collect();
let display = ::display_graph::DisplayGraph::from_nodes(&*nodes)?
.with_graph_def(¶ms.graph)?
.with_analyser(&analyser)?;
display.render(&output_params)?;
Ok(())
}
|
#![no_main]
#![no_std]
#![feature(lang_items)]
#![feature(global_asm)]
#![feature(asm)]
#![allow(dead_code)]
use core::panic::PanicInfo;
global_asm!(include_str!("syscall_interrupts.s"));
#[no_mangle] // don't mangle the name of this function
pub extern "C" fn _start() -> ! {
let hello_world = "HELLO WORLD\n";
let hello_world_ptr = hello_world.as_ptr() as u64;
let num_bytes = hello_world.as_bytes().len();
let stack_pointer : u64;
unsafe {
asm!{
"mov {}, rbp",
out(reg) stack_pointer,
};
}
use core::ptr::addr_of;
unsafe { syscall(0, 0, hello_world_ptr ,num_bytes as u64)};
unsafe { syscall(0, 0, addr_of!(stack_pointer) as u64, 8)};
loop {
}
}
extern "C" {
fn syscall(call_num : u64, param1 : u64, param2 : u64, param3: u64) -> u64;
}
#[panic_handler]
fn panic(_panic: &PanicInfo<'_>) -> ! {
loop {}
} |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - RCC clock control register"]
pub cr: CR,
#[doc = "0x04 - RCC internal clock source calibration register"]
pub icscr: ICSCR,
#[doc = "0x08 - RCC clock configuration register"]
pub cfgr: CFGR,
_reserved3: [u8; 0x0c],
#[doc = "0x18 - RCC clock interrupt enable register"]
pub cier: CIER,
#[doc = "0x1c - RCC clock interrupt flag register"]
pub cifr: CIFR,
#[doc = "0x20 - RCC clock interrupt clear register"]
pub cicr: CICR,
#[doc = "0x24 - RCC I/O port reset register"]
pub ioprstr: IOPRSTR,
#[doc = "0x28 - RCC AHB peripheral reset register"]
pub ahbrstr: AHBRSTR,
#[doc = "0x2c - RCC APB peripheral reset register 1"]
pub apbrstr1: APBRSTR1,
#[doc = "0x30 - RCC APB peripheral reset register 2"]
pub apbrstr2: APBRSTR2,
#[doc = "0x34 - RCC I/O port clock enable register"]
pub iopenr: IOPENR,
#[doc = "0x38 - RCC AHB peripheral clock enable register"]
pub ahbenr: AHBENR,
#[doc = "0x3c - RCC APB peripheral clock enable register 1"]
pub apbenr1: APBENR1,
#[doc = "0x40 - RCC APB peripheral clock enable register 2"]
pub apbenr2: APBENR2,
#[doc = "0x44 - RCC I/O port in Sleep mode clock enable register"]
pub iopsmenr: IOPSMENR,
#[doc = "0x48 - RCC AHB peripheral clock enable in Sleep/Stop mode register"]
pub ahbsmenr: AHBSMENR,
#[doc = "0x4c - RCC APB peripheral clock enable in Sleep/Stop mode register 1"]
pub apbsmenr1: APBSMENR1,
#[doc = "0x50 - RCC APB peripheral clock enable in Sleep/Stop mode register 2"]
pub apbsmenr2: APBSMENR2,
#[doc = "0x54 - RCC peripherals independent clock configuration register"]
pub ccipr: CCIPR,
_reserved19: [u8; 0x04],
#[doc = "0x5c - RCC control/status register 1"]
pub csr1: CSR1,
#[doc = "0x60 - RCC control/status register 2"]
pub csr2: CSR2,
}
#[doc = "CR (rw) register accessor: RCC clock control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cr::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 [`cr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cr`]
module"]
pub type CR = crate::Reg<cr::CR_SPEC>;
#[doc = "RCC clock control register"]
pub mod cr;
#[doc = "ICSCR (rw) register accessor: RCC internal clock source calibration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`icscr::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 [`icscr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`icscr`]
module"]
pub type ICSCR = crate::Reg<icscr::ICSCR_SPEC>;
#[doc = "RCC internal clock source calibration register"]
pub mod icscr;
#[doc = "CFGR (rw) register accessor: RCC clock configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cfgr::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 [`cfgr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cfgr`]
module"]
pub type CFGR = crate::Reg<cfgr::CFGR_SPEC>;
#[doc = "RCC clock configuration register"]
pub mod cfgr;
#[doc = "CIER (rw) register accessor: RCC clock interrupt enable register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cier::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 [`cier::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cier`]
module"]
pub type CIER = crate::Reg<cier::CIER_SPEC>;
#[doc = "RCC clock interrupt enable register"]
pub mod cier;
#[doc = "CIFR (r) register accessor: RCC clock interrupt flag register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cifr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cifr`]
module"]
pub type CIFR = crate::Reg<cifr::CIFR_SPEC>;
#[doc = "RCC clock interrupt flag register"]
pub mod cifr;
#[doc = "CICR (w) register accessor: RCC clock interrupt clear register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cicr::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cicr`]
module"]
pub type CICR = crate::Reg<cicr::CICR_SPEC>;
#[doc = "RCC clock interrupt clear register"]
pub mod cicr;
#[doc = "IOPRSTR (rw) register accessor: RCC I/O port reset register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ioprstr::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 [`ioprstr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ioprstr`]
module"]
pub type IOPRSTR = crate::Reg<ioprstr::IOPRSTR_SPEC>;
#[doc = "RCC I/O port reset register"]
pub mod ioprstr;
#[doc = "AHBRSTR (rw) register accessor: RCC AHB peripheral reset register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ahbrstr::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 [`ahbrstr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ahbrstr`]
module"]
pub type AHBRSTR = crate::Reg<ahbrstr::AHBRSTR_SPEC>;
#[doc = "RCC AHB peripheral reset register"]
pub mod ahbrstr;
#[doc = "APBRSTR1 (rw) register accessor: RCC APB peripheral reset register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apbrstr1::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 [`apbrstr1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`apbrstr1`]
module"]
pub type APBRSTR1 = crate::Reg<apbrstr1::APBRSTR1_SPEC>;
#[doc = "RCC APB peripheral reset register 1"]
pub mod apbrstr1;
#[doc = "APBRSTR2 (rw) register accessor: RCC APB peripheral reset register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apbrstr2::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 [`apbrstr2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`apbrstr2`]
module"]
pub type APBRSTR2 = crate::Reg<apbrstr2::APBRSTR2_SPEC>;
#[doc = "RCC APB peripheral reset register 2"]
pub mod apbrstr2;
#[doc = "IOPENR (rw) register accessor: RCC I/O port clock enable register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`iopenr::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 [`iopenr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`iopenr`]
module"]
pub type IOPENR = crate::Reg<iopenr::IOPENR_SPEC>;
#[doc = "RCC I/O port clock enable register"]
pub mod iopenr;
#[doc = "AHBENR (rw) register accessor: RCC AHB peripheral clock enable register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ahbenr::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 [`ahbenr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ahbenr`]
module"]
pub type AHBENR = crate::Reg<ahbenr::AHBENR_SPEC>;
#[doc = "RCC AHB peripheral clock enable register"]
pub mod ahbenr;
#[doc = "APBENR1 (rw) register accessor: RCC APB peripheral clock enable register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apbenr1::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 [`apbenr1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`apbenr1`]
module"]
pub type APBENR1 = crate::Reg<apbenr1::APBENR1_SPEC>;
#[doc = "RCC APB peripheral clock enable register 1"]
pub mod apbenr1;
#[doc = "APBENR2 (rw) register accessor: RCC APB peripheral clock enable register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apbenr2::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 [`apbenr2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`apbenr2`]
module"]
pub type APBENR2 = crate::Reg<apbenr2::APBENR2_SPEC>;
#[doc = "RCC APB peripheral clock enable register 2"]
pub mod apbenr2;
#[doc = "IOPSMENR (rw) register accessor: RCC I/O port in Sleep mode clock enable register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`iopsmenr::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 [`iopsmenr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`iopsmenr`]
module"]
pub type IOPSMENR = crate::Reg<iopsmenr::IOPSMENR_SPEC>;
#[doc = "RCC I/O port in Sleep mode clock enable register"]
pub mod iopsmenr;
#[doc = "AHBSMENR (rw) register accessor: RCC AHB peripheral clock enable in Sleep/Stop mode register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ahbsmenr::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 [`ahbsmenr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ahbsmenr`]
module"]
pub type AHBSMENR = crate::Reg<ahbsmenr::AHBSMENR_SPEC>;
#[doc = "RCC AHB peripheral clock enable in Sleep/Stop mode register"]
pub mod ahbsmenr;
#[doc = "APBSMENR1 (rw) register accessor: RCC APB peripheral clock enable in Sleep/Stop mode register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apbsmenr1::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 [`apbsmenr1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`apbsmenr1`]
module"]
pub type APBSMENR1 = crate::Reg<apbsmenr1::APBSMENR1_SPEC>;
#[doc = "RCC APB peripheral clock enable in Sleep/Stop mode register 1"]
pub mod apbsmenr1;
#[doc = "APBSMENR2 (rw) register accessor: RCC APB peripheral clock enable in Sleep/Stop mode register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apbsmenr2::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 [`apbsmenr2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`apbsmenr2`]
module"]
pub type APBSMENR2 = crate::Reg<apbsmenr2::APBSMENR2_SPEC>;
#[doc = "RCC APB peripheral clock enable in Sleep/Stop mode register 2"]
pub mod apbsmenr2;
#[doc = "CCIPR (rw) register accessor: RCC peripherals independent clock configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ccipr::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 [`ccipr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ccipr`]
module"]
pub type CCIPR = crate::Reg<ccipr::CCIPR_SPEC>;
#[doc = "RCC peripherals independent clock configuration register"]
pub mod ccipr;
#[doc = "CSR1 (rw) register accessor: RCC control/status register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr1::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 [`csr1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr1`]
module"]
pub type CSR1 = crate::Reg<csr1::CSR1_SPEC>;
#[doc = "RCC control/status register 1"]
pub mod csr1;
#[doc = "CSR2 (rw) register accessor: RCC control/status register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr2::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 [`csr2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr2`]
module"]
pub type CSR2 = crate::Reg<csr2::CSR2_SPEC>;
#[doc = "RCC control/status register 2"]
pub mod csr2;
|
//use tokio::io::BufStream;
use tokio::net::{TcpStream, UnixStream};
pub enum Stream {
Unix(UnixStream),
Tcp(TcpStream),
}
impl From<TcpStream> for Stream {
#[inline]
fn from(stream: TcpStream) -> Self {
//Self::Tcp(BufStream::with_capacity(2048, 2048, stream))
Self::Tcp(stream)
}
}
impl From<UnixStream> for Stream {
#[inline]
fn from(stream: UnixStream) -> Self {
//Self::Unix(BufStream::with_capacity(2048, 2048, stream))
Self::Unix(stream)
}
}
use std::io::Result;
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
impl AsyncRead for Stream {
#[inline(always)]
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<Result<()>> {
match self.get_mut() {
Stream::Unix(ref mut stream) => AsyncRead::poll_read(Pin::new(stream), cx, buf),
Stream::Tcp(ref mut stream) => AsyncRead::poll_read(Pin::new(stream), cx, buf),
}
}
}
macro_rules! impl_async_write {
($($method:tt),+) => {
$(
#[inline(always)]
fn $method(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Result<()>> {
match self.get_mut() {
Stream::Unix(ref mut stream) => AsyncWrite::$method(Pin::new(stream), cx),
Stream::Tcp(ref mut stream) => AsyncWrite::$method(Pin::new(stream), cx),
}
}
)*
};
}
impl AsyncWrite for Stream {
#[inline(always)]
fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<Result<usize>> {
match self.get_mut() {
Stream::Unix(ref mut stream) => AsyncWrite::poll_write(Pin::new(stream), cx, buf),
Stream::Tcp(ref mut stream) => AsyncWrite::poll_write(Pin::new(stream), cx, buf),
}
}
impl_async_write!(poll_flush, poll_shutdown);
}
|
// Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
use crate::Example;
pub fn test_basic_proof_verification(e: Box<dyn Example>) {
let proof = e.prove();
assert!(e.verify(proof).is_ok());
}
pub fn test_basic_proof_verification_fail(e: Box<dyn Example>) {
let proof = e.prove();
let verified = e.verify_with_wrong_inputs(proof);
assert!(verified.is_err());
}
|
use std::ops::BitAnd;
///Describes the encoding of a register
///
/// Bit masks can be AND'd together to form the the output mask
#[derive(Clone,Copy,Debug,PartialEq,Eq)]
#[repr(u32)]
pub enum Encode {
/// This is the error condition
NONE = 0x00000000u32,
/// X86 requires. Using a REX prefix causes an error
X86_R = 0x00000001u32,
/// REX required
REX = 0x00000010u32,
/// This can only be encoded with VEX
VEX_R = 0x00000100u32,
/// This can only be encoded in EVEX
EVEX = 0x00001000u32,
/// XOP is a real wild card
XOP = 0x00010000u32,
/// This can be encoded in X86_R or REX mode
X86 = 0x00000011u32,
/// This can be encoded X86, REX, VEX, or EVEX
VEX = 0x00001111u32,
/// This can be encoded in REX, VEX, or EVEX
VEX_REX = 0x00001110u32,
/// Everything, special value used for seeding
EVERYTHING = 0x11111111u32
}
impl Into<u32> for Encode {
/// Cover the enum into a value
#[inline(always)]
fn into(self) -> u32 {
use std::mem;
unsafe{ mem::transmute(self) }
}
}
impl BitAnd<u32> for Encode {
type Output = bool;
/// this is used internally for checking if a bit mask matches
#[inline(always)]
fn bitand(self, other: u32) -> Self::Output {
let x: u32 = self.into();
(x & other) > 0
}
}
impl From<u32> for Encode {
/// apply the bit masking again used internally
#[inline(always)]
fn from(x: u32) -> Encode {
if Encode::X86_R & x {
return Encode::X86_R;
}
if Encode::REX & x {
return Encode::REX;
}
if Encode::VEX_R & x{
return Encode::VEX_R;
}
if Encode::XOP & x {
return Encode::XOP;
}
if Encode::EVEX & x {
return Encode::EVEX;
}
return Encode::NONE;
}
}
impl BitAnd<Encode> for Encode {
type Output = Encode;
/// The actual AND between Encode types
#[inline]
fn bitand(self, other: Encode) -> Self::Output {
let s: u32 = self.into();
let o: u32 = other.into();
Encode::from(s&o)
}
}
macro_rules! tester {
(
$a: expr, $b: expr, $ret: expr
) => {
let dut: Encode = $a&$b;
if dut != $ret {
panic!("{:?} and {:?} = {:?} but observed {:?}", $a, $b, $ret, dut);
}
}
}
#[test]
fn test_encode() {
tester!(Encode::X86,Encode::VEX, Encode::X86_R);
tester!(Encode::X86,Encode::REX, Encode::REX);
tester!(Encode::X86,Encode::X86_R, Encode::X86_R);
tester!(Encode::X86_R, Encode::REX, Encode::NONE);
}
|
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize)]
#[serde(transparent)]
pub struct True(bool);
impl Default for True {
fn default() -> Self {
Self(true)
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(transparent)]
pub struct False(bool);
#[allow(clippy::derivable_impls)] // I want the impl to be explict here
impl Default for False {
fn default() -> Self {
Self(false)
}
}
|
use core::cmp::Ordering;
/// Wrapper around usize for easy pointer math.
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
pub struct Address(usize);
impl Address {
/// Construct Self from usize
#[inline(always)]
pub fn from(val: usize) -> Address {
Address(val)
}
/// Offset from `base`
#[inline(always)]
pub fn offset_from(self, base: Address) -> usize {
debug_assert!(self >= base);
self.to_usize() - base.to_usize()
}
/// Return self + offset
#[inline(always)]
pub fn offset(self, offset: usize) -> Address {
Address(self.0 + offset)
}
/// Return self - offset
#[inline(always)]
pub fn sub(self, offset: usize) -> Address {
Address(self.0 - offset)
}
/// Add pointer to self.
#[inline(always)]
pub fn add_ptr(self, words: usize) -> Address {
Address(self.0 + words * core::mem::size_of::<usize>())
}
/// Sub pointer to self
#[inline(always)]
pub fn sub_ptr(self, words: usize) -> Address {
Address(self.0 - words * core::mem::size_of::<usize>())
}
/// Convert pointer to usize
#[inline(always)]
pub const fn to_usize(self) -> usize {
self.0
}
/// Construct from pointer
#[inline(always)]
pub fn from_ptr<T>(ptr: *const T) -> Address {
Address(ptr as usize)
}
/// Convert to *const T
#[inline(always)]
pub fn to_ptr<T>(&self) -> *const T {
self.0 as *const T
}
/// Convert to *mut T
#[inline(always)]
pub fn to_mut_ptr<T>(&self) -> *mut T {
self.0 as *const T as *mut T
}
/// Create null pointer
#[inline(always)]
pub fn null() -> Address {
Address(0)
}
/// Check if self is null
#[inline(always)]
pub fn is_null(self) -> bool {
self.0 == 0
}
/// Check if self is non null
#[inline(always)]
pub fn is_non_null(self) -> bool {
self.0 != 0
}
}
impl PartialOrd for Address {
fn partial_cmp(&self, other: &Address) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Address {
fn cmp(&self, other: &Address) -> Ordering {
self.to_usize().cmp(&other.to_usize())
}
}
impl From<usize> for Address {
fn from(val: usize) -> Address {
Address(val)
}
}
/// Rounds up `x` to multiple of `divisor`
pub const fn round_up_to_multiple_of(divisor: usize, x: usize) -> usize {
(x + (divisor - 1)) & !(divisor - 1)
}
|
use std::{env, path};
use ggez::event::{self, EventHandler};
use ggez::nalgebra::Point2;
use ggez::{filesystem, graphics, timer};
use ggez::{Context, GameResult};
const PHYSICS_SIMULATION_FPS: u32 = 100;
const PHYSICS_DELTA_TIME: f64 = 1.0 / PHYSICS_SIMULATION_FPS as f64;
impl EventHandler for TheFinalTouch {
fn update(&mut self, ctx: &mut Context) -> GameResult<()> {
while timer::check_update_time(ctx, PHYSICS_SIMULATION_FPS) {
let distance = self.velocity_x as f64 * PHYSICS_DELTA_TIME;
println!("[update] distance {}", distance);
self.previous_x = self.pos_x;
self.pos_x = self.pos_x % 800.0 + distance as f32;
}
Ok(())
}
fn draw(&mut self, ctx: &mut Context) -> GameResult<()> {
graphics::clear(ctx, graphics::WHITE);
self.draw_fps_counter(ctx)?;
let blended_x = self.interpolate(ctx);
self.draw_circles(ctx, blended_x)?;
graphics::present(ctx)
}
}
struct TheFinalTouch {
previous_x: f32,
pos_x: f32,
velocity_x: f32,
}
impl TheFinalTouch {
pub fn interpolate(&self, ctx: &mut Context) -> f32 {
let remainder = timer::remaining_update_time(ctx).as_secs_f64();
let alpha = remainder / PHYSICS_DELTA_TIME;
let previous_x = if self.pos_x >= self.previous_x {
self.previous_x
} else {
// if we're wrapping round, interpolating in between the two would mean
// circle would zip from right to left instead of going off screen
800.0 - self.previous_x
};
let blended_x = (self.pos_x * alpha as f32) + (previous_x * (1.0 - alpha as f32));
blended_x
}
pub fn draw_circles(&self, ctx: &mut Context, blended_x: f32) -> GameResult<()> {
let circle = graphics::Mesh::new_circle(
ctx,
graphics::DrawMode::fill(),
Point2::new(0.0, 0.0),
100.0,
2.0,
graphics::BLACK,
)?;
println!("{:?} {:?}", self.pos_x, blended_x);
graphics::draw(ctx, &circle, (Point2::new(self.pos_x, 150.0),))?;
graphics::draw(ctx, &circle, (Point2::new(blended_x, 380.0),))
}
pub fn new(_ctx: &mut Context) -> TheFinalTouch {
TheFinalTouch {
previous_x: 0.0,
pos_x: 0.0,
velocity_x: 150.0,
}
}
pub fn draw_fps_counter(&self, ctx: &mut Context) -> GameResult<()> {
let fps = timer::fps(ctx);
let delta = timer::delta(ctx);
let stats_display = graphics::Text::new(format!("FPS: {}, delta: {:?}", fps, delta));
println!(
"[draw] ticks: {}\tfps: {}\tdelta: {:?}",
timer::ticks(ctx),
fps,
delta,
);
graphics::draw(
ctx,
&stats_display,
(Point2::new(0.0, 0.0), graphics::BLACK),
)
}
}
fn main() -> GameResult {
let mut cb = ggez::ContextBuilder::new("name", "author");
if let Ok(manifest_dir) = env::var("CARGO_MANIFEST_DIR") {
let path = path::PathBuf::from(manifest_dir).join("resources");
cb = cb.add_resource_path(path);
}
let (ctx, event_loop) = &mut cb.build()?;
println!("{:#?}", filesystem::read_config(ctx));
let mut vsync_demo = TheFinalTouch::new(ctx);
event::run(ctx, event_loop, &mut vsync_demo)
}
|
use std::collections::HashMap;
use std::io::{stdout, Read, Write};
use std::fs::File;
use curl::easy::{Easy, List};
use serde_json::Value as JSONValue;
use error::OpenstackError;
use memmap::MmapOptions;
use indicatif::{ProgressBar, ProgressStyle};
use objectstore::{create_file, download_from_object_store, open_file, upload_to_object_store, upload_to_object_store_dynamic_large_objects};
#[derive(Debug, Serialize, Deserialize)]
pub struct Client {
#[serde(skip, default = "Easy::new")]
pub handle: Easy,
pub headers: HashMap<String, String>,
pub url: Option<String>,
pub method: Option<String>,
pub json: JSONValue,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Response ( pub JSONValue, pub u32, pub Vec<String> );
impl Response{
pub fn status(&self) -> u32{
self.1
}
pub fn response(&self) -> JSONValue{
self.0.clone()
}
pub fn headers(&self) -> Vec<String>{
self.2.clone()
}
pub fn parsed_headers(&self) -> HashMap<String, String>{
let mut headers = HashMap::new();
for item in self.headers(){
let new_item = item.clone();
let mut split = new_item.split(':');
let key = match split.next(){
Some(x) => x.trim(),
None => continue
};
let value = match split.next(){
Some(x) => x.trim(),
None => continue
};
headers.insert(key.to_string(), value.to_string());
}
headers
}
pub fn is_success(&self) -> bool{
!((self.1 / 100 == 4) | (self.1 / 100 == 5))
}
}
impl Default for Response{
fn default() -> Self{
Response{0: JSONValue::Null, 1: 0, 2: vec![]}
}
}
impl Client {
pub fn new() -> Self {
let handle = Easy::new();
let headers: HashMap<String, String> = HashMap::new();
let url = None;
let method = None;
let json = JSONValue::Null;
Client { handle, headers, url, method, json }
}
pub fn set_token(&mut self, token: &str) {
self.set_header("x-auth-token", token);
}
pub fn get_token(&mut self) -> Option<&String> {
self.headers.get("x-auth-token")
}
pub fn set_header(&mut self, header: &str, header_value: &str) {
self.headers
.insert(header.to_string(), header_value.to_string());
}
pub fn set_url(&mut self, url: &str){
self.url = Some(String::from(url));
}
pub fn set_method(&mut self, method: &str){
self.method = Some(String::from(method));
}
pub fn set_json(&mut self, json: JSONValue){
self.json = json;
}
pub fn perform(&mut self) -> Result<Response, OpenstackError>{
self.check_valid()?;
let method = self.method.clone().expect("this is checked to be not none");
let url = self.url.clone().expect("this is checked to be not none");
let json = self.json.clone();
self.request(&method, &url, json)
}
fn check_valid(&mut self) -> Result<(), OpenstackError>{
let mut errors = vec![];
if self.url.is_none(){
errors.push("url is not set")
}
if self.method.is_none(){
errors.push("method is not set")
}
if !errors.is_empty(){
let mut e = String::from("");
for item in errors{
if e == String::from(""){
e = item.to_string();
} else{
e = format!("{} and {}", e, item);
};
}
return Err(OpenstackError::new(&e))
}
Ok(())
}
fn headers_to_list(hashmap: HashMap<String, String>) -> List {
let mut local_headers = List::new();
for (header, header_value) in hashmap.iter() {
local_headers
.append(&format!("{}: {}", header, header_value))
.unwrap()
}
local_headers
}
pub fn request(
&mut self,
method: &str,
url: &str,
json: JSONValue,
) -> Result<Response, OpenstackError> {
let mut data = Vec::new();
self.handle.url(url)?;
self.handle.custom_request(method)?;
let mut local_headers = Self::headers_to_list(self.headers.clone());
match method.to_lowercase().as_ref() {
"post" => {
self.handle.post_fields_copy(json.to_string().as_bytes())?;
local_headers.append("Content-Type: application/json")?;
}
"put" | "patch" => {
self.handle.upload(true)?;
self.handle.in_filesize(json.to_string().len() as u64)?;
local_headers.append("Content-Type: application/json")?;
}
_ => {}
}
self.handle.http_headers(local_headers)?;
let mut remote_headers = vec![];
{
let body = json.to_string();
let mut transfer = self.handle.transfer();
transfer.write_function(|new_data| {
data.extend_from_slice(new_data);
Ok(new_data.len())
})?;
transfer.header_function(|header| {
remote_headers.push(String::from_utf8(header.to_vec()).unwrap_or(String::from(" : ")));
true
})?;
match method.to_lowercase().as_ref() {
"put"| "patch" => transfer.read_function(|into| Ok(body.as_bytes().read(into).unwrap()))?,
_ => ()
};
transfer.perform()?;
}
// self.handle.send(format!("{}", json).as_bytes())?;
let rv = String::from_utf8(data).unwrap_or("".to_string());
let response_data = match rv.parse(){
Ok(x) => x,
Err(_e) => rv.into()
};
Ok(Response{0: response_data, 1: self.handle.response_code()?, 2: remote_headers})
// Ok((rv.parse().unwrap(), self.handle.response_code()?))
}
pub fn get(&mut self, url: &str) -> Result<Response, OpenstackError> {
self.request("GET", url, JSONValue::String("".to_string()))
}
pub fn post(&mut self, url: &str, json: JSONValue) -> Result<Response, OpenstackError> {
self.request("POST", url, json)
}
pub fn put(&mut self, url: &str, json: JSONValue) -> Result<Response, OpenstackError> {
self.request("PUT", url, json)
}
pub fn patch(&mut self, url: &str, json: JSONValue) -> Result<Response, OpenstackError> {
self.request("PATCH", url, json)
}
pub fn delete(&mut self, url: &str) -> Result<Response, OpenstackError> {
self.request("DELETE", url, JSONValue::String("".to_string()))
}
pub fn option(&mut self, url: &str) -> Result<Response, OpenstackError> {
self.request("OPTION", url, JSONValue::String("".to_string()))
}
pub fn head(&mut self, url: &str) -> Result<Response, OpenstackError> {
self.request("HEAD", url, JSONValue::String("".to_string()))
}
fn open_file_ect(&mut self, filename: &str) -> Result<(File, String), OpenstackError> {
let token = match self.get_token(){
Some(x) => x,
None => return Err(OpenstackError::new("token is not set"))
};
let mut file = open_file(filename)?;
Ok((file, token.to_string()))
}
pub fn upload_to_object_store(&mut self, filename: &str, objectstore_url: &str) -> Result<Response, OpenstackError> {
let (mut file, token) = self.open_file_ect(filename)?;
upload_to_object_store(&mut file, objectstore_url, &token)
}
pub fn upload_to_object_store_large(&mut self, filename: &str, objectstore_url: &str, container: &str, name: &str) -> Result<Response, OpenstackError> {
let (mut file, token) = self.open_file_ect(filename)?;
upload_to_object_store_dynamic_large_objects(&mut file, name, container, objectstore_url, &token, 20, 0)
}
pub fn upload_to_object_store_large_with_parts(&mut self, filename: &str, objectstore_url: &str, container: &str, name: &str, parts: usize) -> Result<Response, OpenstackError> {
let (mut file, token) = self.open_file_ect(filename)?;
upload_to_object_store_dynamic_large_objects(&mut file, name, container, objectstore_url, &token, parts, 0)
}
pub fn upload_to_object_store_large_skip_parts(&mut self, filename: &str, objectstore_url: &str, container: &str, name: &str, parts: usize, skip_first: usize) -> Result<Response, OpenstackError> {
let (mut file, token) = self.open_file_ect(filename)?;
upload_to_object_store_dynamic_large_objects(&mut file, name, container, objectstore_url, &token, parts, skip_first)
}
pub fn download_from_object_store(&mut self, outfile: &str, objectstore_url: &str) -> Result<Response, OpenstackError> {
let token = match self.get_token(){
Some(x) => x,
None => return Err(OpenstackError::new("token is not set"))
};
let mut file = create_file(outfile)?;
download_from_object_store(&mut file, objectstore_url, token)
}
}
|
#[doc = "Register `DAC_SHRR` reader"]
pub type R = crate::R<DAC_SHRR_SPEC>;
#[doc = "Register `DAC_SHRR` writer"]
pub type W = crate::W<DAC_SHRR_SPEC>;
#[doc = "Field `TREFRESH1` reader - DAC Channel 1 refresh Time (only valid in sample &amp; hold mode) Refresh time= (TREFRESH\\[7:0\\]) x T LSI"]
pub type TREFRESH1_R = crate::FieldReader;
#[doc = "Field `TREFRESH1` writer - DAC Channel 1 refresh Time (only valid in sample &amp; hold mode) Refresh time= (TREFRESH\\[7:0\\]) x T LSI"]
pub type TREFRESH1_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>;
#[doc = "Field `TREFRESH2` reader - DAC Channel 2 refresh Time (only valid in sample &amp; hold mode) Refresh time= (TREFRESH\\[7:0\\]) x T LSI"]
pub type TREFRESH2_R = crate::FieldReader;
#[doc = "Field `TREFRESH2` writer - DAC Channel 2 refresh Time (only valid in sample &amp; hold mode) Refresh time= (TREFRESH\\[7:0\\]) x T LSI"]
pub type TREFRESH2_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>;
impl R {
#[doc = "Bits 0:7 - DAC Channel 1 refresh Time (only valid in sample &amp; hold mode) Refresh time= (TREFRESH\\[7:0\\]) x T LSI"]
#[inline(always)]
pub fn trefresh1(&self) -> TREFRESH1_R {
TREFRESH1_R::new((self.bits & 0xff) as u8)
}
#[doc = "Bits 16:23 - DAC Channel 2 refresh Time (only valid in sample &amp; hold mode) Refresh time= (TREFRESH\\[7:0\\]) x T LSI"]
#[inline(always)]
pub fn trefresh2(&self) -> TREFRESH2_R {
TREFRESH2_R::new(((self.bits >> 16) & 0xff) as u8)
}
}
impl W {
#[doc = "Bits 0:7 - DAC Channel 1 refresh Time (only valid in sample &amp; hold mode) Refresh time= (TREFRESH\\[7:0\\]) x T LSI"]
#[inline(always)]
#[must_use]
pub fn trefresh1(&mut self) -> TREFRESH1_W<DAC_SHRR_SPEC, 0> {
TREFRESH1_W::new(self)
}
#[doc = "Bits 16:23 - DAC Channel 2 refresh Time (only valid in sample &amp; hold mode) Refresh time= (TREFRESH\\[7:0\\]) x T LSI"]
#[inline(always)]
#[must_use]
pub fn trefresh2(&mut self) -> TREFRESH2_W<DAC_SHRR_SPEC, 16> {
TREFRESH2_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 = "DAC Sample and Hold refresh time register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`dac_shrr::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 [`dac_shrr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct DAC_SHRR_SPEC;
impl crate::RegisterSpec for DAC_SHRR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`dac_shrr::R`](R) reader structure"]
impl crate::Readable for DAC_SHRR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`dac_shrr::W`](W) writer structure"]
impl crate::Writable for DAC_SHRR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets DAC_SHRR to value 0x0001_0001"]
impl crate::Resettable for DAC_SHRR_SPEC {
const RESET_VALUE: Self::Ux = 0x0001_0001;
}
|
#[doc = "Register `MMC_RX_INTERRUPT` reader"]
pub type R = crate::R<MMC_RX_INTERRUPT_SPEC>;
#[doc = "Field `RXCRCERPIS` reader - MMC Receive CRC Error Packet Counter Interrupt Status"]
pub type RXCRCERPIS_R = crate::BitReader;
#[doc = "Field `RXALGNERPIS` reader - MMC Receive Alignment Error Packet Counter Interrupt Status"]
pub type RXALGNERPIS_R = crate::BitReader;
#[doc = "Field `RXUCGPIS` reader - MMC Receive Unicast Good Packet Counter Interrupt Status"]
pub type RXUCGPIS_R = crate::BitReader;
#[doc = "Field `RXLPIUSCIS` reader - MMC Receive LPI microsecond counter interrupt status"]
pub type RXLPIUSCIS_R = crate::BitReader;
#[doc = "Field `RXLPITRCIS` reader - MMC Receive LPI transition counter interrupt status"]
pub type RXLPITRCIS_R = crate::BitReader;
impl R {
#[doc = "Bit 5 - MMC Receive CRC Error Packet Counter Interrupt Status"]
#[inline(always)]
pub fn rxcrcerpis(&self) -> RXCRCERPIS_R {
RXCRCERPIS_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 6 - MMC Receive Alignment Error Packet Counter Interrupt Status"]
#[inline(always)]
pub fn rxalgnerpis(&self) -> RXALGNERPIS_R {
RXALGNERPIS_R::new(((self.bits >> 6) & 1) != 0)
}
#[doc = "Bit 17 - MMC Receive Unicast Good Packet Counter Interrupt Status"]
#[inline(always)]
pub fn rxucgpis(&self) -> RXUCGPIS_R {
RXUCGPIS_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bit 26 - MMC Receive LPI microsecond counter interrupt status"]
#[inline(always)]
pub fn rxlpiuscis(&self) -> RXLPIUSCIS_R {
RXLPIUSCIS_R::new(((self.bits >> 26) & 1) != 0)
}
#[doc = "Bit 27 - MMC Receive LPI transition counter interrupt status"]
#[inline(always)]
pub fn rxlpitrcis(&self) -> RXLPITRCIS_R {
RXLPITRCIS_R::new(((self.bits >> 27) & 1) != 0)
}
}
#[doc = "MMC Rx interrupt register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`mmc_rx_interrupt::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct MMC_RX_INTERRUPT_SPEC;
impl crate::RegisterSpec for MMC_RX_INTERRUPT_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`mmc_rx_interrupt::R`](R) reader structure"]
impl crate::Readable for MMC_RX_INTERRUPT_SPEC {}
#[doc = "`reset()` method sets MMC_RX_INTERRUPT to value 0"]
impl crate::Resettable for MMC_RX_INTERRUPT_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use crate::instruction::Instruction;
use crate::addressing_modes::AddressingMode;
pub static OPCODES : [Option<(Instruction, AddressingMode)>; 256 ] = [
Some((Instruction::Brk, AddressingMode::Implied)), // 0x00
Some((Instruction::Ora, AddressingMode::XIndexedIndirect)), // 0x01
None, // 0x02
None, // 0x03
None, // 0x04
Some((Instruction::Ora, AddressingMode::Zeropage)), // 0x05
Some((Instruction::Asl, AddressingMode::Zeropage)), // 0x06
None, // 0x07
Some((Instruction::Php, AddressingMode::Implied)), // 0x08
Some((Instruction::Ora, AddressingMode::Immediate)), // 0x09
Some((Instruction::Asl, AddressingMode::Accumulator)), // 0x0A
None, // 0x0B
None, // 0x0C
Some((Instruction::Ora, AddressingMode::Absolute)), // 0x0D
Some((Instruction::Asl, AddressingMode::Absolute)), // 0x0E
None, // 0x0F
Some((Instruction::Bpl, AddressingMode::Relative)), // 0x10
Some((Instruction::Ora, AddressingMode::AbsoluteYIndexed)), // 0x11
None, // 0x12
None, // 0x13
None, // 0x14
Some((Instruction::Ora, AddressingMode::ZeropageXIndexed)), // 0x15
Some((Instruction::Asl, AddressingMode::ZeropageXIndexed)), // 0x16
None, // 0x17
Some((Instruction::Clc, AddressingMode::Implied)), // 0x18
Some((Instruction::Ora, AddressingMode::AbsoluteYIndexed)), // 0x19
None, // 0x1A
None, // 0x1B
None, // 0x1C
Some((Instruction::Ora, AddressingMode::AbsoluteXIndexed)), // 0x1D
Some((Instruction::Asl, AddressingMode::AbsoluteXIndexed)), // 0x1E
None, // 0x1F
Some((Instruction::Jsr, AddressingMode::Absolute)), // 0x20
Some((Instruction::And, AddressingMode::XIndexedIndirect)), // 0x21
None, // 0x22
None, // 0x23
Some((Instruction::Bit, AddressingMode::Zeropage)), // 0x24
Some((Instruction::And, AddressingMode::Zeropage)), // 0x25
Some((Instruction::Rol, AddressingMode::Zeropage)), // 0x26
None, // 0x27
Some((Instruction::Plp, AddressingMode::Implied)), // 0x28
Some((Instruction::And, AddressingMode::Immediate)), // 0x29
Some((Instruction::Rol, AddressingMode::Accumulator)), // 0x2A
None, // 0x2B
Some((Instruction::Bit, AddressingMode::Absolute)), // 0x2C
Some((Instruction::And, AddressingMode::Absolute)), // 0x2D
Some((Instruction::Rol, AddressingMode::Absolute)), // 0x2E
None, // 0x2F
Some((Instruction::Bmi, AddressingMode::Relative)), // 0x30
Some((Instruction::And, AddressingMode::IndirectYIndexed)), // 0x31
None, // 0x32
None, // 0x33
None, // 0x34
Some((Instruction::And, AddressingMode::ZeropageXIndexed)), // 0x35
Some((Instruction::Rol, AddressingMode::ZeropageXIndexed)), // 0x36
None, // 0x37
Some((Instruction::Sec, AddressingMode::Implied)), // 0x38
Some((Instruction::And, AddressingMode::AbsoluteYIndexed)), // 0x39
None, // 0x3A
None, // 0x3B
None, // 0x3C
Some((Instruction::And, AddressingMode::AbsoluteXIndexed)), // 0x3D
Some((Instruction::Rol, AddressingMode::AbsoluteXIndexed)), // 0x3E
None, // 0x3F
Some((Instruction::Rti, AddressingMode::Implied)), // 0x40
Some((Instruction::Eor, AddressingMode::XIndexedIndirect)), // 0x41
None, // 0x42
None, // 0x43
None, // 0x44
Some((Instruction::Eor, AddressingMode::Zeropage)), // 0x45
Some((Instruction::Lsr, AddressingMode::Zeropage)), // 0x46
None, // 0x47
Some((Instruction::Pha, AddressingMode::Implied)), // 0x48
Some((Instruction::Eor, AddressingMode::Immediate)), // 0x49
Some((Instruction::Lsr, AddressingMode::Accumulator)), // 0x4A
None, // 0x4B
Some((Instruction::Jmp, AddressingMode::Absolute)), // 0x4C
Some((Instruction::Eor, AddressingMode::Absolute)), // 0x4D
Some((Instruction::Lsr, AddressingMode::Absolute)), // 0x4E
None, // 0x4F
Some((Instruction::Bvc, AddressingMode::Relative)), // 0x50
Some((Instruction::Eor, AddressingMode::IndirectYIndexed)), // 0x51
None, // 0x52
None, // 0x53
None, // 0x54
Some((Instruction::Eor, AddressingMode::ZeropageXIndexed)), // 0x55
Some((Instruction::Lsr, AddressingMode::ZeropageXIndexed)), // 0x56
None, // 0x57
Some((Instruction::Cli, AddressingMode::Implied)), // 0x58
Some((Instruction::Eor, AddressingMode::AbsoluteYIndexed)), // 0x59
None, // 0x5A
None, // 0x5B
None, // 0x5C
Some((Instruction::Eor, AddressingMode::AbsoluteXIndexed)), // 0x5D
Some((Instruction::Lsr, AddressingMode::AbsoluteXIndexed)), // 0x5E
None, // 0x5F
Some((Instruction::Rts, AddressingMode::Implied)), // 0x60
Some((Instruction::Adc, AddressingMode::XIndexedIndirect)), // 0x61
None, // 0x62
None, // 0x63
None, // 0x64
Some((Instruction::Adc, AddressingMode::Zeropage)), // 0x65
Some((Instruction::Ror, AddressingMode::Zeropage)), // 0x66
None, // 0x67
Some((Instruction::Pla, AddressingMode::Implied)), // 0x68
Some((Instruction::Adc, AddressingMode::Immediate)), // 0x69
Some((Instruction::Ror, AddressingMode::Accumulator)), // 0x6A
None, // 0x6B
Some((Instruction::Jmp, AddressingMode::Indirect)), // 0x6C
Some((Instruction::Adc, AddressingMode::Absolute)), // 0x6D
Some((Instruction::Ror, AddressingMode::Absolute)), // 0x6E
None, // 0x6F
Some((Instruction::Bvs, AddressingMode::Relative)), // 0x70
Some((Instruction::Adc, AddressingMode::IndirectYIndexed)), // 0x71
None, // 0x72
None, // 0x73
None, // 0x74
Some((Instruction::Adc, AddressingMode::ZeropageXIndexed)), // 0x75
Some((Instruction::Ror, AddressingMode::ZeropageXIndexed)), // 0x76
None, // 0x77
Some((Instruction::Sei, AddressingMode::Implied)), // 0x78
Some((Instruction::Adc, AddressingMode::AbsoluteYIndexed)), // 0x79
None, // 0x7A
None, // 0x7B
None, // 0x7C
Some((Instruction::Adc, AddressingMode::AbsoluteXIndexed)), // 0x7D
Some((Instruction::Ror, AddressingMode::AbsoluteXIndexed)), // 0x7E
None, // 0x7F
None, // 0x80
Some((Instruction::Sta, AddressingMode::IndirectYIndexed)), // 0x81
None, // 0x82
None, // 0x83
Some((Instruction::Sty, AddressingMode::Zeropage)), // 0x84
Some((Instruction::Sta, AddressingMode::Zeropage)), // 0x85
Some((Instruction::Stx, AddressingMode::Zeropage)), // 0x86
None, // 0x87
Some((Instruction::Dey, AddressingMode::Implied)), // 0x88
None, // 0x89
Some((Instruction::Txa, AddressingMode::Implied)), // 0x8A
None, // 0x8B
Some((Instruction::Sty, AddressingMode::Absolute)), // 0x8C
Some((Instruction::Sta, AddressingMode::Absolute)), // 0x8D
Some((Instruction::Stx, AddressingMode::Absolute)), // 0x8E
None, // 0x8F
Some((Instruction::Bcc, AddressingMode::Relative)), // 0x90
Some((Instruction::Sta, AddressingMode::IndirectYIndexed)), // 0x91
None, // 0x92
None, // 0x93
Some((Instruction::Sty, AddressingMode::ZeropageXIndexed)), // 0x94
Some((Instruction::Sta, AddressingMode::ZeropageXIndexed)), // 0x95
Some((Instruction::Stx, AddressingMode::ZeropageXIndexed)), // 0x96
None, // 0x97
Some((Instruction::Tya, AddressingMode::Implied)), // 0x98
Some((Instruction::Sta, AddressingMode::AbsoluteYIndexed)), // 0x99
Some((Instruction::Txs, AddressingMode::Implied)), // 0x9A
None, // 0x9B
None, // 0x9C
Some((Instruction::Sta, AddressingMode::AbsoluteXIndexed)), // 0x9D
None, // 0x9E
None, // 0x9F
Some((Instruction::Ldy, AddressingMode::Immediate)), // 0xA0
Some((Instruction::Lda, AddressingMode::XIndexedIndirect)), // 0xA1
Some((Instruction::Ldx, AddressingMode::Immediate)), // 0xA2
None, // 0xA3
Some((Instruction::Ldy, AddressingMode::Zeropage)), // 0xA4
Some((Instruction::Lda, AddressingMode::Zeropage)), // 0xA5
Some((Instruction::Ldx, AddressingMode::Zeropage)), // 0xA6
None, // 0xA7
Some((Instruction::Tay, AddressingMode::Implied)), // 0xA8
Some((Instruction::Lda, AddressingMode::Immediate)), // 0xA9
Some((Instruction::Tax, AddressingMode::Implied)), // 0xAA
None, // 0xAB
Some((Instruction::Ldy, AddressingMode::Absolute)), // 0xAC
Some((Instruction::Lda, AddressingMode::Absolute)), // 0xAD
Some((Instruction::Ldx, AddressingMode::Absolute)), // 0xAE
None, // 0xAF
Some((Instruction::Bcs, AddressingMode::Relative)), // 0xB0
Some((Instruction::Lda, AddressingMode::IndirectYIndexed)), // 0xB1
None, // 0xB2
None, // 0xB3
Some((Instruction::Ldy, AddressingMode::ZeropageXIndexed)), // 0xB4
Some((Instruction::Lda, AddressingMode::ZeropageXIndexed)), // 0xB5
Some((Instruction::Ldx, AddressingMode::ZeropageYIndexed)), // 0xB6
None, // 0xB7
Some((Instruction::Clv, AddressingMode::Implied)), // 0xB8
Some((Instruction::Lda, AddressingMode::AbsoluteYIndexed)), // 0xB9
Some((Instruction::Tsx, AddressingMode::Implied)), // 0xBA
None, // 0xBB
Some((Instruction::Ldy, AddressingMode::AbsoluteXIndexed)), // 0xBC
Some((Instruction::Lda, AddressingMode::AbsoluteXIndexed)), // 0xBD
Some((Instruction::Ldx, AddressingMode::AbsoluteYIndexed)), // 0xBE
None, // 0xBF
Some((Instruction::Cpy, AddressingMode::Immediate)), // 0xC0
Some((Instruction::Cmp, AddressingMode::XIndexedIndirect)), // 0xC1
None, // 0xC2
None, // 0xC3
Some((Instruction::Cpy, AddressingMode::Zeropage)), // 0xC4
Some((Instruction::Cmp, AddressingMode::Zeropage)), // 0xC5
Some((Instruction::Dec, AddressingMode::Zeropage)), // 0xC6
None, // 0xC7
Some((Instruction::Iny, AddressingMode::Implied)), // 0xC8
Some((Instruction::Cmp, AddressingMode::Immediate)), // 0xC9
Some((Instruction::Dex, AddressingMode::Implied)), // 0xCA
None, // 0xCB
Some((Instruction::Cpy, AddressingMode::Absolute)), // 0xCC
Some((Instruction::Cmp, AddressingMode::Absolute)), // 0xCD
Some((Instruction::Dec, AddressingMode::Absolute)), // 0xCE
None, // 0xCF
Some((Instruction::Bne, AddressingMode::Relative)), // 0xD0
Some((Instruction::Cmp, AddressingMode::IndirectYIndexed)), // 0xD1
None, // 0xD2
None, // 0xD3
None, // 0xD4
Some((Instruction::Cmp, AddressingMode::ZeropageXIndexed)), // 0xD5
Some((Instruction::Dec, AddressingMode::ZeropageXIndexed)), // 0xD6
None, // 0xD7
Some((Instruction::Cld, AddressingMode::Implied)), // 0xD8
Some((Instruction::Cmp, AddressingMode::AbsoluteYIndexed)), // 0xD9
None, // 0xDA
None, // 0xDB
None, // 0xDC
Some((Instruction::Cmp, AddressingMode::AbsoluteXIndexed)), // 0xDD
Some((Instruction::Dec, AddressingMode::AbsoluteXIndexed)), // 0xDE
None, // 0xDF
Some((Instruction::Cpx, AddressingMode::Immediate)), // 0xE0
Some((Instruction::Sbc, AddressingMode::XIndexedIndirect)), // 0xE1
None, // 0xE2
None, // 0xE3
Some((Instruction::Cpx, AddressingMode::Zeropage)), // 0xE4
Some((Instruction::Sbc, AddressingMode::Zeropage)), // 0xE5
Some((Instruction::Inc, AddressingMode::Zeropage)), // 0xE6
None, // 0xE7
Some((Instruction::Inx, AddressingMode::Implied)), // 0xE8
Some((Instruction::Sbc, AddressingMode::Immediate)), // 0xE9
Some((Instruction::Nop, AddressingMode::Implied)), // 0xEA
None, // 0xEB
Some((Instruction::Cpx, AddressingMode::Absolute)), // 0xEC
Some((Instruction::Sbc, AddressingMode::Absolute)), // 0xED
Some((Instruction::Inc, AddressingMode::Absolute)), // 0xEE
None, // 0xEF
Some((Instruction::Beq, AddressingMode::Relative)), // 0xF0
Some((Instruction::Sbc, AddressingMode::IndirectYIndexed)), // 0xF1
None, // 0xF2
None, // 0xF3
None, // 0xF4
Some((Instruction::Sbc, AddressingMode::ZeropageXIndexed)), // 0xF5
Some((Instruction::Inc, AddressingMode::ZeropageXIndexed)), // 0xF6
None, // 0xF7
Some((Instruction::Sed, AddressingMode::Implied)), // 0xF8
Some((Instruction::Sbc, AddressingMode::AbsoluteYIndexed)), // 0xF9
None, // 0xFA
None, // 0xFB
None, // 0xFC
Some((Instruction::Sbc, AddressingMode::AbsoluteXIndexed)), // 0xFD
Some((Instruction::Inc, AddressingMode::AbsoluteXIndexed)), // 0xFE
None, // 0xFF
];
|
use super::{Error, Result};
use crate::model::{Product, Wishlist};
use mongodb::bson::oid::ObjectId;
pub trait ProductDao: Send + Sync {
fn get_products_by_id(&self, ids: &[ObjectId]) -> Result<Vec<Product>>;
fn get_archived_products(&self, page: usize, per_page: usize) -> Result<Vec<Product>>;
fn get_products_for_wishlist(&self, wishlist: &Wishlist) -> Result<Vec<Product>> {
wishlist
.get_product_ids()
.ok_or(Error::FieldNotLoaded("wishlist", "product_ids"))
.and_then(|ids| self.get_products_by_id(ids).map_err(Error::from))
.map_err(Error::from)
}
}
|
use self::basic::BasicMemory;
mod basic;
const NES_MEMORY_SIZE: usize = 65536;
pub trait Memory {
fn fetch(&self, addr: u16) -> u8;
fn store(&mut self, addr: u16, value: u8) -> u8;
}
pub type NesMemorySpace = [u8; NES_MEMORY_SIZE];
pub struct NesMemory {
memory: BasicMemory<NesMemorySpace>,
}
impl NesMemory {
pub fn with_data(data: NesMemorySpace) -> Self {
NesMemory {
memory: BasicMemory::with_data(data),
}
}
pub fn fetch(&self, addr: u16) -> u8 {
self.memory.fetch(addr)
}
pub fn store(&mut self, addr: u16, value: u8) -> u8 {
self.memory.store(addr, value)
}
}
impl Default for NesMemory {
fn default() -> Self {
NesMemory::with_data([0; NES_MEMORY_SIZE])
}
}
|
#[cfg(test)]
mod tests {
use crate::util::pkcs7_pad;
use std::str;
// Ninth cryptopals challenge - https://cryptopals.com/sets/2/challenges/9
#[test]
fn challenge9() {
assert_eq!(
"YELLOW SUBMARINE\x04\x04\x04\x04",
str::from_utf8(&pkcs7_pad(&"YELLOW SUBMARINE".as_bytes(), 20)).unwrap()
);
}
}
|
use crate::row::Row;
use dfa_optimizer::{Row as DfaRow, Table as DfaTable};
use log::*;
use std::collections::{BTreeMap, BTreeSet};
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::iter::FromIterator;
use std::path::Path;
use log::debug;
pub type StateSet = BTreeSet<usize>;
#[derive(Debug, Clone, Default)]
pub struct Nfa {
// transition[start node][char][outgoing#] = end node
// Starting state is always node 0
lambda_char: char,
transitions: Vec<Vec<Vec<usize>>>, // potentially refactor this to map?
accepting_states: BTreeSet<usize>,
character_map: BTreeMap<char, usize>,
}
impl Nfa {
pub fn new() -> Self {
todo!()
}
pub fn lambda_char(&self) -> char {
self.lambda_char
}
pub fn character_map(&self) -> &BTreeMap<char, usize> {
&self.character_map
}
pub fn to_dfa(&self) -> DfaTable {
info!("character map: {:?} ", self.character_map());
info!("self at the start of to_dfa {:#?}", self);
let mut dfa_char_map = self.character_map().clone();
dfa_char_map.remove(&self.lambda_char);
let alpha_len = dfa_char_map.len(); // length of the new dfa alphabet
let mut dfa_rows = Vec::new();
let mut seen_states: BTreeMap<StateSet, usize> = BTreeMap::new();
let mut row_number = 0;
// TODO: Stack of &StateSet
let mut states_to_process = Vec::new();
let mut initial_state = BTreeSet::new();
initial_state.insert(0); // insert starting node
initial_state = self.follow_lambda(&initial_state);
debug!("Initial Lambda Closure: {:?}", initial_state);
let initial_lambda_accepting = initial_state
.intersection(&self.accepting_states)
.next()
.is_some();
let new_row = DfaRow::blank_row(initial_lambda_accepting, row_number, alpha_len);
dfa_rows.push(new_row);
seen_states.insert(initial_state.clone(), row_number);
states_to_process.push(initial_state);
row_number += 1;
while let Some(next_state_to_process) = states_to_process.pop() {
debug!("Next State: {:?}", next_state_to_process);
for character in dfa_char_map.values() {
let lambda_closure =
self.follow_lambda(&self.follow_char(&next_state_to_process, *character));
debug!("{} => {:?}", character, lambda_closure);
let lambda_clone = lambda_closure.clone();
if !seen_states.contains_key(&lambda_closure) {
debug!("Lambda closure in seen_states {:?}of", lambda_closure);
let accepting_state = lambda_closure
.intersection(&self.accepting_states)
.next()
.is_some();
info!("Is the new row an accepting state? {}", accepting_state);
let new_row = DfaRow::blank_row(accepting_state, row_number, alpha_len);
dfa_rows.push(new_row);
seen_states.insert(lambda_closure.clone(), row_number);
states_to_process.push(lambda_closure);
row_number += 1;
}
let current_row = seen_states[&next_state_to_process];
let transition = seen_states[&lambda_clone];
dfa_rows[current_row][*character - 1] = Some(transition);
}
}
let len = dfa_rows.len();
DfaTable::new(dfa_rows, len)
}
/*
* returns the set of NFA states encountered by
* recursively following only λ transitions.
*/
fn follow_lambda(&self, states: &StateSet) -> StateSet {
let mut states_to_process = Vec::from_iter(states.into_iter());
let mut lambda_closure = StateSet::new();
while let Some(t) = states_to_process.pop() {
lambda_closure.insert(*t);
for l_tran in self.transitions[*t][0].iter() {
if !lambda_closure.contains(&l_tran) {
lambda_closure.insert(*l_tran);
states_to_process.push(l_tran);
}
}
}
lambda_closure
}
/*
* returns the set of NFA states obtained from following character c
* from a set of states.
*/
fn follow_char(&self, states: &StateSet, c: usize) -> StateSet {
let mut follow = BTreeSet::new();
for state in states.iter() {
for transition in self.transitions[*state][c].iter() {
follow.insert(*transition);
}
}
follow
}
pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self, Box<dyn std::error::Error>> {
let file = File::open(path)?;
let reader = BufReader::new(file);
let mut all_rows = reader.lines().flatten();
let first_line = all_rows.next().unwrap();
let (character_map, lambda_char) = get_char_map(&first_line);
let num_states: usize = get_num_states(&first_line);
// let mut rows: Vec<Row> = all_rows.map(|r| r.parse().unwrap()).collect();
let mut rows: Vec<Row> = Vec::new();
for row in all_rows {
match Row::from_str_custom(&row) {
Ok(row) => rows.push(row),
_ => break,
}
// rows.push(Row::from_str_custom(&row).unwrap());
}
make_indexable(&mut rows);
let accepting_state_from_ids: Vec<usize> = rows
.iter()
.filter(|r| r.get_accepting_state())
.map(|r| r.get_from_id().to_owned())
.collect();
let transitions: Vec<Vec<Vec<usize>>> = get_transitions(&rows, &character_map, num_states);
Ok(Self {
lambda_char,
transitions,
character_map,
accepting_states: BTreeSet::from_iter(accepting_state_from_ids),
})
}
}
fn make_indexable(rows: &mut Vec<Row>) {
let mut state_map: BTreeMap<usize, usize> = BTreeMap::new();
state_map.insert(0, 0); // Start node is ALWAYS 0
for row in rows.iter() {
let from_index = row.get_from_id();
let to_index = row.get_to_id();
if !state_map.contains_key(&from_index) {
state_map.insert(from_index, state_map.len());
}
if !state_map.contains_key(&to_index) {
state_map.insert(to_index, state_map.len());
}
}
for row in rows {
let from_index = state_map.get(&row.get_from_id()).unwrap();
let to_index = state_map.get(&row.get_to_id()).unwrap();
row.set_from_id(*from_index);
row.set_to_id(*to_index);
}
}
fn get_transitions(
rows: &[Row],
char_map: &BTreeMap<char, usize>,
num_states: usize,
) -> Vec<Vec<Vec<usize>>> {
let mut outer: Vec<Vec<Vec<usize>>> = vec![vec![Vec::new(); char_map.len()]; num_states];
for row in rows {
let from_index = row.get_from_id();
let to_index = row.get_to_id();
for c in row.get_transitions() {
let char_index = char_map[c];
outer[from_index][char_index].push(to_index);
}
}
outer
}
fn get_num_states(first_lines: &str) -> usize {
first_lines
.split(' ')
.collect::<Vec<&str>>()
.into_iter()
.next()
.unwrap()
.parse()
.unwrap()
}
fn get_char_map(first_line: &str) -> (BTreeMap<char, usize>, char) {
let alphabet_letters: Vec<&str> = first_line
.split(' ')
.skip(1) // skip num of states
.collect();
let lambda_char = alphabet_letters[0].parse().unwrap();
let mut map = BTreeMap::new();
for (i, v) in alphabet_letters.iter().enumerate() {
map.insert(v.parse().expect("Error while looking at alphabet"), i);
}
(map, lambda_char)
}
|
use std::rc::Rc;
use crate::common::{ Value, Table, BuiltIn, RustFunc };
use crate::vm::{ VM, RuntimeError };
pub fn tbl_builtin(tbl: &Table, name: &str, func: &'static BuiltIn) {
let rf = RustFunc {
name: name.clone().into(),
func: func
};
tbl.insert(Value::String(name.into()), Value::NativeFunc(Rc::new(rf))).unwrap();
}
pub fn get(vm: &mut VM) -> Result<Value, RuntimeError> {
vm.nci.base += 1; // so this never gets read again
if vm.nci.base > vm.nci.top {
Err(RuntimeError::CustomError("expected value".into()))
} else {
let pos = vm.nci.base - 1;
Ok(vm.regs.get(pos as usize).unwrap_or(&Value::Nil).clone())
}
}
pub fn try_get(vm: &mut VM) -> Option<Value> {
let res = get(vm);
if let Ok(v) = res {
Some(v)
} else {
None
}
}
pub fn get_all(vm: &mut VM) -> Vec<Value> {
let mut vals = Vec::new();
for i in vm.nci.base .. vm.nci.top {
vals.push(vm.regs[i as usize].clone());
}
vals
}
#[macro_export]
macro_rules! get_all {
($vm:ident) => {
crate::vm::env::aux::get_all($vm)
};
}
#[macro_export]
macro_rules! expect {
($id:ident, $vm:ident) => {{
let val = crate::vm::env::aux::get($vm)?;
if let Value::$id(x) = val {
Ok(x.clone())
} else {
Err(format!("expected {} got {:?}", stringify!($id).to_lowercase(), crate::common::Type::from(&val)))
}}
};
}
#[macro_export]
macro_rules! expect_any {
($vm:ident) => {
crate::vm::env::aux::get($vm)?
};
}
#[macro_export]
macro_rules! optional {
($id:ident, $or:expr, $vm:ident) => {{
let val = crate::vm::env::aux::get($vm)?;
if let Value::$id(x) = val {
x.clone()
} else {
$or
}}
};
}
#[macro_export]
macro_rules! arg_check {
($cond:expr, $arg:expr, $err:expr) => {
if !($cond) {
Err(format!("bad argument #{} ({})", $arg, $err))
} else { Ok(()) }
};
} |
mod window;
fn main() {
window::make_window();
}
|
use std::borrow::Cow;
use anyhow::Result;
use crate::env_file::entry::Entry;
use crate::env_file::{Env, Var};
pub struct EnvDiffController {
update_var_fn: Box<dyn Fn(&mut Var) -> Result<Cow<Var>>>,
delete_var_fn: Box<dyn Fn(&Var) -> Result<bool>>,
}
impl EnvDiffController {
pub fn new<UVF: 'static, DVF: 'static>(update_var: UVF, delete_var: DVF) -> Self
where
UVF: Fn(&mut Var) -> Result<Cow<Var>>,
DVF: Fn(&Var) -> Result<bool>,
{
Self {
update_var_fn: Box::new(update_var),
delete_var_fn: Box::new(delete_var),
}
}
fn update_var<'a>(&self, var: &'a mut Var) -> Result<Cow<'a, Var>> {
(&self.update_var_fn)(var)
}
fn delete_var(&self, var: &Var) -> Result<bool> {
(&self.delete_var_fn)(var)
}
}
impl Env {
pub fn update_by_diff(&mut self, source_env: &Env, env_diff: &EnvDiffController) -> Result<()> {
let mut source_entries = source_env.entries.clone();
// Prevent delete vars.
// Append target entry to source entry if delete control return false.
// In this way we prevent the delete of the the variable.
for (index, target_entry) in self.entries.iter().enumerate() {
if let None = source_env
.entries
.iter()
.find(|entry| *entry == target_entry)
{
if let Entry::Var(var) = target_entry {
if !env_diff.delete_var(var)? {
source_entries.insert(index, target_entry.clone());
}
}
}
}
let mut new_entries = vec![];
// Delete vars : Don't append in new_entries var that not present in source_entries.
// Update vars : Vars can be update via the update control.
for source_entry in source_entries.iter() {
if let Some(target_entry) = self.entries.iter().find(|entry| *entry == source_entry) {
new_entries.push(target_entry.clone());
} else {
let source_entry = source_entry.clone();
if let Entry::Var(var) = source_entry {
let mut var = var;
let update_var = env_diff.update_var(&mut var)?;
new_entries.push(Entry::Var(update_var.into_owned()));
} else {
new_entries.push(source_entry);
}
}
}
self.entries = new_entries;
Ok(())
}
}
#[cfg(test)]
mod tests {
use std::borrow::Cow;
use crate::env_file::diff::EnvDiffController;
use crate::env_file::Env;
#[test]
fn update_by_diff_add_var() {
let mut env_source = Env::new("".into());
env_source.add("name1", "value1");
let mut env_target = Env::new("".into());
let controller = EnvDiffController::new(|var| Ok(Cow::Borrowed(var)), |_var| Ok(true));
env_target.update_by_diff(&env_source, &controller).unwrap();
let mut env_expected = Env::new("".into());
env_expected.add("name1", "value1");
assert_eq!(env_expected.to_string(), env_target.to_string());
}
#[test]
fn update_by_diff_add_altered_var() {
let mut env_source = Env::new("".into());
env_source.add("name1", "value1");
let mut env_target = Env::new("".into());
let controller = EnvDiffController::new(
|var| {
var.set_value("value1.1");
Ok(Cow::Borrowed(var))
},
|_var| Ok(true),
);
env_target.update_by_diff(&env_source, &controller).unwrap();
let mut env_expected = Env::new("".into());
env_expected.add("name1", "value1.1");
assert_eq!(env_expected.to_string(), env_target.to_string());
}
#[test]
fn update_by_diff_replace_var() {
let mut env_source = Env::new("".into());
env_source.add("name1", "value1");
let mut env_target = Env::new("".into());
env_target.add("name1", "value1.1");
let controller = EnvDiffController::new(|v| Ok(Cow::Borrowed(v)), |_| Ok(true));
env_target.update_by_diff(&env_source, &controller).unwrap();
let mut env_expected = Env::new("".into());
env_expected.add("name1", "value1.1");
assert_eq!(env_expected.to_string(), env_target.to_string());
}
#[test]
fn update_by_diff_delete_var_true() {
let env_source = Env::new("".into());
let mut env_target = Env::new("".into());
env_target.add("name1", "value1.1");
let controller = EnvDiffController::new(|v| Ok(Cow::Borrowed(v)), |_| Ok(true));
env_target.update_by_diff(&env_source, &controller).unwrap();
let env_expected = Env::new("".into());
assert_eq!(env_expected.to_string(), env_target.to_string());
}
#[test]
fn update_by_diff_delete_var_false() {
let env_source = Env::new("".into());
let mut env_target = Env::new("".into());
env_target.add("name1", "value1.1");
let controller = EnvDiffController::new(|v| Ok(Cow::Borrowed(v)), |_| Ok(false));
env_target.update_by_diff(&env_source, &controller).unwrap();
let mut env_expected = Env::new("".into());
env_expected.add("name1", "value1.1");
assert_eq!(env_expected.to_string(), env_target.to_string());
}
}
|
use super::traits::Circular;
pub fn parse(data: &str) -> usize {
let mut chars = data.chars().circular().peekable();
let mut sum: usize = 0;
loop {
let step: u32 = match (chars.next(), chars.peek()) {
(Some(chr1), Some(chr2)) if chr1 == *chr2 => {
chr1.to_digit(10).expect("Char to digit conversion failed")
},
(Some(_), Some(_)) => 0,
_ => break
};
sum += step as usize;
}
sum
}
#[cfg(test)]
mod tests {
use super::parse;
#[test]
fn day01_part1_test1() {
assert_eq!(3, parse("1122"));
}
#[test]
fn day01_part1_test2() {
assert_eq!(4, parse("1111"));
}
#[test]
fn day01_part1_test3() {
assert_eq!(0, parse("1234"));
}
#[test]
fn day01_part1_test4() {
assert_eq!(9, parse("91212129"));
}
}
|
//! Link: https://adventofcode.com/2019/day/9
//! Day 9: Sensor Boost
//!
//! You've just said goodbye to the rebooted rover and left Mars when you receive
//! a faint distress signal coming from the asteroid belt. It must be the Ceres monitoring station!
//!
//! In order to lock on to the signal, you'll need to boost your sensors.
//! The Elves send up the latest BOOST program - Basic Operation Of System Test.
//!
//! While BOOST (your puzzle input) is capable of boosting your sensors,
//! for tenuous safety reasons, it refuses to do so until the computer it runs on
//! passes some checks to demonstrate it is a complete Intcode computer.
use failure::Error;
use std::str::FromStr;
use crate::common::intcode_old::IntcodeVM;
#[aoc_generator(day9)]
fn input_generator(input: &str) -> IntcodeVM {
IntcodeVM::from_str(input).unwrap()
}
// Your existing Intcode computer is missing one key feature:
// it needs support for parameters in relative mode.
//
// Parameters in mode 2, relative mode, behave very similarly to parameters in position mode:
// the parameter is interpreted as a position.
// Like position mode, parameters in relative mode can be read from or written to.
//
// The important difference is that relative mode parameters don't count from address 0.
// Instead, they count from a value called the relative base. The relative base starts at 0.
//
// The address a relative mode parameter refers to is itself plus the current relative base.
// When the relative base is 0, relative mode parameters and position mode parameters with
// the same value refer to the same address.
//
// The relative base is modified with the relative base offset instruction:
// - Opcode 9 adjusts the relative base by the value of its only parameter.
// The relative base increases (or decreases, if the value is negative) by the value of the parameter.
//
// Your Intcode computer will also need a few other capabilities:
// - The computer's available memory should be much larger than the initial program.
// Memory beyond the initial program starts with the value 0 and
// can be read or written like any other memory.
// (It is invalid to try to access memory at a negative address, though.)
// - The computer should have support for large numbers.
// Some instructions near the beginning of the BOOST program will verify this capability.
//
// The BOOST program will ask for a single input; run it in test mode by providing it the value 1.
// It will perform a series of checks on each opcode,
// output any opcodes (and the associated parameter modes) that seem to be functioning incorrectly,
// and finally output a BOOST keycode.
//
// Once your Intcode computer is fully functional,
// the BOOST program should report no malfunctioning opcodes when run in test mode;
// it should only output a single value, the BOOST keycode.
// What BOOST keycode does it produce?
//
// Your puzzle answer was 2789104029.
#[aoc(day9, part1, IntcodeVM)]
fn solve_part1_intcode(vm: &IntcodeVM) -> Result<i64, Error> {
let output = vm.clone().simple_input(vec![1]).execute_and_collect()?;
Ok(*output.first().expect("expected output to contain at least one value"))
}
// You now have a complete Intcode computer.
//
// Finally, you can lock on to the Ceres distress signal!
// You just need to boost your sensors using the BOOST program.
//
// The program runs in sensor boost mode by providing the input instruction the value 2.
// Once run, it will boost the sensors automatically,
// but it might take a few seconds to complete the operation on slower hardware.
// In sensor boost mode, the program will output a single value:
// the coordinates of the distress signal.
//
// Run the BOOST program in sensor boost mode.
// What are the coordinates of the distress signal?
//
// Your puzzle answer was 32869.
#[aoc(day9, part2, IntcodeVM)]
fn solve_part2_intcode(vm: &IntcodeVM) -> Result<i64, Error> {
let output = vm.clone().simple_input(vec![2]).execute_and_collect()?;
Ok(*output.first().expect("expected output to contain at least one value"))
} |
use rocket::serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize)]
#[serde(crate = "rocket::serde")]
pub enum PayloadType {
Offer,
Answer,
Candidate,
Watch,
}
#[derive(Deserialize, Serialize)]
#[serde(crate = "rocket::serde")]
pub struct Payload {
pub pt: PayloadType,
pub payload: String,
pub id: String,
pub session: String,
}
|
use std::fs::File;
use std::io::Read;
use std::collections::HashMap;
use scan_fmt::*;
//use chrono::{DateTime, TimeZone, NaiveDateTime, Utc};
type Year = i32;
type Month = i32;
type Day = i32;
type Hour = i32;
type Min = i32;
type Kind = String;
type Id = i32;
#[derive(Debug, Eq, PartialEq, Hash)]
struct Date {
year: Year,
month: Month,
day: Day,
}
#[derive(Debug)]
struct Event {
date: Date,
hour: Hour,
min: Min,
kind: Kind
}
fn main() {
let mut file = File::open("input").unwrap();
let mut buf = String::new();
file.read_to_string(&mut buf).unwrap();
let lines: std::str::Lines<'_> = buf.lines();
let mut guards: HashMap<Id, HashMap<Date, [bool; 60]>> = HashMap::new();
let mut events: Vec<Event> = lines
.map(|line| {
let res = scan_fmt!(
line,
"[{}-{}-{}_{}:{}]_{}",
Year, Month, Day, Hour, Min, Kind
);
Event {
date: Date {
year: res.0.unwrap(),
month: res.1.unwrap(),
day: res.2.unwrap(),
},
hour: res.3.unwrap(),
min: res.4.unwrap(),
kind: res.5.unwrap(),
}
})
.collect();
events.sort_by(|a, b| {
a.date.year.cmp(&b.date.year).then(
a.date.month.cmp(&b.date.month).then(
a.date.day.cmp(&b.date.day).then(
a.hour.cmp(&b.hour).then(
a.min.cmp(&b.min)
)
)
)
)
});
let mut sleep_start = 0;
let mut current_id = 0;
for event in events {
if let Some(id) = scan_fmt!(&event.kind, "Guard_#{}_begins_shift", Id) {
current_id = id;
guards.entry(current_id).or_insert(HashMap::new());
} else if event.kind == "falls_asleep" {
sleep_start = event.min;
} else if event.kind == "wakes_up" {
let ref mut guard = guards.get_mut(¤t_id).unwrap();
let ref mut shift = guard.entry(event.date).or_insert([false; 60]);
let sleep_stop = event.min;
for i in sleep_start..sleep_stop {
shift[i as usize] = true;
}
} else {
println!("{}", event.kind);
unreachable!()
}
}
let mut max_sleep = 0;
let mut max_id = 0;
for (id, shifts) in guards.iter() {
let mut current_sleep = 0;
for shift in shifts.values() {
current_sleep += shift.iter().filter(|is_asleep| **is_asleep).count();
}
if max_sleep < current_sleep {
max_id = *id;
max_sleep = current_sleep;
}
}
let mut minutes = [0; 60];
for shift in guards.get(&max_id).unwrap().values() {
for (is_asleep, minute) in shift.iter().zip(minutes.iter_mut()) {
if *is_asleep {
*minute += 1;
}
}
}
let max_minute = minutes
.iter()
.enumerate()
.max_by(|a, b| a.1.cmp(&b.1))
.map(|x| x.0)
.unwrap();
println!("Strategy 1: {} = {}*{}", max_id*(max_minute as i32), max_id, max_minute);
let mut max_sleep = 0;
let mut max_id = 0;
let mut max_minute = 0;
for (current_id, shifts) in guards.iter() {
let mut minutes = [0; 60];
for shift in shifts.values() {
for (is_asleep, minute) in shift.iter().zip(minutes.iter_mut()) {
if *is_asleep {
*minute += 1;
}
}
}
let (current_max_minute, current_max_sleep) = minutes
.iter()
.enumerate()
.max_by(|a, b| a.1.cmp(&b.1))
.unwrap();
if max_sleep < *current_max_sleep {
max_id = *current_id;
max_sleep = *current_max_sleep;
max_minute = current_max_minute;
}
}
println!("Strategy 2: {} = {}*{}", max_id*(max_minute as i32), max_id, max_minute);
}
|
fn it_works() {}
|
pub mod backend;
pub mod crdt;
use backend::{CrdtBackend, MemoryBackend};
use crdt::Crdt;
impl Crdt<String> for String {
fn merge(self, other: String) -> String {
match self.len() > other.len() {
true => self,
false => other
}
}
}
#[derive(Eq, PartialEq, Ord, PartialOrd)]
struct Person {
age: i16
}
fn main() {
let mut backend: MemoryBackend<String, String> = MemoryBackend::new();
let key = "word".to_string();
backend.put(&key, "okaymaybethisisthelongest".to_string());
backend.delete(&key);
backend.put(&key, "short".to_string());
backend.put(&key, "a".to_string());
backend.put(&key, "longest".to_string());
let fetched = backend.get(&"word".to_string()).unwrap();
println!("\nResolved value:\n===============\n{}", fetched);
backend.put(&"other".to_string(), "another value".to_string());
let values = backend.get_many(&vec![key, "other".to_string(), "onemore".to_string()]).unwrap();
println!("{}", "\nValues:\n=======\n");
for value in values.iter() {
println!("{}", value);
}
}
|
use winapi::um::profileapi::{QueryPerformanceCounter, QueryPerformanceFrequency};
use winapi::um::winnt::LARGE_INTEGER;
const TICKS_PER_SECOND: u64 = 10000000;
//TODO: mark everything as unsafe
pub struct StepTimer {
qpc_frequency: LARGE_INTEGER,
qpc_last_time: LARGE_INTEGER,
qpc_max_delta: u64,
elapsed_ticks: u64,
total_ticks: u64,
leftover_ticks: u64,
frame_count: u32,
frames_per_second: u32,
frames_this_second: u32,
qpc_second_counter: u64,
is_fixed_timestep: bool,
target_elapsed_ticks: u64,
}
impl StepTimer {
pub fn new() -> StepTimer {
unsafe {
let mut freq: LARGE_INTEGER = std::mem::zeroed();
if QueryPerformanceFrequency(&mut freq) == 0 {
panic!("QueryPerformanceFrequency failed");
}
let mut last_time: LARGE_INTEGER = std::mem::zeroed();
if QueryPerformanceCounter(&mut last_time) == 0 {
panic!("QueryPerformanceCounter failed");
}
let max_delta = (freq.QuadPart() / 10) as u64;
StepTimer {
qpc_frequency: freq,
qpc_last_time: last_time,
qpc_max_delta: max_delta,
elapsed_ticks: 0,
total_ticks: 0,
leftover_ticks: 0,
frame_count: 0,
frames_per_second: 0,
frames_this_second: 0,
qpc_second_counter: 0,
is_fixed_timestep: false,
target_elapsed_ticks: TICKS_PER_SECOND / 60,
}
}
}
pub fn tick<F>(&mut self, mut update_func: F)
where
F: FnMut(&mut StepTimer),
{
unsafe {
let mut current_time: LARGE_INTEGER = std::mem::zeroed();
if QueryPerformanceCounter(&mut current_time) == 0 {
panic!("QueryPerformanceCounter failed");
}
let mut time_delta = (current_time.QuadPart() - self.qpc_last_time.QuadPart()) as u64;
self.qpc_last_time = current_time;
self.qpc_second_counter += time_delta;
// Clamp excessively large time deltas (e.g. after paused in the debugger).
if time_delta > self.qpc_max_delta {
time_delta = self.qpc_max_delta;
}
// Convert QPC units into a canonical tick format. This cannot overflow due to the previous clamp.
time_delta *= TICKS_PER_SECOND;
time_delta /= *self.qpc_frequency.QuadPart() as u64;
let last_frame_count = self.frame_count;
if self.is_fixed_timestep {
// Fixed timestep update logic
// If the app is running very close to the target elapsed time (within 1/4 of a millisecond) just clamp
// the clock to exactly match the target value. This prevents tiny and irrelevant errors
// from accumulating over time. Without this clamping, a game that requested a 60 fps
// fixed update, running with vsync enabled on a 59.94 NTSC display, would eventually
// accumulate enough tiny errors that it would drop a frame. It is better to just round
// small deviations down to zero to leave things running smoothly.
if (time_delta - self.target_elapsed_ticks) < TICKS_PER_SECOND / 4000 {
time_delta = self.target_elapsed_ticks;
}
self.leftover_ticks += time_delta;
while self.leftover_ticks >= self.target_elapsed_ticks {
self.elapsed_ticks = self.target_elapsed_ticks;
self.total_ticks += self.target_elapsed_ticks;
self.leftover_ticks -= self.target_elapsed_ticks;
self.frame_count += 1;
update_func(self);
}
} else {
// Variable timestep update logic.
self.elapsed_ticks = time_delta;
self.total_ticks += time_delta;
self.leftover_ticks = 0;
self.frame_count += 1;
update_func(self);
}
// Track the current framerate
if self.frame_count != last_frame_count {
self.frames_this_second += 1;
}
if self.qpc_second_counter >= *self.qpc_frequency.QuadPart() as u64 {
self.frames_per_second = self.frames_this_second;
self.frames_this_second = 0;
self.qpc_second_counter %= *self.qpc_frequency.QuadPart() as u64;
}
}
}
pub fn reset_elapsed_time(&mut self) {
unsafe {
if QueryPerformanceCounter(&mut self.qpc_last_time) == 0 {
panic!("QueryPerformanceCounter failed");
}
}
self.leftover_ticks = 0;
self.frames_per_second = 0;
self.frames_this_second = 0;
self.qpc_second_counter = 0;
}
pub fn get_elapsed_ticks(&self) -> u64 {
self.elapsed_ticks
}
pub fn get_elapsed_seconds(&self) -> f64 {
//directly ported but probably doesn't need to be associated fn
Self::ticks_to_seconds(self.elapsed_ticks)
}
pub fn get_total_ticks(&self) -> u64 {
self.total_ticks
}
pub fn get_total_seconds(&self) -> f64 {
Self::ticks_to_seconds(self.total_ticks)
}
pub fn get_frame_count(&self) -> u32 {
self.frame_count
}
pub fn get_frames_per_second(&self) -> u32 {
self.frames_per_second
}
pub fn set_fixed_time_step(&mut self, is_fixed_timestep: bool) {
self.is_fixed_timestep = is_fixed_timestep;
}
pub fn set_target_elapsed_ticks(&mut self, target_elapsed: u64) {
self.target_elapsed_ticks = target_elapsed;
}
pub fn set_target_elapsed_seconds(&mut self, target_elapsed_s: f64) {
self.target_elapsed_ticks = Self::seconds_to_ticks(target_elapsed_s)
}
pub fn ticks_to_seconds(ticks: u64) -> f64 {
ticks as f64 / TICKS_PER_SECOND as f64
}
pub fn seconds_to_ticks(seconds: f64) -> u64 {
seconds as u64 * TICKS_PER_SECOND
}
}
|
use chrono::NaiveDateTime;
use diesel::prelude::*;
use diesel::pg::PgConnection;
use schema::horus_videos;
use models::traits::passwordable;
#[derive(AsChangeset, Queryable, Serialize, Identifiable, Insertable)]
#[table_name = "horus_videos"]
pub struct HVideo
{
pub id: String,
pub title: Option<String>,
pub owner: i32,
pub filepath: String,
pub date_added: NaiveDateTime,
pub is_expiry: bool,
pub expiration_time: Option<NaiveDateTime>,
pub password: Option<String>
}
impl passwordable::Passwordable for HVideo {
fn set_password(&mut self, password: Option<String>, conn: &PgConnection) -> Option<String>
{
use diesel::SaveChangesDsl;
self.password = passwordable::retrieve_hashed(password);
let result = self.save_changes::<HVideo>(conn);
match result {
Ok(_) => None,
Err(e) => Some(format!("{}", e))
}
}
fn get_hashed_password(&self, conn: &PgConnection) -> Option<String>
{
use schema::horus_videos::dsl::*;
horus_videos.find(&self.id).select(password).get_result::<Option<String>>(conn).unwrap()
}
fn get_s3_location(&self) -> String
{
self.filepath.clone()
}
fn owner(&self) -> i32
{
self.owner
}
}
|
use anyhow::Result;
use isahc::prelude::*;
use openssl::hash::MessageDigest;
use openssl::pkey::PKey;
use openssl::rsa::Rsa;
use openssl::sign::Signer;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
const BASE: &str = "https://api.bunq.com";
#[derive(Serialize)]
struct Installation<'a> {
client_public_key: &'a str,
}
#[derive(Deserialize)]
struct Token {
token: String,
}
#[derive(Deserialize)]
#[serde(rename_all = "PascalCase")]
struct InstallationResponse {
token: Token,
}
#[derive(Serialize)]
struct DeviceServer<'a> {
description: &'a str,
secret: &'a str,
permitted_ips: &'a [&'a str],
}
#[derive(Serialize)]
struct SessionServer<'a> {
secret: &'a str,
}
#[derive(Deserialize)]
#[serde(rename_all = "PascalCase")]
struct SessionServerResponse {
token: Token,
user_person: UserPerson,
}
#[derive(Deserialize)]
struct UserPerson {
id: i64,
}
fn sign<K: openssl::pkey::HasPrivate>(body: &str, key: &PKey<K>) -> Result<String> {
let mut signer = Signer::new(MessageDigest::sha256(), key)?;
let sig = signer.sign_oneshot_to_vec(body.as_bytes())?;
Ok(base64::encode(&sig))
}
#[derive(Deserialize)]
#[serde(rename_all = "PascalCase")]
struct RawResponse {
response: Vec<serde_json::Value>,
pagination: Option<Pagination>,
}
struct Response<T> {
response: T,
pagination: Option<Pagination>,
}
impl RawResponse {
fn decode_retarded<T: DeserializeOwned>(self) -> Result<Response<T>> {
let mut map = serde_json::Map::new();
for e in self.response {
if let serde_json::Value::Object(e) = e {
let (k, v) = e
.into_iter()
.next()
.ok_or_else(|| anyhow::anyhow!("malformed response"))?;
map.insert(k, v);
}
}
Ok(Response {
response: serde_json::from_value(map.into())?,
pagination: self.pagination,
})
}
}
fn deserialize_retarded_response<T: DeserializeOwned>(r: &str) -> Result<Response<T>> {
let r: RawResponse = serde_json::from_str(r)?;
r.decode_retarded()
}
fn deserialize_normal_response<T: DeserializeOwned>(r: &str) -> Result<Response<T>> {
let r: RawResponse = serde_json::from_str(r)?;
Ok(Response {
response: serde_json::from_value(r.response.into())?,
pagination: r.pagination,
})
}
#[derive(Serialize, Deserialize, Default)]
struct AppState {
token: String,
pem_private: String,
}
#[derive(Serialize, Deserialize, Default)]
pub struct BunqConfig {
api_key: String,
state: Option<AppState>,
}
pub struct BunqConfigReady {
token: String,
keypair: PKey<openssl::pkey::Private>,
user_id: i64,
}
impl BunqConfig {
pub fn load() -> Result<BunqConfig> {
Ok(confy::load("bunq-rs")?)
}
pub fn save(&self) -> Result<()> {
confy::store("bunq-rs", self)?;
Ok(())
}
pub fn install(mut self) -> Result<BunqConfigReady> {
let api_key = &self.api_key;
let keypair = if let Some(state) = &self.state {
PKey::private_key_from_pem(state.pem_private.as_bytes())?
} else {
let rsa = Rsa::generate(2048)?;
let pem_private = rsa.private_key_to_pem()?;
let pem_private = String::from_utf8(pem_private)?;
let keypair = PKey::from_rsa(rsa)?;
let pem_public = String::from_utf8(keypair.public_key_to_pem()?)?;
let body = Installation {
client_public_key: &pem_public,
};
let response = isahc::post(
format!("{}/v1/installation", BASE),
serde_json::to_string(&body)?,
)?
.text()?;
let response: InstallationResponse = deserialize_retarded_response(&response)?.response;
let token = response.token.token;
let body = DeviceServer {
description: "awesome",
secret: &api_key,
permitted_ips: &["31.21.118.143", "*"],
};
let body = serde_json::to_string(&body)?;
let mut response = isahc::http::Request::post(format!("{}/v1/device-server", BASE))
.header("X-Bunq-Client-Authentication", &token)
.body(body)?
.send()?;
println!("{}", response.text()?);
self.state = Some(AppState { pem_private, token });
self.save()?;
keypair
};
let token = self.state.unwrap().token;
let body = SessionServer { secret: &api_key };
let body = serde_json::to_string(&body)?;
let sig = sign(&body, &keypair)?;
let response = isahc::http::Request::post(format!("{}/v1/session-server", BASE))
.header("X-Bunq-Client-Authentication", &token)
.header("X-Bunq-Client-Signature", &sig)
.body(body)?
.send()?
.text()?;
let r: SessionServerResponse = deserialize_retarded_response(&response)?.response;
Ok(BunqConfigReady {
keypair,
token: r.token.token,
user_id: r.user_person.id,
})
}
}
impl BunqConfigReady {
pub fn monetary_accounts(&self) -> Result<Vec<MonetaryAccountBank>> {
let response = isahc::http::Request::get(format!(
"{}/v1/user/{}/monetary-account",
BASE, self.user_id
))
.header("X-Bunq-Client-Authentication", &self.token)
.body(())?
.send()?
.text()?;
Ok(
deserialize_normal_response::<Vec<MonetaryAccount>>(&response)?
.response
.into_iter()
.map(|m| m.monetary_account_bank)
.collect(),
)
}
pub fn payments(&self, acc: &MonetaryAccountBank) -> Result<Vec<Payment>> {
self.payments_from_to(acc, None, None)
}
pub fn payments_from_to(
&self,
acc: &MonetaryAccountBank,
from: Option<i64>,
to: Option<i64>,
) -> Result<Vec<Payment>> {
let next_page = |url: &str| -> Result<(_, _)> {
let response = isahc::http::Request::get(url)
.header("X-Bunq-Client-Authentication", &self.token)
.body(())?
.send()?
.text()?;
let Response {
response,
pagination,
} = deserialize_normal_response::<Vec<PaymentPayment>>(&response)?;
Ok((
response.into_iter().map(|p| p.payment).collect(),
pagination,
))
};
let mut url = format!(
"/v1/user/{}/monetary-account/{}/payment",
self.user_id, acc.id
);
if let Some(to) = to {
url = format!("{}?newer_id={}", url, to);
}
let mut all = Vec::new();
loop {
let (mut payments, pag) = next_page(&format!("{}{}", BASE, url))?;
all.append(&mut payments);
dbg!(&pag);
if let Some(Pagination {
older_url: Some(older_url),
..
}) = pag
{
if let (Some(latest), Some(from)) = (all.last(), from) {
if latest.id <= from {
all = all.into_iter().filter(|p| p.id >= from).collect();
break;
}
}
url = older_url;
} else {
break;
}
}
Ok(all)
}
}
#[derive(Deserialize, Debug)]
pub struct LabelMonetaryAccount {
pub iban: Option<String>,
pub display_name: String,
pub merchant_category_code: Option<String>,
}
#[derive(Deserialize, Debug)]
pub struct Amount {
pub value: String,
pub currency: String,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
struct PaymentPayment {
payment: Payment,
}
#[derive(Deserialize, Debug)]
struct Pagination {
future_url: Option<String>,
newer_url: Option<String>,
older_url: Option<String>,
}
#[derive(Deserialize, Debug)]
pub struct Payment {
pub alias: LabelMonetaryAccount,
pub counterparty_alias: LabelMonetaryAccount,
pub amount: Amount,
pub balance_after_mutation: Amount,
pub created: String,
pub updated: String,
pub description: String,
pub id: i64,
pub monetary_account_id: i64,
#[serde(rename = "type")]
pub type_: String,
pub sub_type: String,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
struct MonetaryAccount {
monetary_account_bank: MonetaryAccountBank,
}
#[derive(Deserialize, Debug)]
pub struct MonetaryAccountBank {
pub id: i64,
pub description: String,
}
|
use swf_tree as ast;
use nom::IResult;
use nom::{be_f32 as parse_be_f32, be_u16 as parse_be_u16, be_u32 as parse_be_u32, le_u8 as parse_u8, le_u32 as parse_le_u32};
use ordered_float::OrderedFloat;
use parsers::avm1::parse_actions_block;
use parsers::basic_data_types::{parse_le_fixed8_p8, parse_le_fixed16_p16, parse_straight_s_rgba8};
#[allow(unused_variables)]
pub fn parse_blend_mode(input: &[u8]) -> IResult<&[u8], ast::BlendMode> {
switch!(input, parse_u8,
0 => value!(ast::BlendMode::Normal) |
1 => value!(ast::BlendMode::Normal) |
2 => value!(ast::BlendMode::Layer) |
3 => value!(ast::BlendMode::Multiply) |
4 => value!(ast::BlendMode::Screen) |
5 => value!(ast::BlendMode::Lighten) |
6 => value!(ast::BlendMode::Darken) |
7 => value!(ast::BlendMode::Difference) |
8 => value!(ast::BlendMode::Add) |
9 => value!(ast::BlendMode::Subtract) |
10 => value!(ast::BlendMode::Invert) |
11 => value!(ast::BlendMode::Alpha) |
12 => value!(ast::BlendMode::Erase) |
13 => value!(ast::BlendMode::Overlay) |
14 => value!(ast::BlendMode::Hardlight)
// TODO(demurgos): Error on unexpected value
)
}
pub fn parse_clip_actions_string(input: &[u8], extended_events: bool) -> IResult<&[u8], Vec<ast::ClipAction>> {
let mut result: Vec<ast::ClipAction> = Vec::new();
let mut current_input = input;
loop {
let head = if extended_events {
parse_be_u32(current_input)
} else {
map!(current_input, parse_be_u16, |x| x as u32)
};
match head {
IResult::Done(next_input, event_flags) => {
if event_flags == 0 {
current_input = next_input;
break;
}
}
IResult::Error(e) => return IResult::Error(e),
IResult::Incomplete(n) => return IResult::Incomplete(n),
};
match parse_clip_actions(current_input, extended_events) {
IResult::Done(next_input, clip_actions) => {
result.push(clip_actions);
current_input = next_input;
}
IResult::Error(e) => return IResult::Error(e),
IResult::Incomplete(n) => return IResult::Incomplete(n),
};
}
IResult::Done(current_input, result)
}
#[allow(unused_variables)]
pub fn parse_clip_event_flags(input: &[u8], extended_events: bool) -> IResult<&[u8], ast::ClipEventFlags> {
do_parse!(
input,
flags: switch!(value!(extended_events),
true => call!(parse_be_u32) |
false => map!(parse_be_u16, |x| (x as u32) << 16)
) >>
(ast::ClipEventFlags {
key_up: (flags & (1 << 31)) != 0,
key_down: (flags & (1 << 30)) != 0,
mouse_up: (flags & (1 << 29)) != 0,
mouse_down: (flags & (1 << 28)) != 0,
mouse_move: (flags & (1 << 27)) != 0,
unload: (flags & (1 << 26)) != 0,
enter_frame: (flags & (1 << 25)) != 0,
load: (flags & (1 << 24)) != 0,
drag_over: (flags & (1 << 23)) != 0,
roll_out: (flags & (1 << 22)) != 0,
roll_over: (flags & (1 << 21)) != 0,
release_outside: (flags & (1 << 20)) != 0,
release: (flags & (1 << 19)) != 0,
press: (flags & (1 << 18)) != 0,
initialize: (flags & (1 << 17)) != 0,
data: (flags & (1 << 16)) != 0,
construct: (flags & (1 << 10)) != 0,
key_press: (flags & (1 << 9)) != 0,
drag_out: (flags & (1 << 8)) != 0,
})
)
}
pub fn parse_clip_actions(input: &[u8], extended_events: bool) -> IResult<&[u8], ast::ClipAction> {
do_parse!(
input,
events: apply!(parse_clip_event_flags, extended_events) >>
actions_size: map!(parse_le_u32, |x| if events.key_press && x > 0 { x - 1 } else { x } as usize) >>
key_code: cond!(events.key_press, parse_u8) >>
actions: apply!(parse_actions_block, actions_size) >>
(ast::ClipAction {
events: events,
key_code: key_code,
actions: actions,
})
)
}
pub fn parse_filter_list(input: &[u8]) -> IResult<&[u8], Vec<ast::Filter>> {
length_count!(input, parse_u8, parse_filter)
}
#[allow(unused_variables)]
pub fn parse_filter(input: &[u8]) -> IResult<&[u8], ast::Filter> {
switch!(input, parse_u8,
0 => map!(parse_drop_shadow_filter, |f| ast::Filter::DropShadow(f)) |
1 => map!(parse_blur_filter, |f| ast::Filter::Blur(f)) |
2 => map!(parse_glow_filter, |f| ast::Filter::Glow(f)) |
3 => map!(parse_bevel_filter, |f| ast::Filter::Bevel(f)) |
4 => map!(parse_gradient_glow_filter, |f| ast::Filter::GradientGlow(f)) |
5 => map!(parse_convolution_filter, |f| ast::Filter::Convolution(f)) |
6 => map!(parse_color_matrix_filter, |f| ast::Filter::ColorMatrix(f)) |
7 => map!(parse_gradient_bevel_filter, |f| ast::Filter::GradientBevel(f))
// TODO(demurgos): Error on unexpected value
)
}
pub fn parse_bevel_filter(input: &[u8]) -> IResult<&[u8], ast::filters::Bevel> {
do_parse!(
input,
shadow_color: parse_straight_s_rgba8 >>
highlight_color: parse_straight_s_rgba8 >>
blur_x: parse_le_fixed16_p16 >>
blur_y: parse_le_fixed16_p16 >>
angle: parse_le_fixed16_p16 >>
distance: parse_le_fixed16_p16 >>
strength: parse_le_fixed8_p8 >>
flags: parse_u8 >>
inner: value!((flags & (1 << 7)) != 0) >>
knockout: value!((flags & (1 << 6)) != 0) >>
composite_source: value!((flags & (1 << 5)) != 0) >>
on_top: value!((flags & (1 << 4)) != 0) >>
passes: value!(flags & ((1 << 4) - 1)) >>
(ast::filters::Bevel {
shadow_color: shadow_color,
highlight_color: highlight_color,
blur_x: blur_x,
blur_y: blur_y,
angle: angle,
distance: distance,
strength: strength,
inner: inner,
knockout: knockout,
composite_source: composite_source,
on_top: on_top,
passes: passes,
})
)
}
pub fn parse_blur_filter(input: &[u8]) -> IResult<&[u8], ast::filters::Blur> {
do_parse!(
input,
blur_x: parse_le_fixed16_p16 >>
blur_y: parse_le_fixed16_p16 >>
flags: parse_u8 >>
passes: value!(flags >> 3) >>
(ast::filters::Blur {
blur_x: blur_x,
blur_y: blur_y,
passes: passes,
})
)
}
pub fn parse_color_matrix_filter(input: &[u8]) -> IResult<&[u8], ast::filters::ColorMatrix> {
do_parse!(
input,
matrix: length_count!(value!(20), map!(parse_be_f32, |x| OrderedFloat::<f32>(x))) >>
(ast::filters::ColorMatrix {
matrix: matrix,
})
)
}
pub fn parse_convolution_filter(input: &[u8]) -> IResult<&[u8], ast::filters::Convolution> {
do_parse!(
input,
matrix_width: map!(parse_u8, |x| x as usize) >>
matrix_height: map!(parse_u8, |x| x as usize) >>
divisor: map!(parse_be_f32, |x| OrderedFloat::<f32>(x)) >>
bias: map!(parse_be_f32, |x| OrderedFloat::<f32>(x)) >>
matrix: length_count!(value!(matrix_width * matrix_height), map!(parse_be_f32, |x| OrderedFloat::<f32>(x))) >>
default_color: parse_straight_s_rgba8 >>
flags: parse_u8 >>
clamp: value!((flags & (1 << 1)) != 0) >>
preserve_alpha: value!((flags & (1 << 0)) != 0) >>
(ast::filters::Convolution {
matrix_width: matrix_width,
matrix_height: matrix_height,
divisor: divisor,
bias: bias,
matrix: matrix,
default_color: default_color,
clamp: clamp,
preserve_alpha: preserve_alpha,
})
)
}
pub fn parse_drop_shadow_filter(input: &[u8]) -> IResult<&[u8], ast::filters::DropShadow> {
do_parse!(
input,
color: parse_straight_s_rgba8 >>
blur_x: parse_le_fixed16_p16 >>
blur_y: parse_le_fixed16_p16 >>
angle: parse_le_fixed16_p16 >>
distance: parse_le_fixed16_p16 >>
strength: parse_le_fixed8_p8 >>
flags: parse_u8 >>
inner: value!((flags & (1 << 7)) != 0) >>
knockout: value!((flags & (1 << 6)) != 0) >>
composite_source: value!((flags & (1 << 5)) != 0) >>
passes: value!(flags & ((1 << 5) - 1)) >>
(ast::filters::DropShadow {
color: color,
blur_x: blur_x,
blur_y: blur_y,
angle: angle,
distance: distance,
strength: strength,
inner: inner,
knockout: knockout,
composite_source: composite_source,
passes: passes,
})
)
}
pub fn parse_glow_filter(input: &[u8]) -> IResult<&[u8], ast::filters::Glow> {
do_parse!(
input,
color: parse_straight_s_rgba8 >>
blur_x: parse_le_fixed16_p16 >>
blur_y: parse_le_fixed16_p16 >>
strength: parse_le_fixed8_p8 >>
flags: parse_u8 >>
inner: value!((flags & (1 << 7)) != 0) >>
knockout: value!((flags & (1 << 6)) != 0) >>
composite_source: value!((flags & (1 << 5)) != 0) >>
passes: value!(flags & ((1 << 5) - 1)) >>
(ast::filters::Glow {
color: color,
blur_x: blur_x,
blur_y: blur_y,
strength: strength,
inner: inner,
knockout: knockout,
composite_source: composite_source,
passes: passes,
})
)
}
fn parse_filter_gradient(input: &[u8], color_count: usize) -> IResult<&[u8], Vec<ast::ColorStop>> {
let mut result: Vec<ast::ColorStop> = Vec::with_capacity(color_count);
let mut current_input = input;
for _ in 0..color_count {
match parse_straight_s_rgba8(current_input) {
IResult::Done(next_input, color) => {
result.push(ast::ColorStop { ratio: 0, color: color });
current_input = next_input;
}
IResult::Error(e) => return IResult::Error(e),
IResult::Incomplete(n) => return IResult::Incomplete(n),
};
}
for mut color_stop in &mut result {
match parse_u8(current_input) {
IResult::Done(next_input, ratio) => {
color_stop.ratio = ratio;
current_input = next_input;
}
IResult::Error(e) => return IResult::Error(e),
IResult::Incomplete(n) => return IResult::Incomplete(n),
};
}
IResult::Done(current_input, result)
}
pub fn parse_gradient_bevel_filter(input: &[u8]) -> IResult<&[u8], ast::filters::GradientBevel> {
do_parse!(
input,
color_count: map!(parse_u8, |x| x as usize) >>
gradient: apply!(parse_filter_gradient, color_count) >>
blur_x: parse_le_fixed16_p16 >>
blur_y: parse_le_fixed16_p16 >>
angle: parse_le_fixed16_p16 >>
distance: parse_le_fixed16_p16 >>
strength: parse_le_fixed8_p8 >>
flags: parse_u8 >>
inner: value!((flags & (1 << 7)) != 0) >>
knockout: value!((flags & (1 << 6)) != 0) >>
composite_source: value!((flags & (1 << 5)) != 0) >>
on_top: value!((flags & (1 << 4)) != 0) >>
passes: value!(flags & ((1 << 4) - 1)) >>
(ast::filters::GradientBevel {
gradient: gradient,
blur_x: blur_x,
blur_y: blur_y,
angle: angle,
distance: distance,
strength: strength,
inner: inner,
knockout: knockout,
composite_source: composite_source,
on_top: on_top,
passes: passes,
})
)
}
pub fn parse_gradient_glow_filter(input: &[u8]) -> IResult<&[u8], ast::filters::GradientGlow> {
do_parse!(
input,
color_count: map!(parse_u8, |x| x as usize) >>
gradient: apply!(parse_filter_gradient, color_count) >>
blur_x: parse_le_fixed16_p16 >>
blur_y: parse_le_fixed16_p16 >>
angle: parse_le_fixed16_p16 >>
distance: parse_le_fixed16_p16 >>
strength: parse_le_fixed8_p8 >>
flags: parse_u8 >>
inner: value!((flags & (1 << 7)) != 0) >>
knockout: value!((flags & (1 << 6)) != 0) >>
composite_source: value!((flags & (1 << 5)) != 0) >>
on_top: value!((flags & (1 << 4)) != 0) >>
passes: value!(flags & ((1 << 4) - 1)) >>
(ast::filters::GradientGlow {
gradient: gradient,
blur_x: blur_x,
blur_y: blur_y,
angle: angle,
distance: distance,
strength: strength,
inner: inner,
knockout: knockout,
composite_source: composite_source,
on_top: on_top,
passes: passes,
})
)
}
|
use serenity::model::interactions::ApplicationCommandInteractionData;
pub fn extract_option(data: &ApplicationCommandInteractionData, key: &str) -> Option<String> {
let opt = data
.options
.iter()
.find(|&opt| opt.name == key)
.map(|v| v.value.clone());
if let Some(Some(arg)) = opt {
use serde_json::Value::*;
let v = match arg {
String(s) => s,
Null => "".to_string(),
Bool(b) => {
if b {
"true".to_string()
} else {
"false".to_string()
}
}
Number(n) => {
format!("{}", n)
}
v => v.to_string(),
};
Some(v)
} else {
None
}
}
|
//! # Vectors
//! This crate takes in some form of a vector and outputs all related data that is required.
//! We'll try to implement it in the terminal for now but porting it over to the web shouldn't be that hard.
//! Need to learn some basic wasm + svelte for that though.
//!
//! ## Process
//! Takes in vector
//!
//! ## Returns
//! Magnitude
//! Unit vector
//! Initial and terminating point
//!
//! ## Allows for
//! Adding and subracting vectors
//! Multiplying vectors with constants
//! Multiplying vectors with vectors
// use std::env;
use vectors::Config;
fn main() {
// The three forms of a vector are
// `V = < V_x, V_y >`
// First get user input
let input = Config::new(&env::args());
}
|
#[doc = "Register `DMACCARxBR` reader"]
pub type R = crate::R<DMACCARX_BR_SPEC>;
#[doc = "Field `CURRBUFAPTR` reader - Application Receive Buffer Address Pointer"]
pub type CURRBUFAPTR_R = crate::FieldReader<u32>;
impl R {
#[doc = "Bits 0:31 - Application Receive Buffer Address Pointer"]
#[inline(always)]
pub fn currbufaptr(&self) -> CURRBUFAPTR_R {
CURRBUFAPTR_R::new(self.bits)
}
}
#[doc = "Channel current application receive buffer register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`dmaccarx_br::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct DMACCARX_BR_SPEC;
impl crate::RegisterSpec for DMACCARX_BR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`dmaccarx_br::R`](R) reader structure"]
impl crate::Readable for DMACCARX_BR_SPEC {}
#[doc = "`reset()` method sets DMACCARxBR to value 0"]
impl crate::Resettable for DMACCARX_BR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use opendp::err;
use crate::core::{FfiDomain, FfiMeasure, FfiMeasureGlue, FfiMeasurement, FfiResult, FfiTransformation};
use crate::util;
use crate::util::Type;
use opendp::chain::{make_chain_mt_glue, make_chain_tt_glue, make_composition_glue};
#[no_mangle]
pub extern "C" fn opendp_core__make_chain_mt(measurement1: *const FfiMeasurement, transformation0: *const FfiTransformation) -> FfiResult<*mut FfiMeasurement> {
let transformation0 = try_as_ref!(transformation0);
let measurement1 = try_as_ref!(measurement1);
let FfiTransformation {
input_glue: input_glue0,
output_glue: output_glue0,
value: value0
} = transformation0;
let FfiMeasurement {
input_glue: input_glue1,
output_glue: output_glue1,
value: value1
} = measurement1;
if output_glue0.domain_type != input_glue1.domain_type {
return err!(DomainMismatch, "chained domain types do not match").into();
}
let measurement = try_!(make_chain_mt_glue(
value1, value0, None,
&input_glue0.metric_glue,
&output_glue0.metric_glue,
&output_glue1.measure_glue));
FfiResult::Ok(util::into_raw(
FfiMeasurement::new(input_glue0.clone(), output_glue1.clone(), measurement)))
}
#[no_mangle]
pub extern "C" fn opendp_core__make_chain_tt(transformation1: *const FfiTransformation, transformation0: *const FfiTransformation) -> FfiResult<*mut FfiTransformation> {
let transformation0 = try_as_ref!(transformation0);
let transformation1 = try_as_ref!(transformation1);
let FfiTransformation {
input_glue: input_glue0,
output_glue: output_glue0,
value: value0
} = transformation0;
let FfiTransformation {
input_glue: input_glue1,
output_glue: output_glue1,
value: value1
} = transformation1;
if output_glue0.domain_type != input_glue1.domain_type {
return err!(DomainMismatch, "chained domain types do not match").into();
}
let transformation = try_!(make_chain_tt_glue(
value1,
value0,
None,
&input_glue0.metric_glue,
&output_glue0.metric_glue,
&output_glue1.metric_glue));
FfiResult::Ok(util::into_raw(
FfiTransformation::new(input_glue0.clone(), output_glue1.clone(), transformation)))
}
#[no_mangle]
pub extern "C" fn opendp_core__make_composition(measurement0: *const FfiMeasurement, measurement1: *const FfiMeasurement) -> FfiResult<*mut FfiMeasurement> {
let measurement0 = try_as_ref!(measurement0);
let measurement1 = try_as_ref!(measurement1);
let FfiMeasurement {
input_glue: input_glue0,
output_glue: output_glue0,
value: value0
} = measurement0;
let FfiMeasurement {
input_glue: input_glue1,
output_glue: output_glue1,
value: value1
} = measurement1;
if input_glue0.domain_type != input_glue1.domain_type {
return err!(DomainMismatch, "chained domain types do not match").into();
}
let measurement = try_!(make_composition_glue(
value0, value1,
&input_glue0.metric_glue,
&output_glue0.measure_glue,
&output_glue1.measure_glue));
// TODO: output_glue for composition.
let output_glue_domain_type = Type::of::<FfiDomain>();
let output_glue_domain_carrier = Type::new_box_pair(&output_glue0.domain_carrier, &output_glue1.domain_carrier);
let output_glue_measure_glue = output_glue0.measure_glue.clone();
let output_glue = FfiMeasureGlue::<FfiDomain, FfiMeasure>::new_explicit(output_glue_domain_type, output_glue_domain_carrier, output_glue_measure_glue);
FfiResult::Ok(util::into_raw(
FfiMeasurement::new(input_glue0.clone(), output_glue, measurement)))
} |
use std::error::Error;
type Result<T> = ::std::result::Result<T, Box<dyn Error>>;
macro_rules! err {
($($tt:tt)*) => { return Err(Box::<dyn Error>::from(format!($($tt)*))) }
}
pub struct IntCodeVm {
pub state: StateVm,
pub ram: Vec<isize>,
pub current_position: usize,
pub relative_position: isize,
}
impl IntCodeVm {
pub fn new(input: &str) -> Result<Self> {
let mut steps: Vec<isize> = vec![];
for step in input.trim().split(',') {
steps.push(step.parse()?);
}
Ok(Self {
state: StateVm::Initial,
ram: steps,
current_position: 0,
relative_position: 0,
})
}
pub fn set_ram(&mut self, position: usize, value: isize) {
self.ram[position] = value;
}
pub fn run(&mut self, mut input: Option<isize>) -> Result<Option<isize>> {
self.state = StateVm::Initial;
loop {
if self.ram.len() <= self.current_position {
err!("Current step outside boundaries of input steps!");
}
let (opcode, access_mode_1, access_mode_2, access_mode_3) = self.parse_instruction()?;
self.current_position += match opcode {
OpCode::Addition => {
let first_param = self.get_parameter(1, access_mode_1)?;
let second_param = self.get_parameter(2, access_mode_2)?;
self.set_parameter(3, access_mode_3, first_param + second_param)?;
4
}
OpCode::Multiplication => {
let first_param = self.get_parameter(1, access_mode_1)?;
let second_param = self.get_parameter(2, access_mode_2)?;
self.set_parameter(3, access_mode_3, first_param * second_param)?;
4
}
OpCode::Input => {
match input.take() {
Some(input) => {
self.set_parameter(1, access_mode_1, input)?;
}
None => {
self.state = StateVm::WaitingInstruction;
return Ok(None);
}
}
2
}
OpCode::Output => {
let first_param = self.get_parameter(1, access_mode_1)?;
self.current_position += 2;
self.state = StateVm::Output;
return Ok(Some(first_param));
}
OpCode::JumpIfTrue => {
let first_param = self.get_parameter(1, access_mode_1)?;
let second_param = self.get_parameter(2, access_mode_2)?;
if first_param != 0 {
self.current_position = second_param as usize;
0
} else {
3
}
}
OpCode::JumpIfFalse => {
let first_param = self.get_parameter(1, access_mode_1)?;
let second_param = self.get_parameter(2, access_mode_2)?;
if first_param == 0 {
self.current_position = second_param as usize;
0
} else {
3
}
}
OpCode::LessThan => {
let first_param = self.get_parameter(1, access_mode_1)?;
let second_param = self.get_parameter(2, access_mode_2)?;
self.set_parameter(
3,
access_mode_3,
if first_param < second_param { 1 } else { 0 },
)?;
4
}
OpCode::Equals => {
let first_param = self.get_parameter(1, access_mode_1)?;
let second_param = self.get_parameter(2, access_mode_2)?;
self.set_parameter(
3,
access_mode_3,
if first_param == second_param { 1 } else { 0 },
)?;
4
}
OpCode::AdjustsRelativeBase => {
let first_param = self.get_parameter(1, access_mode_1)?;
self.relative_position += first_param;
2
}
OpCode::EndsProgram => {
self.state = StateVm::Ended;
return Ok(None);
}
};
}
}
fn get_parameter(&mut self, position: usize, access_mode: AccessMode) -> Result<isize> {
self.check_memory((self.current_position + position) as isize)?;
let param: isize;
let current_val = self.ram[self.current_position + position];
match access_mode {
AccessMode::Position => {
self.check_memory(current_val)?;
param = self.ram[current_val as usize];
}
AccessMode::Immediate => {
param = current_val;
}
AccessMode::Relative => {
self.check_memory(current_val + self.relative_position)?;
param = self.ram[(current_val + self.relative_position) as usize];
}
}
Ok(param)
}
fn set_parameter(
&mut self,
position: usize,
access_mode: AccessMode,
value: isize,
) -> Result<()> {
self.check_memory((self.current_position + position) as isize)?;
let current_val = self.ram[self.current_position + position];
match access_mode {
AccessMode::Position => {
self.check_memory(current_val)?;
self.ram[current_val as usize] = value;
}
AccessMode::Immediate => {
err!("Setting parameter in immediate mode is not allowed!");
}
AccessMode::Relative => {
self.check_memory(current_val + self.relative_position)?;
self.ram[(current_val + self.relative_position) as usize] = value;
}
}
Ok(())
}
fn check_memory(&mut self, position: isize) -> Result<()> {
if position < 0 {
err!("Positional parameter should not be less than zero!");
}
if self.ram.len() <= position as usize {
for _ in 0..=(position as usize - self.ram.len()) {
self.ram.push(0);
}
}
Ok(())
}
fn parse_instruction(&self) -> Result<(OpCode, AccessMode, AccessMode, AccessMode)> {
let instruction = format!("{:05}", self.ram[self.current_position]);
let vec_code = instruction.chars().collect::<Vec<char>>();
let opcode = OpCode::from_int(self.ram[self.current_position] % 100)?;
let mode_1 = AccessMode::from_char(vec_code[2])?;
let mode_2 = AccessMode::from_char(vec_code[1])?;
let mode_3 = AccessMode::from_char(vec_code[0])?;
Ok((opcode, mode_1, mode_2, mode_3))
}
}
pub enum StateVm {
Initial,
WaitingInstruction,
Output,
Ended,
}
enum AccessMode {
Position,
Immediate,
Relative,
}
impl AccessMode {
fn from_char(c: char) -> Result<Self> {
match c {
'0' => Ok(AccessMode::Position),
'1' => Ok(AccessMode::Immediate),
'2' => Ok(AccessMode::Relative),
_ => err!("Not a valid access mode character : {}", c),
}
}
}
enum OpCode {
Addition,
Multiplication,
Input,
Output,
JumpIfTrue,
JumpIfFalse,
LessThan,
Equals,
AdjustsRelativeBase,
EndsProgram,
}
impl OpCode {
fn from_int(n: isize) -> Result<OpCode> {
match n {
1 => Ok(OpCode::Addition),
2 => Ok(OpCode::Multiplication),
3 => Ok(OpCode::Input),
4 => Ok(OpCode::Output),
5 => Ok(OpCode::JumpIfTrue),
6 => Ok(OpCode::JumpIfFalse),
7 => Ok(OpCode::LessThan),
8 => Ok(OpCode::Equals),
9 => Ok(OpCode::AdjustsRelativeBase),
99 => Ok(OpCode::EndsProgram),
_ => err!("Not a valid opcode : {}", n),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn parse_input_to_steps(input: &str) -> Vec<isize> {
let mut steps = vec![];
for step in input.trim().split(',') {
steps.push(step.parse().unwrap());
}
steps
}
#[test]
fn test_1() {
let input = "109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99";
let mut intcode_vm = IntCodeVm::new(input).unwrap();
let mut result: Vec<isize> = vec![];
let expected_result = parse_input_to_steps(input);
loop {
match intcode_vm.run(None).unwrap() {
Some(x) => {
result.push(x);
}
None => match intcode_vm.state {
StateVm::Ended => break,
_ => unreachable!("Other states should not be reachable during this test!"),
},
}
}
assert_eq!(result, expected_result, "Copy of itself");
}
#[test]
fn test_2() {
let input = "1102,34915192,34915192,7,4,7,99,0";
let mut intcode_vm = IntCodeVm::new(input).unwrap();
let mut result: Vec<isize> = vec![];
loop {
match intcode_vm.run(None).unwrap() {
Some(x) => {
result.push(x);
}
None => match intcode_vm.state {
StateVm::Ended => break,
_ => unreachable!("Other states should not be reachable during this test!"),
},
}
}
assert_eq!(result, vec![34915192 * 34915192], "16 digit number");
}
#[test]
fn test_3() {
let input = "104,1125899906842624,99";
let mut intcode_vm = IntCodeVm::new(input).unwrap();
let mut result: Vec<isize> = vec![];
loop {
match intcode_vm.run(None).unwrap() {
Some(x) => {
result.push(x);
}
None => match intcode_vm.state {
StateVm::Ended => break,
_ => unreachable!("Other states should not be reachable during this test!"),
},
}
}
assert_eq!(result, vec![1125899906842624], "Large number");
}
}
|
#![cfg(feature = "llvm-10-or-greater")]
//! These tests simply ensure that we can parse all of the `.bc` files in LLVM 10's `test/Bitcode` directory without crashing.
//! We only include the `.bc` files which are new or have changed since LLVM 9 (older ones are covered in llvm_9_tests.rs or llvm_8_tests.rs).
//! Human-readable `.ll` versions of these files can be found in the LLVM repo at `test/Bitcode` at the git tag `llvmorg-10.0.1`.
use llvm_ir::Module;
use std::path::Path;
macro_rules! llvm_test {
($path:expr, $func:ident) => {
#[test]
#[allow(non_snake_case)]
fn $func() {
let _ = env_logger::builder().is_test(true).try_init(); // capture log messages with test harness
let path = Path::new($path);
let _ = Module::from_bc_path(&path).expect("Failed to parse module");
}
};
}
llvm_test!(
"tests/llvm_bc/aarch64-addp-upgrade.bc",
aarch64_addp_upgrade
);
//llvm_test!("tests/llvm_bc/invalid-functionptr-align.ll.bc", invalid_functionptr_align); // we omit this .bc file because it is intentionally invalid
//llvm_test!("tests/llvm_bc/invalid-type-for-null-constant.ll.bc", invalid_type_for_null_constant); // we omit this .bc file because it is intentionally invalid
llvm_test!(
"tests/llvm_bc/upgrade-arc-runtime-calls-bitcast.bc",
upgrade_arc_runtime_calls_bitcast
);
llvm_test!(
"tests/llvm_bc/upgrade-arc-runtime-calls-new.bc",
upgrade_arc_runtime_calls_new
);
llvm_test!(
"tests/llvm_bc/upgrade-arc-runtime-calls.bc",
upgrade_arc_runtime_calls
);
llvm_test!(
"tests/llvm_bc/upgrade-mrr-runtime-calls.bc",
upgrade_mrr_runtime_calls
);
// also ensure that new-to-llvm-10 constructs -- specifically, freeze
// instructions, AtomicRMWBinOps, and the `weak` field on CmpXchg -- were parsed
// correctly
use llvm_ir::instruction::RMWBinOp;
use llvm_ir::{instruction, Constant, ConstantRef, Name, Operand};
use std::convert::TryInto;
/// LLVM 10 added the Freeze instruction; ensure that that was parsed correctly
#[test]
fn freeze() {
let _ = env_logger::builder().is_test(true).try_init(); // capture log messages with test harness
let path = Path::new("tests/llvm_bc/compatibility.ll.bc");
let module = Module::from_bc_path(&path).expect("Failed to parse module");
let func = module
.get_func_by_name("instructions.other")
.expect("Failed to find function");
let bb = func
.get_bb_by_name(&Name::from("exit"))
.expect("Failed to find exit bb");
let freeze: &instruction::Freeze = &bb.instrs[6]
.clone()
.try_into()
.unwrap_or_else(|_| panic!("Expected a freeze, got {:?}", &bb.instrs[6]));
assert_eq!(
freeze.operand,
Operand::LocalOperand {
name: Name::from("op1"),
ty: module.types.i32()
}
);
assert_eq!(freeze.dest, Name::from(31));
assert_eq!(&format!("{}", freeze), "%31 = freeze i32 %op1");
let freeze: &instruction::Freeze = &bb.instrs[7]
.clone()
.try_into()
.unwrap_or_else(|_| panic!("Expected a freeze, got {:?}", &bb.instrs[7]));
assert_eq!(
freeze.operand,
Operand::ConstantOperand(ConstantRef::new(Constant::Int {
bits: 32,
value: 10
}))
);
assert_eq!(freeze.dest, Name::from(32));
assert_eq!(&format!("{}", freeze), "%32 = freeze i32 10");
let freeze: &instruction::Freeze = &bb.instrs[9]
.clone()
.try_into()
.unwrap_or_else(|_| panic!("Expected a freeze, got {:?}", &bb.instrs[9]));
#[cfg(feature = "llvm-11-or-greater")]
assert_eq!(
freeze.operand,
Operand::LocalOperand {
name: Name::from("vop"),
ty: module.types.vector_of(module.types.i32(), 2, false),
}
);
#[cfg(feature = "llvm-10-or-lower")]
assert_eq!(
freeze.operand,
Operand::LocalOperand {
name: Name::from("vop"),
ty: module.types.vector_of(module.types.i32(), 2),
}
);
assert_eq!(freeze.dest, Name::from(34));
assert_eq!(&format!("{}", freeze), "%34 = freeze <2 x i32> %vop");
}
/// LLVM 10 added the ability to get the AtomicRMW operation to the C API, so we test that functionality
#[test]
fn atomicrmw_binops() {
let _ = env_logger::builder().is_test(true).try_init(); // capture log messages with test harness
let path = Path::new("tests/llvm_bc/compatibility.ll.bc");
let module = Module::from_bc_path(&path).expect("Failed to parse module");
let func = module
.get_func_by_name("atomics")
.expect("Failed to find function");
let bb = &func.basic_blocks[0];
let atomic_xchg: &instruction::AtomicRMW = &bb.instrs[8]
.clone()
.try_into()
.unwrap_or_else(|_| panic!("Expected an AtomicRMW, got {:?}", &bb.instrs[8]));
assert_eq!(atomic_xchg.operation, RMWBinOp::Xchg);
let atomic_add: &instruction::AtomicRMW = &bb.instrs[9]
.clone()
.try_into()
.unwrap_or_else(|_| panic!("Expected an AtomicRMW, got {:?}", &bb.instrs[9]));
assert_eq!(atomic_add.operation, RMWBinOp::Add);
let atomic_sub: &instruction::AtomicRMW = &bb.instrs[10]
.clone()
.try_into()
.unwrap_or_else(|_| panic!("Expected an AtomicRMW, got {:?}", &bb.instrs[10]));
assert_eq!(atomic_sub.operation, RMWBinOp::Sub);
let atomic_and: &instruction::AtomicRMW = &bb.instrs[11]
.clone()
.try_into()
.unwrap_or_else(|_| panic!("Expected an AtomicRMW, got {:?}", &bb.instrs[11]));
assert_eq!(atomic_and.operation, RMWBinOp::And);
let atomic_nand: &instruction::AtomicRMW = &bb.instrs[12]
.clone()
.try_into()
.unwrap_or_else(|_| panic!("Expected an AtomicRMW, got {:?}", &bb.instrs[12]));
assert_eq!(atomic_nand.operation, RMWBinOp::Nand);
let atomic_or: &instruction::AtomicRMW = &bb.instrs[13]
.clone()
.try_into()
.unwrap_or_else(|_| panic!("Expected an AtomicRMW, got {:?}", &bb.instrs[13]));
assert_eq!(atomic_or.operation, RMWBinOp::Or);
let atomic_xor: &instruction::AtomicRMW = &bb.instrs[14]
.clone()
.try_into()
.unwrap_or_else(|_| panic!("Expected an AtomicRMW, got {:?}", &bb.instrs[14]));
assert_eq!(atomic_xor.operation, RMWBinOp::Xor);
let atomic_max: &instruction::AtomicRMW = &bb.instrs[15]
.clone()
.try_into()
.unwrap_or_else(|_| panic!("Expected an AtomicRMW, got {:?}", &bb.instrs[15]));
assert_eq!(atomic_max.operation, RMWBinOp::Max);
let atomic_min: &instruction::AtomicRMW = &bb.instrs[16]
.clone()
.try_into()
.unwrap_or_else(|_| panic!("Expected an AtomicRMW, got {:?}", &bb.instrs[16]));
assert_eq!(atomic_min.operation, RMWBinOp::Min);
let atomic_umax: &instruction::AtomicRMW = &bb.instrs[17]
.clone()
.try_into()
.unwrap_or_else(|_| panic!("Expected an AtomicRMW, got {:?}", &bb.instrs[17]));
assert_eq!(atomic_umax.operation, RMWBinOp::UMax);
let atomic_umin: &instruction::AtomicRMW = &bb.instrs[18]
.clone()
.try_into()
.unwrap_or_else(|_| panic!("Expected an AtomicRMW, got {:?}", &bb.instrs[18]));
assert_eq!(atomic_umin.operation, RMWBinOp::UMin);
let func = module
.get_func_by_name("fp_atomics")
.expect("Failed to find function");
let bb = &func.basic_blocks[0];
let atomic_xchg: &instruction::AtomicRMW = &bb.instrs[0]
.clone()
.try_into()
.unwrap_or_else(|_| panic!("Expected an AtomicRMW, got {:?}", &bb.instrs[0]));
assert_eq!(atomic_xchg.operation, RMWBinOp::Xchg);
let atomic_fadd: &instruction::AtomicRMW = &bb.instrs[1]
.clone()
.try_into()
.unwrap_or_else(|_| panic!("Expected an AtomicRMW, got {:?}", &bb.instrs[1]));
assert_eq!(atomic_fadd.operation, RMWBinOp::FAdd);
let atomic_fsub: &instruction::AtomicRMW = &bb.instrs[2]
.clone()
.try_into()
.unwrap_or_else(|_| panic!("Expected an AtomicRMW, got {:?}", &bb.instrs[2]));
assert_eq!(atomic_fsub.operation, RMWBinOp::FSub);
}
/// LLVM 10 added the ability to get the `weak` option for CmpXchg through the C API, so we test that functionality
#[test]
fn weak_cmpxchg() {
let _ = env_logger::builder().is_test(true).try_init(); // capture log messages with test harness
let path = Path::new("tests/llvm_bc/compatibility.ll.bc");
let module = Module::from_bc_path(&path).expect("Failed to parse module");
let func = module
.get_func_by_name("atomics")
.expect("Failed to find function");
let bb = &func.basic_blocks[0];
let cmpxchg_notweak: &instruction::CmpXchg = &bb.instrs[0]
.clone()
.try_into()
.unwrap_or_else(|_| panic!("Expected a CmpXchg, got {:?}", &bb.instrs[0]));
assert_eq!(cmpxchg_notweak.weak, false);
let cmpxchg_notweak: &instruction::CmpXchg = &bb.instrs[1]
.clone()
.try_into()
.unwrap_or_else(|_| panic!("Expected a CmpXchg, got {:?}", &bb.instrs[1]));
assert_eq!(cmpxchg_notweak.weak, false);
let cmpxchg_weak: &instruction::CmpXchg = &bb.instrs[5]
.clone()
.try_into()
.unwrap_or_else(|_| panic!("Expected a CmpXchg, got {:?}", &bb.instrs[5]));
assert_eq!(cmpxchg_weak.weak, true);
let cmpxchg_weak: &instruction::CmpXchg = &bb.instrs[7]
.clone()
.try_into()
.unwrap_or_else(|_| panic!("Expected a CmpXchg, got {:?}", &bb.instrs[7]));
assert_eq!(cmpxchg_weak.weak, true);
}
|
$NetBSD: patch-compiler_rustc__target_src_spec_netbsd__base.rs,v 1.7 2023/01/23 18:49:04 he Exp $
For the benefit of powerpc, when libatomic-links is installed,
search the directory containing the symlinks to -latomic.
--- compiler/rustc_target/src/spec/netbsd_base.rs.orig 2022-12-12 16:02:12.000000000 +0000
+++ compiler/rustc_target/src/spec/netbsd_base.rs
@@ -1,12 +1,20 @@
-use crate::spec::{cvs, RelroLevel, TargetOptions};
+use crate::spec::{cvs, Cc, Lld, RelroLevel, LinkerFlavor, TargetOptions};
pub fn opts() -> TargetOptions {
+ let pre_link_args = TargetOptions::link_args(
+ LinkerFlavor::Gnu(Cc::Yes, Lld::No),
+ &[
+ // For the benefit of powerpc, when libatomic-links is installed,
+ "-Wl,-L@PREFIX@/lib/libatomic".into(),
+ ],
+ );
TargetOptions {
os: "netbsd".into(),
dynamic_linking: true,
families: cvs!["unix"],
no_default_libraries: false,
has_rpath: true,
+ pre_link_args,
position_independent_executables: true,
relro_level: RelroLevel::Full,
use_ctors_section: true,
|
use clap::{App, Arg};
use rawpb_core::parse_to_pretty;
use std::io::{Read, Write};
type IoResult<T> = Result<T, std::io::Error>;
enum InputFormatType {
Binary,
HexString,
Base64,
}
impl InputFormatType {
pub fn new(fmt: &str) -> Self {
if fmt == "h" {
Self::HexString
} else if fmt == "B" {
Self::Base64
} else {
Self::Binary
}
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let matches = App::new("Protobuf data")
.version("1.0")
.author("Taoism<xietao1233@outlook.com>")
.about("Parse protobuf data")
.arg(
Arg::with_name("output_file")
.short("o")
.long("output")
.value_name("FILE")
.help("Sets a output file")
.takes_value(true),
)
.arg(
Arg::with_name("input_file")
.short("i")
.long("input")
.value_name("FILE")
.help("Sets a input file")
.takes_value(true),
)
.arg(
Arg::with_name("format_string")
.short("f")
.long("format")
.value_name("FORMAT_STRING")
.help("\"b\" is binary, \"h\" is hex string, \'B\" is base64 string.")
.takes_value(true),
)
.arg(
Arg::with_name("who_is_first")
.short("w")
.long("first")
.value_name("WHO_IS_FIRST")
.help("\"s\" is String, \"o\" is Object. \"String\" and \"Object\", which is first")
.takes_value(true),
)
.get_matches();
let input_file = matches.value_of("input_file").unwrap_or("");
let output_file = matches.value_of("output_file").unwrap_or("");
let input_fmt = matches.value_of("format_string").unwrap_or("b");
let wif = matches.value_of("who_is_first").unwrap_or("s");
match (
std::fs::File::open(std::path::Path::new(input_file)),
std::fs::File::create(std::path::Path::new(output_file)),
) {
(Ok(ref mut f), Ok(ref mut of)) => {
parse_data(f, of, InputFormatType::new(input_fmt), wif == "o")?;
}
(Ok(ref mut f), Err(_)) => {
// println!("output file error: {:?}, 已重定向到stdout.", err);
let mut of = std::io::stdout();
parse_data(f, &mut of, InputFormatType::new(input_fmt), wif == "o")?;
}
(Err(_), Ok(ref mut of)) => {
// println!("input file error: {:?}, 已重定向到stdin.", err);
let mut f = std::io::stdin();
parse_data(&mut f, of, InputFormatType::new(input_fmt), wif == "o")?;
}
_ => {
// println!("no input file.");
let mut f = std::io::stdin();
let mut of = std::io::stdout();
parse_data(&mut f, &mut of, InputFormatType::new(input_fmt), wif == "o")?;
}
}
Ok(())
}
fn parse_data(
f: &mut impl Read,
of: &mut impl Write,
fmt: InputFormatType,
sif: bool,
) -> IoResult<()> {
let mut data = Vec::new();
f.read_to_end(&mut data)?;
let _data = match fmt {
InputFormatType::HexString => {
// 去除末尾的回车键字符
data.pop();
hex::decode(data).expect("输入的hex字符串格式错误!")
}
InputFormatType::Base64 => {
// 去除末尾的回车键字符
data.pop();
base64::decode(data).expect("输入的base64格式错误!")
}
_ => data,
};
match parse_to_pretty(_data.as_ref(), sif) {
Ok(d) => {
of.write_all(d.as_bytes())?;
}
Err(err) => {
panic!("解析pb错误: {:?}", err)
}
}
Ok(())
}
|
pub fn exist(board: Vec<Vec<char>>, word: String) -> bool {
let m = board.len();
if m == 0 {
return false;
}
let n = board[0].len();
let mut marked = vec![vec![false; n]; m];
let directions = vec![
(-1, 0), // 上
(0, 1), // 右
(1, 0), // 下
(0, -1), // 左
];
for i in 0..m {
for j in 0..n {
if match_word(
&board,
m,
n,
word.as_bytes(),
0,
i,
j,
&mut marked,
&directions,
) {
return true;
}
}
}
false
}
fn match_word(
board: &Vec<Vec<char>>,
m: usize,
n: usize,
word: &[u8],
word_idx: usize,
board_x: usize,
board_y: usize,
marked: &mut Vec<Vec<bool>>,
directions: &Vec<(isize, isize)>,
) -> bool {
if board[board_x][board_y] as u8 != word[word_idx] {
return false;
}
if word_idx == word.len() - 1 {
// 匹配完了
return true;
}
marked[board_x][board_y] = true;
// 当前匹配上了,再匹配下一个,可选的是相邻的四个位置
for (dx, dy) in directions {
let (x, y) = (board_x as isize + *dx, board_y as isize + *dy);
if 0 <= x && x < m as isize && 0 <= y && y < n as isize {
let (x, y) = (x as usize, y as usize);
if !marked[x][y]
&& match_word(board, m, n, word, word_idx + 1, x, y, marked, directions)
{
return true;
}
}
}
// 四个方向都没有匹配的上,退回到上一步
marked[board_x][board_y] = false;
false
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_exist() {
let board = vec![
vec!['A', 'B', 'C', 'E'],
vec!['S', 'F', 'C', 'S'],
vec!['A', 'D', 'E', 'E'],
];
assert_eq!(exist(board.clone(), "ABCCED".to_owned()), true);
assert_eq!(exist(board.clone(), "SEE".to_owned()), true);
assert_eq!(exist(board.clone(), "ABCB".to_owned()), false);
}
}
|
extern crate libc;
extern crate rctl;
#[cfg(feature = "serialize")]
extern crate serde_json;
#[cfg(feature = "serialize")]
fn main() {
let uid = unsafe { libc::getuid() };
let subject = rctl::Subject::user_id(uid);
let serialized = serde_json::to_string(&subject).expect("Could not serialize RCTL subject.");
println!("{}", serialized);
}
#[cfg(not(feature = "serialize"))]
fn main() {
println!("Run `cargo build --features=serialize` to enable this example");
}
|
#[doc = "Reader of register DDRCTRL_DRAMTMG1"]
pub type R = crate::R<u32, super::DDRCTRL_DRAMTMG1>;
#[doc = "Writer for register DDRCTRL_DRAMTMG1"]
pub type W = crate::W<u32, super::DDRCTRL_DRAMTMG1>;
#[doc = "Register DDRCTRL_DRAMTMG1 `reset()`'s with value 0x0008_0414"]
impl crate::ResetValue for super::DDRCTRL_DRAMTMG1 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0x0008_0414
}
}
#[doc = "Reader of field `T_RC`"]
pub type T_RC_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `T_RC`"]
pub struct T_RC_W<'a> {
w: &'a mut W,
}
impl<'a> T_RC_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 & !0x7f) | ((value as u32) & 0x7f);
self.w
}
}
#[doc = "Reader of field `RD2PRE`"]
pub type RD2PRE_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `RD2PRE`"]
pub struct RD2PRE_W<'a> {
w: &'a mut W,
}
impl<'a> RD2PRE_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 & !(0x3f << 8)) | (((value as u32) & 0x3f) << 8);
self.w
}
}
#[doc = "Reader of field `T_XP`"]
pub type T_XP_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `T_XP`"]
pub struct T_XP_W<'a> {
w: &'a mut W,
}
impl<'a> T_XP_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x1f << 16)) | (((value as u32) & 0x1f) << 16);
self.w
}
}
impl R {
#[doc = "Bits 0:6 - T_RC"]
#[inline(always)]
pub fn t_rc(&self) -> T_RC_R {
T_RC_R::new((self.bits & 0x7f) as u8)
}
#[doc = "Bits 8:13 - RD2PRE"]
#[inline(always)]
pub fn rd2pre(&self) -> RD2PRE_R {
RD2PRE_R::new(((self.bits >> 8) & 0x3f) as u8)
}
#[doc = "Bits 16:20 - T_XP"]
#[inline(always)]
pub fn t_xp(&self) -> T_XP_R {
T_XP_R::new(((self.bits >> 16) & 0x1f) as u8)
}
}
impl W {
#[doc = "Bits 0:6 - T_RC"]
#[inline(always)]
pub fn t_rc(&mut self) -> T_RC_W {
T_RC_W { w: self }
}
#[doc = "Bits 8:13 - RD2PRE"]
#[inline(always)]
pub fn rd2pre(&mut self) -> RD2PRE_W {
RD2PRE_W { w: self }
}
#[doc = "Bits 16:20 - T_XP"]
#[inline(always)]
pub fn t_xp(&mut self) -> T_XP_W {
T_XP_W { w: self }
}
}
|
use std::time::{Duration, Instant};
use backoff::{backoff::Backoff, Clock, SystemClock};
/// A [`Backoff`] wrapper that resets after a fixed duration has elapsed.
pub struct ResetTimerBackoff<B, C = SystemClock> {
backoff: B,
clock: C,
last_backoff: Option<Instant>,
reset_duration: Duration,
}
impl<B: Backoff> ResetTimerBackoff<B> {
pub fn new(backoff: B, reset_duration: Duration) -> Self {
Self::new_with_custom_clock(backoff, reset_duration, SystemClock {})
}
}
impl<B: Backoff, C: Clock> ResetTimerBackoff<B, C> {
fn new_with_custom_clock(backoff: B, reset_duration: Duration, clock: C) -> Self {
Self {
backoff,
clock,
last_backoff: None,
reset_duration,
}
}
}
impl<B: Backoff, C: Clock> Backoff for ResetTimerBackoff<B, C> {
fn next_backoff(&mut self) -> Option<Duration> {
if let Some(last_backoff) = self.last_backoff {
if self.clock.now() > last_backoff + self.reset_duration {
tracing::debug!(
?last_backoff,
reset_duration = ?self.reset_duration,
"Resetting backoff, since reset duration has expired"
);
self.backoff.reset();
}
}
self.last_backoff = Some(self.clock.now());
self.backoff.next_backoff()
}
fn reset(&mut self) {
// Do not even bother trying to reset here, since `next_backoff` will take care of this when the timer expires.
}
}
#[cfg(test)]
mod tests {
use backoff::{backoff::Backoff, Clock};
use tokio::time::advance;
use super::ResetTimerBackoff;
use crate::utils::stream_backoff::tests::LinearBackoff;
use std::time::{Duration, Instant};
#[tokio::test]
async fn should_reset_when_timer_expires() {
tokio::time::pause();
let mut backoff = ResetTimerBackoff::new_with_custom_clock(
LinearBackoff::new(Duration::from_secs(2)),
Duration::from_secs(60),
TokioClock,
);
assert_eq!(backoff.next_backoff(), Some(Duration::from_secs(2)));
advance(Duration::from_secs(40)).await;
assert_eq!(backoff.next_backoff(), Some(Duration::from_secs(4)));
advance(Duration::from_secs(40)).await;
assert_eq!(backoff.next_backoff(), Some(Duration::from_secs(6)));
advance(Duration::from_secs(80)).await;
assert_eq!(backoff.next_backoff(), Some(Duration::from_secs(2)));
advance(Duration::from_secs(80)).await;
assert_eq!(backoff.next_backoff(), Some(Duration::from_secs(2)));
}
struct TokioClock;
impl Clock for TokioClock {
fn now(&self) -> Instant {
tokio::time::Instant::now().into_std()
}
}
}
|
use std::sync::Arc;
use async_trait::async_trait;
use common::error::Error;
use common::result::Result;
use identity::domain::user::{UserId, UserRepository};
use publishing::domain::author::{Author, AuthorId, AuthorRepository};
use publishing::domain::publication::PublicationRepository;
pub struct AuthorTranslator {
publication_repo: Arc<dyn PublicationRepository>,
user_repo: Arc<dyn UserRepository>,
}
impl AuthorTranslator {
pub fn new(
publication_repo: Arc<dyn PublicationRepository>,
user_repo: Arc<dyn UserRepository>,
) -> Self {
AuthorTranslator {
publication_repo,
user_repo,
}
}
}
#[async_trait]
impl AuthorRepository for AuthorTranslator {
async fn next_id(&self) -> Result<AuthorId> {
let user_id = self.user_repo.next_id().await?;
Ok(AuthorId::new(user_id.value())?)
}
async fn find_all(&self) -> Result<Vec<Author>> {
let users = self.user_repo.find_all().await?;
let users = users.iter().filter(|user| user.person().is_some());
let mut authors = Vec::new();
for user in users {
let author_id = AuthorId::new(user.base().id().value())?;
authors.push(Author::new(
author_id,
user.identity().username().value(),
user.person().unwrap().fullname().name(),
user.person().unwrap().fullname().lastname(),
)?)
}
Ok(authors)
}
async fn find_by_id(&self, id: &AuthorId) -> Result<Author> {
let user = self.user_repo.find_by_id(&UserId::new(id.value())?).await?;
let author_id = AuthorId::new(user.base().id().value())?;
if user.person().is_none() {
return Err(Error::new("author", "does_not_have_a_name"));
}
Ok(Author::new(
author_id,
user.identity().username().value(),
user.person().unwrap().fullname().name(),
user.person().unwrap().fullname().lastname(),
)?)
}
async fn search(&self, _text: &str) -> Result<Vec<Author>> {
Ok(Vec::new())
}
async fn save(&self, _author: &mut Author) -> Result<()> {
Ok(())
}
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - GPIO port mode register"]
pub moder: MODER,
#[doc = "0x04 - GPIO port output type register"]
pub otyper: OTYPER,
#[doc = "0x08 - GPIO port output speed register"]
pub ospeedr: OSPEEDR,
#[doc = "0x0c - GPIO port pull-up/pull-down register"]
pub pupdr: PUPDR,
#[doc = "0x10 - GPIO port input data register"]
pub idr: IDR,
#[doc = "0x14 - GPIO port output data register"]
pub odr: ODR,
#[doc = "0x18 - GPIO port bit set/reset register"]
pub bsrr: BSRR,
#[doc = "0x1c - GPIO port configuration lock register"]
pub lckr: LCKR,
#[doc = "0x20 - GPIO alternate function low register"]
pub afrl: AFRL,
#[doc = "0x24 - GPIO alternate function high register"]
pub afrh: AFRH,
}
#[doc = "MODER (rw) register accessor: GPIO port mode register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`moder::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 [`moder::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`moder`]
module"]
pub type MODER = crate::Reg<moder::MODER_SPEC>;
#[doc = "GPIO port mode register"]
pub mod moder;
#[doc = "OTYPER (rw) register accessor: GPIO port output type register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`otyper::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 [`otyper::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`otyper`]
module"]
pub type OTYPER = crate::Reg<otyper::OTYPER_SPEC>;
#[doc = "GPIO port output type register"]
pub mod otyper;
#[doc = "OSPEEDR (rw) register accessor: GPIO port output speed register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ospeedr::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 [`ospeedr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ospeedr`]
module"]
pub type OSPEEDR = crate::Reg<ospeedr::OSPEEDR_SPEC>;
#[doc = "GPIO port output speed register"]
pub mod ospeedr;
#[doc = "PUPDR (rw) register accessor: GPIO port pull-up/pull-down register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`pupdr::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 [`pupdr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`pupdr`]
module"]
pub type PUPDR = crate::Reg<pupdr::PUPDR_SPEC>;
#[doc = "GPIO port pull-up/pull-down register"]
pub mod pupdr;
#[doc = "IDR (r) register accessor: GPIO port input data register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`idr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`idr`]
module"]
pub type IDR = crate::Reg<idr::IDR_SPEC>;
#[doc = "GPIO port input data register"]
pub mod idr;
#[doc = "ODR (rw) register accessor: GPIO port output data register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`odr::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 [`odr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`odr`]
module"]
pub type ODR = crate::Reg<odr::ODR_SPEC>;
#[doc = "GPIO port output data register"]
pub mod odr;
#[doc = "BSRR (w) register accessor: GPIO port bit set/reset register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`bsrr::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`bsrr`]
module"]
pub type BSRR = crate::Reg<bsrr::BSRR_SPEC>;
#[doc = "GPIO port bit set/reset register"]
pub mod bsrr;
#[doc = "LCKR (rw) register accessor: GPIO port configuration lock register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`lckr::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 [`lckr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`lckr`]
module"]
pub type LCKR = crate::Reg<lckr::LCKR_SPEC>;
#[doc = "GPIO port configuration lock register"]
pub mod lckr;
#[doc = "AFRL (rw) register accessor: GPIO alternate function low register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`afrl::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 [`afrl::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`afrl`]
module"]
pub type AFRL = crate::Reg<afrl::AFRL_SPEC>;
#[doc = "GPIO alternate function low register"]
pub mod afrl;
#[doc = "AFRH (rw) register accessor: GPIO alternate function high register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`afrh::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 [`afrh::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`afrh`]
module"]
pub type AFRH = crate::Reg<afrh::AFRH_SPEC>;
#[doc = "GPIO alternate function high register"]
pub mod afrh;
|
#![deny(missing_docs)]
//! A 3D game engine with built-in editor.
#[macro_use]
extern crate bitflags;
extern crate camera_controllers;
extern crate gfx;
extern crate gfx_debug_draw;
extern crate gfx_device_gl;
extern crate gfx_text;
extern crate piston_meta;
extern crate piston_window;
extern crate sdl2_window;
extern crate vecmath;
#[macro_use]
extern crate log;
extern crate range;
#[macro_use]
extern crate conrod;
extern crate find_folder;
pub use math::Mat4;
pub use math::Ray;
pub use math::Vec3;
pub use math::AABB;
pub use world::World;
pub mod data;
pub mod logger;
pub mod math;
pub mod render;
pub mod world;
widget_ids! {
#[allow(missing_docs)]
pub struct Ids {
refresh,
}
}
/// Starts Turbine pointing it to a project folder.
pub fn start(project_folder: &str) {
use camera_controllers::*;
use piston_window::*;
use sdl2_window::Sdl2Window;
// use conrod::{ Ui, Theme };
// use gfx_debug_draw::DebugRenderer;
use crate::math::Matrix;
println!(
"
~~~~~~~~ TURBINE ~~~~~~~~\n\
=============================\n\
Camera navigation (on/off): C\n\
Camera control: WASD\n\
"
);
let mut window: PistonWindow<Sdl2Window> = WindowSettings::new("Turbine", [1024, 768])
.exit_on_esc(true)
.samples(4)
.build()
.unwrap();
logger::init().unwrap();
let mut capture_cursor = true;
window.set_capture_cursor(capture_cursor);
let fov = 90.0;
let near = 0.1;
let far = 1000.0;
let get_projection = |draw_size: Size| {
CameraPerspective {
fov,
near_clip: near,
far_clip: far,
aspect_ratio: (draw_size.width as f32) / (draw_size.height as f32),
}
.projection()
};
let mut projection = get_projection(window.draw_size());
let mut first_person = FirstPerson::new([0.5, 0.5, 4.0], FirstPersonSettings::keyboard_wasd());
// TODO: Update debug renderer.
/*
let mut debug_renderer = {
let text_renderer =
gfx_text::new(window.factory.borrow().clone()).unwrap();
DebugRenderer::new(window.factory.borrow().clone(),
text_renderer, 64).ok().unwrap()
};
*/
let mut cursor_pos = [0.0, 0.0];
let mut ground_pos = [0.0, 0.0, 0.0];
let mut ortho = false;
// TODO: Update Conrod.
/*
let mut ui = {
let assets = find_folder::Search::ParentsThenKids(3, 3)
.for_folder("assets").unwrap();
let font_path = assets.join("fonts/NotoSans/NotoSans-Regular.ttf");
let mut theme = Theme::default();
theme.font_size_medium = 12;
let glyph_cache = Glyphs::new(&font_path, window.factory.borrow().clone());
Ui::new(glyph_cache.unwrap(), theme)
};
*/
let mut world = World::new();
{
// Create folders if they do not exists.
data::create_folders(project_folder).unwrap();
// Load entities.
let files = data::entities::files(project_folder).unwrap();
data::entities::load(&mut world, &files).unwrap();
}
while let Some(e) = window.next() {
if capture_cursor {
first_person.event(&e);
}
window.draw_3d(&e, |window| {
let draw_size = window.draw_size();
let draw_size = [draw_size.width, draw_size.height];
let args = e.render_args().unwrap();
let camera = first_person.camera(args.ext_dt);
let mvp = model_view_projection(Matrix::id(), camera.orthogonal(), projection);
window
.encoder
.clear(&window.output_color, [0.3, 0.3, 0.3, 1.0]);
window.encoder.clear_depth(&window.output_stencil, 1.0);
window.encoder.clear_stencil(&window.output_stencil, 0);
// TODO: Update debug renderer.
/*
render::entity_current_positions(&world, &mut debug_renderer);
render::axes(&camera, projection, draw_size, &mut debug_renderer);
let yellow = [1.0, 1.0, 0.0, 1.0];
debug_renderer.draw_marker(ground_pos, 0.1, yellow);
debug_renderer.render(stream, mvp).unwrap();
*/
});
if capture_cursor {
// Send render events to make Conrod update window size.
if e.render_args().is_some() {
// TODO: Update Conrod.
// ui.handle_event(&e);
}
} else {
// use conrod::*;
// TODO: Update Conrod.
// ui.handle_event(&e);
/*
e.update(|_| ui.set_widgets(|ui| {
Button::new()
.color(color::BLUE)
.top_left()
.w_h(60.0, 30.0)
.label("refresh")
.react(|| {})
.set(REFRESH, ui);
}));
*/
window.draw_2d(&e, |c, g| {
// TODO: Update Conrod.
// ui.draw(c, g);
});
}
e.resize(|_, _| {
if !ortho {
projection = get_projection(window.draw_size());
}
});
if let Some(pos) = e.mouse_cursor_args() {
cursor_pos = pos;
}
if let Some(Button::Keyboard(Key::C)) = e.press_args() {
capture_cursor = !capture_cursor;
window.set_capture_cursor(capture_cursor);
}
if let Some(Button::Keyboard(Key::O)) = e.press_args() {
ortho = !ortho;
if ortho {
projection = Matrix::id();
} else {
projection = get_projection(window.draw_size());
}
}
if let Some(Button::Mouse(MouseButton::Left)) = e.press_args() {
if !capture_cursor {
let draw_size = window.draw_size();
let draw_size = [draw_size.width, draw_size.height];
let ray = Ray::from_2d(cursor_pos, draw_size, fov, near, far);
let view_to_world = first_person.camera(0.0).orthogonal().inv();
match view_to_world.ray(ray).ground_plane() {
None => info!("Click on the ground to add entity"),
Some(pos) => {
ground_pos = pos;
world.add_entity(pos);
}
}
}
}
}
{
// Save entities data.
let entities_folder = data::entities::folder(project_folder);
data::entities::save(&world, entities_folder).unwrap();
}
}
#[cfg(test)]
pub mod tests {
use super::*;
use piston_meta::*;
#[test]
fn entity_syntax() {
let _ = load_syntax_data("assets/entity/syntax.txt", "assets/entity/test-cube.txt");
}
}
|
use actix_files as fs;
use actix_multipart::Multipart;
use actix_web::{middleware, web, App, Error, HttpResponse, HttpServer};
use futures::{StreamExt, TryStreamExt};
use std::collections::BTreeMap;
use std_logger::request;
use tokio::sync::mpsc;
use futures::executor;
use bytes::BytesMut;
use handlebars::Handlebars;
use image_utils;
async fn handle_multipart_post(mut payload: Multipart) -> Result<HttpResponse, Error> {
let mut handlebars = Handlebars::new();
let mut data = BTreeMap::new();
let image_template = r#"<html>
<head><title>Upload Test</title></head>
<body>
100x100 <p><img src={{image_url_1}}/> <p>
400x400 <p><img src={{image_url_2}}/> <p>
</body>
</html>"#;
match handlebars.register_template_string("result", image_template) {
Ok(res) => {
request!("handle bars registered {:?}", res);
}
Err(reason) => {
request!("handle bars registered {:?}", reason);
}
};
let (send, mut recv) = mpsc::unbounded_channel();
let mut buf = Vec::with_capacity(1024);
while let Ok(Some(mut field)) = payload.try_next().await {
buf.clear();
while let Some(chunk) = field.next().await {
let data = chunk.unwrap();
buf.extend_from_slice(&data);
}
let img = image::load_from_memory(&buf).unwrap();
let send = send.clone();
rayon::spawn(move || {
let thumbnail_task_mem = || -> String {
match image_utils::read_img_mem_resize(&img, 100, 100) {
Ok(res) => res,
rest => rest.unwrap().to_string(),
}
};
let half_task_mem = || -> String {
match image_utils::read_img_mem_resize(&img, 400, 400) {
Ok(res) => res,
rest => rest.unwrap().to_string(),
}
};
let (tk_res, ht_res) = rayon::join(thumbnail_task_mem, half_task_mem);
send.send(("image_url_1".to_string(), tk_res)).unwrap();
send.send(("image_url_2".to_string(), ht_res)).unwrap();
});
}
drop(send);
while let Some((url, res)) = recv.recv().await {
data.insert(url, res);
}
let html = handlebars.render_template(image_template, &data).unwrap();
Ok(HttpResponse::Ok().body(html).into())
}
fn index() -> HttpResponse {
let html = r#"<html>
<head><title>Upload Test</title></head>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" multiple name="file"/>
<input type="submit" value="Submit"></button>
</form>
</body>
</html>"#;
HttpResponse::Ok().body(html)
}
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
std::env::set_var("RUST_LOG", "actix_server=info,actix_web=info");
std_logger::init();
let ip = "0.0.0.0:3000";
request!("Started server {:?}", ip);
HttpServer::new(|| {
App::new()
.wrap(middleware::Logger::default())
.service(
web::resource("/")
.route(web::get().to(index))
.route(web::post().to(handle_multipart_post)),
)
.service(
fs::Files::new("/test-image/", "./test-image")
.show_files_listing()
.use_last_modified(true),
)
})
.bind(ip)?
.run()
.await
}
|
#[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::INTSET {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
#[doc = r" Writes the reset value to the register"]
#[inline]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = r" Value of the field"]
pub struct CQERRR {
bits: bool,
}
impl CQERRR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct CQUPDR {
bits: bool,
}
impl CQUPDR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct CQPAUSEDR {
bits: bool,
}
impl CQPAUSEDR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct DERRR {
bits: bool,
}
impl DERRR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct DCMPR {
bits: bool,
}
impl DCMPR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct ARBR {
bits: bool,
}
impl ARBR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct STOPR {
bits: bool,
}
impl STOPR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct STARTR {
bits: bool,
}
impl STARTR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct ICMDR {
bits: bool,
}
impl ICMDR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct IACCR {
bits: bool,
}
impl IACCR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct NAKR {
bits: bool,
}
impl NAKR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct FOVFLR {
bits: bool,
}
impl FOVFLR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct FUNDFLR {
bits: bool,
}
impl FUNDFLR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct THRR {
bits: bool,
}
impl THRR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct CMDCMPR {
bits: bool,
}
impl CMDCMPR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Proxy"]
pub struct _CQERRW<'a> {
w: &'a mut W,
}
impl<'a> _CQERRW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 14;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _CQUPDW<'a> {
w: &'a mut W,
}
impl<'a> _CQUPDW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 13;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _CQPAUSEDW<'a> {
w: &'a mut W,
}
impl<'a> _CQPAUSEDW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 12;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _DERRW<'a> {
w: &'a mut W,
}
impl<'a> _DERRW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 11;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _DCMPW<'a> {
w: &'a mut W,
}
impl<'a> _DCMPW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 10;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _ARBW<'a> {
w: &'a mut W,
}
impl<'a> _ARBW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 9;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _STOPW<'a> {
w: &'a mut W,
}
impl<'a> _STOPW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 8;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _STARTW<'a> {
w: &'a mut W,
}
impl<'a> _STARTW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 7;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _ICMDW<'a> {
w: &'a mut W,
}
impl<'a> _ICMDW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 6;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _IACCW<'a> {
w: &'a mut W,
}
impl<'a> _IACCW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 5;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _NAKW<'a> {
w: &'a mut W,
}
impl<'a> _NAKW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 4;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FOVFLW<'a> {
w: &'a mut W,
}
impl<'a> _FOVFLW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 3;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FUNDFLW<'a> {
w: &'a mut W,
}
impl<'a> _FUNDFLW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 2;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _THRW<'a> {
w: &'a mut W,
}
impl<'a> _THRW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 1;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _CMDCMPW<'a> {
w: &'a mut W,
}
impl<'a> _CMDCMPW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bit 14 - Error during command queue operations"]
#[inline]
pub fn cqerr(&self) -> CQERRR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 14;
((self.bits >> OFFSET) & MASK as u32) != 0
};
CQERRR { bits }
}
#[doc = "Bit 13 - CQ write operation performed a register write with the register address bit 0 set to 1. The low address bits in the CQ address fields are unused and bit 0 can be used to trigger an interrupt to indicate when this register write is performed by the CQ operation."]
#[inline]
pub fn cqupd(&self) -> CQUPDR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 13;
((self.bits >> OFFSET) & MASK as u32) != 0
};
CQUPDR { bits }
}
#[doc = "Bit 12 - Command queue is paused due to an active event enabled in the PAUSEEN register. The interrupt is posted when the event is enabled within the PAUSEEN register, the mask is active in the CQIRQMASK field and the event occurs."]
#[inline]
pub fn cqpaused(&self) -> CQPAUSEDR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 12;
((self.bits >> OFFSET) & MASK as u32) != 0
};
CQPAUSEDR { bits }
}
#[doc = "Bit 11 - DMA Error encountered during the processing of the DMA command. The DMA error could occur when the memory access specified in the DMA operation is not available or incorrectly specified."]
#[inline]
pub fn derr(&self) -> DERRR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 11;
((self.bits >> OFFSET) & MASK as u32) != 0
};
DERRR { bits }
}
#[doc = "Bit 10 - DMA Complete. Processing of the DMA operation has completed and the DMA submodule is returned into the idle state"]
#[inline]
pub fn dcmp(&self) -> DCMPR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 10;
((self.bits >> OFFSET) & MASK as u32) != 0
};
DCMPR { bits }
}
#[doc = "Bit 9 - Arbitration loss interrupt. Asserted when arbitration is enabled and has been lost to another master on the bus."]
#[inline]
pub fn arb(&self) -> ARBR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 9;
((self.bits >> OFFSET) & MASK as u32) != 0
};
ARBR { bits }
}
#[doc = "Bit 8 - STOP command interrupt. Asserted when another master on the bus has signaled a STOP command."]
#[inline]
pub fn stop(&self) -> STOPR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 8;
((self.bits >> OFFSET) & MASK as u32) != 0
};
STOPR { bits }
}
#[doc = "Bit 7 - START command interrupt. Asserted when another master on the bus has signaled a START command."]
#[inline]
pub fn start(&self) -> STARTR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 7;
((self.bits >> OFFSET) & MASK as u32) != 0
};
STARTR { bits }
}
#[doc = "Bit 6 - illegal command interrupt. Asserted when a command is written when an active command is in progress."]
#[inline]
pub fn icmd(&self) -> ICMDR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 6;
((self.bits >> OFFSET) & MASK as u32) != 0
};
ICMDR { bits }
}
#[doc = "Bit 5 - illegal FIFO access interrupt. Asserted when there is a overflow or underflow event"]
#[inline]
pub fn iacc(&self) -> IACCR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 5;
((self.bits >> OFFSET) & MASK as u32) != 0
};
IACCR { bits }
}
#[doc = "Bit 4 - I2C NAK interrupt. Asserted when an unexpected NAK has been received on the I2C bus."]
#[inline]
pub fn nak(&self) -> NAKR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 4;
((self.bits >> OFFSET) & MASK as u32) != 0
};
NAKR { bits }
}
#[doc = "Bit 3 - Write FIFO Overflow interrupt. This occurs when software tries to write to a full fifo. The current operation does not stop."]
#[inline]
pub fn fovfl(&self) -> FOVFLR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 3;
((self.bits >> OFFSET) & MASK as u32) != 0
};
FOVFLR { bits }
}
#[doc = "Bit 2 - Read FIFO Underflow interrupt. This occurs when software tries to pop from an empty fifo."]
#[inline]
pub fn fundfl(&self) -> FUNDFLR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 2;
((self.bits >> OFFSET) & MASK as u32) != 0
};
FUNDFLR { bits }
}
#[doc = "Bit 1 - FIFO Threshold interrupt. For write operations, asserted when the number of free bytes in the write FIFO equals or exceeds the WTHR field. For read operations, asserted when the number of valid bytes in the read FIFO equals of exceeds the value set in the RTHR field."]
#[inline]
pub fn thr(&self) -> THRR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 1;
((self.bits >> OFFSET) & MASK as u32) != 0
};
THRR { bits }
}
#[doc = "Bit 0 - Command Complete interrupt. Asserted when the current operation has completed. For repeated commands, this will only be asserted when the final repeated command is completed."]
#[inline]
pub fn cmdcmp(&self) -> CMDCMPR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) != 0
};
CMDCMPR { bits }
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 14 - Error during command queue operations"]
#[inline]
pub fn cqerr(&mut self) -> _CQERRW {
_CQERRW { w: self }
}
#[doc = "Bit 13 - CQ write operation performed a register write with the register address bit 0 set to 1. The low address bits in the CQ address fields are unused and bit 0 can be used to trigger an interrupt to indicate when this register write is performed by the CQ operation."]
#[inline]
pub fn cqupd(&mut self) -> _CQUPDW {
_CQUPDW { w: self }
}
#[doc = "Bit 12 - Command queue is paused due to an active event enabled in the PAUSEEN register. The interrupt is posted when the event is enabled within the PAUSEEN register, the mask is active in the CQIRQMASK field and the event occurs."]
#[inline]
pub fn cqpaused(&mut self) -> _CQPAUSEDW {
_CQPAUSEDW { w: self }
}
#[doc = "Bit 11 - DMA Error encountered during the processing of the DMA command. The DMA error could occur when the memory access specified in the DMA operation is not available or incorrectly specified."]
#[inline]
pub fn derr(&mut self) -> _DERRW {
_DERRW { w: self }
}
#[doc = "Bit 10 - DMA Complete. Processing of the DMA operation has completed and the DMA submodule is returned into the idle state"]
#[inline]
pub fn dcmp(&mut self) -> _DCMPW {
_DCMPW { w: self }
}
#[doc = "Bit 9 - Arbitration loss interrupt. Asserted when arbitration is enabled and has been lost to another master on the bus."]
#[inline]
pub fn arb(&mut self) -> _ARBW {
_ARBW { w: self }
}
#[doc = "Bit 8 - STOP command interrupt. Asserted when another master on the bus has signaled a STOP command."]
#[inline]
pub fn stop(&mut self) -> _STOPW {
_STOPW { w: self }
}
#[doc = "Bit 7 - START command interrupt. Asserted when another master on the bus has signaled a START command."]
#[inline]
pub fn start(&mut self) -> _STARTW {
_STARTW { w: self }
}
#[doc = "Bit 6 - illegal command interrupt. Asserted when a command is written when an active command is in progress."]
#[inline]
pub fn icmd(&mut self) -> _ICMDW {
_ICMDW { w: self }
}
#[doc = "Bit 5 - illegal FIFO access interrupt. Asserted when there is a overflow or underflow event"]
#[inline]
pub fn iacc(&mut self) -> _IACCW {
_IACCW { w: self }
}
#[doc = "Bit 4 - I2C NAK interrupt. Asserted when an unexpected NAK has been received on the I2C bus."]
#[inline]
pub fn nak(&mut self) -> _NAKW {
_NAKW { w: self }
}
#[doc = "Bit 3 - Write FIFO Overflow interrupt. This occurs when software tries to write to a full fifo. The current operation does not stop."]
#[inline]
pub fn fovfl(&mut self) -> _FOVFLW {
_FOVFLW { w: self }
}
#[doc = "Bit 2 - Read FIFO Underflow interrupt. This occurs when software tries to pop from an empty fifo."]
#[inline]
pub fn fundfl(&mut self) -> _FUNDFLW {
_FUNDFLW { w: self }
}
#[doc = "Bit 1 - FIFO Threshold interrupt. For write operations, asserted when the number of free bytes in the write FIFO equals or exceeds the WTHR field. For read operations, asserted when the number of valid bytes in the read FIFO equals of exceeds the value set in the RTHR field."]
#[inline]
pub fn thr(&mut self) -> _THRW {
_THRW { w: self }
}
#[doc = "Bit 0 - Command Complete interrupt. Asserted when the current operation has completed. For repeated commands, this will only be asserted when the final repeated command is completed."]
#[inline]
pub fn cmdcmp(&mut self) -> _CMDCMPW {
_CMDCMPW { w: self }
}
}
|
use std::collections::hash_map::DefaultHasher;
use std::hash::Hasher;
fn main() {
//struct Sentence {
// id: u32,
// clause: u64,
//}
//struct Block {
// timestamp: ,
// source_host: ,
// data: ,
// prev_hash: ,
// nonce: ,
//}
let mut hasher = DefaultHasher::new();
hasher.write(b"sv0001");
println!("Hash is {:x}!", hasher.finish());
}
|
use gfx;
use gfx_core;
use gfx_device_gl;
pub type Resources = gfx_device_gl::Resources;
pub type CommandBuffer = gfx_device_gl::CommandBuffer;
pub type Encoder = gfx::Encoder<Resources, CommandBuffer>;
pub type Device = gfx_device_gl::Device;
pub type Factory = gfx_device_gl::Factory;
pub use gfx::format::TextureFormat;
pub type ColorFormat = gfx::format::Srgba8;
pub type NormalFormat = gfx::format::Rgba8;
pub type DepthFormat = (gfx::format::D16, gfx::format::Unorm);
pub type OutputColor = gfx::handle::RenderTargetView<Resources, ColorFormat>;
pub type OutputDepth = gfx::handle::DepthStencilView<Resources, DepthFormat>;
pub type PipelineState<T> = gfx::pso::PipelineState<Resources, T>;
pub type GpuBuffer<T> = gfx::handle::Buffer<Resources, T>;
pub type Texture<T> = gfx::handle::Texture<Resources, T>;
pub type Sampler = gfx::handle::Sampler<Resources>;
pub type ShaderResourceView<T> = gfx::handle::ShaderResourceView<Resources, T>;
pub type TextureView<F: TextureFormat> = ShaderResourceView<F::View>;
pub type RenderTargetView<T> = gfx::handle::RenderTargetView<Resources, T>;
pub type Slice = gfx::Slice<Resources>;
pub type Bundle<T> = gfx::pso::bundle::Bundle<Resources, T>;
pub type GfxRect = gfx_core::target::Rect; |
use silkenweb::{
element_list::OrderedElementList,
elements::{button, div, hr, Button},
mount,
signal::Signal,
Builder,
};
use silkenweb_tutorial_common::define_counter;
// ANCHOR: main
fn main() {
// ANCHOR: new_list
let list = Signal::new(OrderedElementList::new(div()));
// ANCHOR_END: new_list
mount(
"app",
div()
.text("How many counters would you like?")
.child(
div()
.child(pop_button(&list))
// ANCHOR: list_len
.text(list.read().map(|list| format!("{}", list.len())))
// ANCHOR_END: list_len
.child(push_button(&list)),
)
.child(hr())
.child(list.read()),
);
}
// ANCHOR_END: main
// ANCHOR: push_button
fn push_button(list: &Signal<OrderedElementList<usize>>) -> Button {
let push_elem = list.write();
button()
.on_click(move |_, _| {
// ANCHOR: mutate_list
push_elem
.mutate(move |list| list.insert(list.len(), define_counter(&Signal::new(0)).into()))
// ANCHOR_END: mutate_list
})
.text("+")
.build()
}
// ANCHOR_END: push_button
// ANCHOR: pop_button
fn pop_button(list: &Signal<OrderedElementList<usize>>) -> Button {
let pop_elem = list.write();
button()
.on_click(move |_, _| {
pop_elem.mutate(move |list| {
if !list.is_empty() {
list.remove(&(list.len() - 1))
}
})
})
.text("-")
.build()
}
// ANCHOR_END: pop_button
|
use runestick::{ContextError, Module, Panic, Stack, Value, VmError};
use std::cell;
use std::io;
/// Provide a bunch of `std` functions which does something appropriate to the
/// wasm context.
pub fn module() -> Result<Module, ContextError> {
let mut module = Module::new(&["std"]);
module.function(&["print"], print_impl)?;
module.function(&["println"], println_impl)?;
module.raw_fn(&["dbg"], dbg_impl)?;
Ok(module)
}
thread_local!(static OUT: cell::RefCell<io::Cursor<Vec<u8>>> = cell::RefCell::new(io::Cursor::new(Vec::new())));
/// Drain all output that has been written to `OUT`. If `OUT` contains non -
/// UTF-8, will drain but will still return `None`.
pub fn drain_output() -> Option<String> {
OUT.with(|out| {
let mut out = out.borrow_mut();
let out = std::mem::take(&mut *out).into_inner();
String::from_utf8(out).ok()
})
}
fn print_impl(m: &str) -> Result<(), Panic> {
use std::io::Write as _;
OUT.with(|out| {
let mut out = out.borrow_mut();
write!(out, "{}", m).map_err(Panic::custom)
})
}
fn println_impl(m: &str) -> Result<(), Panic> {
use std::io::Write as _;
OUT.with(|out| {
let mut out = out.borrow_mut();
writeln!(out, "{}", m).map_err(Panic::custom)
})
}
fn dbg_impl(stack: &mut Stack, args: usize) -> Result<(), VmError> {
use std::io::Write as _;
OUT.with(|out| {
let mut out = out.borrow_mut();
for value in stack.drain_stack_top(args)? {
writeln!(out, "{:?}", value).map_err(VmError::panic)?;
}
stack.push(Value::Unit);
Ok(())
})
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.