text stringlengths 8 4.13M |
|---|
use libc::open;
use libc::dup2;
use libc::{O_RDONLY, O_WRONLY, O_CREAT, O_TRUNC};
use libc::{STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO};
use libc::exit;
use libc::EXIT_FAILURE;
use std::io::{Error, Result, Write};
use std::os::unix::io::{AsRawFd, RawFd, FromRawFd};
use std::os::unix::fs::{MetadataExt};
use std::fs::{File, Metadata};
use std::fmt::Display;
use std::ffi::CString;
pub struct Stdin {
pub file: File,
}
pub struct Stdout {
pub file: File,
}
pub struct Stderr {
pub file: File,
}
impl AsRawFd for Stdin {
fn as_raw_fd(&self) -> RawFd {
STDIN_FILENO
}
}
impl AsRawFd for Stdout {
fn as_raw_fd(&self) -> RawFd {
STDOUT_FILENO
}
}
impl AsRawFd for Stderr {
fn as_raw_fd(&self) -> RawFd {
STDERR_FILENO
}
}
pub trait FileInfo {
fn metadata(&self) -> Result<Metadata>;
}
impl FileInfo for Stdin {
fn metadata(&self) -> Result<Metadata> {
self.file.metadata()
}
}
impl FileInfo for Stdout {
fn metadata(&self) -> Result<Metadata> {
self.file.metadata()
}
}
impl FileInfo for Stderr {
fn metadata(&self) -> Result<Metadata> {
self.file.metadata()
}
}
impl Stdin {
pub fn own() -> Stdin {
unsafe { Stdin { file: File::from_raw_fd(STDIN_FILENO) } }
}
}
impl Stdout {
pub fn own() -> Stdout {
unsafe { Stdout { file: File::from_raw_fd(STDOUT_FILENO) } }
}
}
impl Stderr {
pub fn own() -> Stderr {
unsafe { Stderr { file: File::from_raw_fd(STDERR_FILENO) } }
}
}
impl FileInfo for File {
fn metadata(&self) -> Result<Metadata> {
self.metadata()
}
}
pub trait ReopenMode {
fn oreopen(&mut self, path: &String, mode: i32) -> Result<()>;
}
impl<T> ReopenMode for T
where T: AsRawFd + FileInfo
{
fn oreopen(&mut self, path: &String, mode: i32) -> Result<()> {
let fd = self.as_raw_fd();
let metadata = try!(self.metadata());
let cpath = CString::new(&path[..]).unwrap();
let file = unsafe { open(cpath.as_ptr(), mode, metadata.mode()) };
if file == -1 {
return Err(Error::last_os_error());
}
if unsafe { dup2(file, fd) == -1 } {
return Err(Error::last_os_error());
}
Ok(())
}
}
pub trait Reopen: ReopenMode {
fn reopen(&mut self, path: &String) -> Result<()>;
}
impl Reopen for Stdin {
fn reopen(&mut self, path: &String) -> Result<()> {
self.oreopen(path, O_RDONLY)
}
}
impl Reopen for Stdout {
fn reopen(&mut self, path: &String) -> Result<()> {
self.oreopen(path, O_WRONLY | O_CREAT | O_TRUNC)
}
}
impl Reopen for Stderr {
fn reopen(&mut self, path: &String) -> Result<()> {
self.oreopen(path, O_WRONLY | O_CREAT | O_TRUNC)
}
}
pub fn fail<T: Display>(msg: T) -> ! {
let mut f = Stderr::own().file;
writeln!(f, "{}", msg).unwrap_or(());
f.flush().unwrap_or(());
unsafe {
exit(EXIT_FAILURE);
}
}
|
#[derive(Debug)]
pub enum DesktopMode {
Tile,
}
pub struct Desktop {
pub mode: DesktopMode,
}
impl Desktop {
pub fn new(mode: DesktopMode) -> Self {
Self { mode }
}
}
|
use std::default::Default;
use std::io::Result;
use std::process::exit;
mod lib;
use lib::Bot;
use lib::CONFIG_PATH;
extern crate irc;
use irc::client::prelude::Config;
fn main() {
if let Ok(config) = handle_config() {
let bot = Bot::new(config);
if let Ok(bot) = bot {
bot.run()
} else if let Err(err) = bot {
println!("Failed to spawn bot instance: {}", err);
}
} else {
println!("Failed to access config file, do you have read/write permissions?");
}
}
fn handle_config() -> Result<Config> {
let config = Config::load(lib::CONFIG_PATH);
match config {
Ok(result) => Ok(result),
Err(err) => {
let config = Config {
nickname: Some("PleaseConfigureMe".into()),
alt_nicks: Some(vec!["WhyDidYou".into(), "ForgetTo".into(), "ConfigureMe".into()]),
server: Some("default.com".into()),
owners: Some(vec!["SK83RJOSH".into()]),
..Default::default()
};
println!("Failed to open config: {}", err);
try!(config.save(CONFIG_PATH));
println!("Wrote default config to {}!", CONFIG_PATH);
println!("Now exiting...");
exit(0);
}
}
}
|
use std::collections::{HashMap, HashSet};
use std::env;
use std::error::Error;
use std::fs;
use std::str;
use bioinformatics_algorithms::{neighbors, revc};
pub fn frequent_words_with_mismatches_and_rc(text: &[u8], k: usize, d: usize) -> HashSet<String> {
let mut kmers = HashMap::new();
let mut frequent = HashSet::new();
let mut max = 0;
text.windows(k)
.map(|x| {
for pattern in neighbors(str::from_utf8(x).unwrap(), d) {
let rc_str = revc(&pattern);
let mut current_freq = 0;
{
let kmer = kmers.entry(pattern.clone()).or_insert(0);
*kmer += 1;
current_freq += *kmer;
}
if let Some(&rc_c) = kmers.get(&rc_str) {
current_freq += rc_c
};
if current_freq == max {
frequent.insert(pattern);
frequent.insert(rc_str);
} else if current_freq > max {
max = current_freq;
frequent.clear();
frequent.insert(pattern);
frequent.insert(rc_str);
}
}
})
.count();
frequent
}
fn main() -> Result<(), Box<dyn Error>> {
let input: String = env::args()
.nth(1)
.unwrap_or("data/rosalind_ba1j.txt".into());
let data = fs::read_to_string(input)?;
let mut lines = data.lines();
let text = lines.next().unwrap();
let mut ints = lines
.next()
.unwrap()
.split(' ')
.map(|x| x.parse().unwrap())
.take(2);
let k = ints.next().unwrap();
let d = ints.next().unwrap();
for word in frequent_words_with_mismatches_and_rc(text.as_bytes(), k, d) {
print!("{} ", word);
}
println!();
Ok(())
}
|
#[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::HB16CFG4 {
#[doc = r"Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
self.register.set(f(&R { bits }, &mut W { bits }).bits);
}
#[doc = r"Reads the contents of the register"]
#[inline(always)]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r"Writes to the register"]
#[inline(always)]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
self.register.set(
f(&mut W {
bits: Self::reset_value(),
})
.bits,
);
}
#[doc = r"Reset value of the register"]
#[inline(always)]
pub const fn reset_value() -> u32 {
0
}
#[doc = r"Writes the reset value to the register"]
#[inline(always)]
pub fn reset(&self) {
self.register.set(Self::reset_value())
}
}
#[doc = "Possible values of the field `EPI_HB16CFG4_MODE`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum EPI_HB16CFG4_MODER {
#[doc = "ADMUX - AD\\[15:0\\]"]
EPI_HB16CFG4_MODE_ADMUX,
#[doc = "ADNONMUX - D\\[15:0\\]"]
EPI_HB16CFG4_MODE_AD,
#[doc = r"Reserved"]
_Reserved(u8),
}
impl EPI_HB16CFG4_MODER {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
match *self {
EPI_HB16CFG4_MODER::EPI_HB16CFG4_MODE_ADMUX => 0,
EPI_HB16CFG4_MODER::EPI_HB16CFG4_MODE_AD => 1,
EPI_HB16CFG4_MODER::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _from(value: u8) -> EPI_HB16CFG4_MODER {
match value {
0 => EPI_HB16CFG4_MODER::EPI_HB16CFG4_MODE_ADMUX,
1 => EPI_HB16CFG4_MODER::EPI_HB16CFG4_MODE_AD,
i => EPI_HB16CFG4_MODER::_Reserved(i),
}
}
#[doc = "Checks if the value of the field is `EPI_HB16CFG4_MODE_ADMUX`"]
#[inline(always)]
pub fn is_epi_hb16cfg4_mode_admux(&self) -> bool {
*self == EPI_HB16CFG4_MODER::EPI_HB16CFG4_MODE_ADMUX
}
#[doc = "Checks if the value of the field is `EPI_HB16CFG4_MODE_AD`"]
#[inline(always)]
pub fn is_epi_hb16cfg4_mode_ad(&self) -> bool {
*self == EPI_HB16CFG4_MODER::EPI_HB16CFG4_MODE_AD
}
}
#[doc = "Values that can be written to the field `EPI_HB16CFG4_MODE`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum EPI_HB16CFG4_MODEW {
#[doc = "ADMUX - AD\\[15:0\\]"]
EPI_HB16CFG4_MODE_ADMUX,
#[doc = "ADNONMUX - D\\[15:0\\]"]
EPI_HB16CFG4_MODE_AD,
}
impl EPI_HB16CFG4_MODEW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _bits(&self) -> u8 {
match *self {
EPI_HB16CFG4_MODEW::EPI_HB16CFG4_MODE_ADMUX => 0,
EPI_HB16CFG4_MODEW::EPI_HB16CFG4_MODE_AD => 1,
}
}
}
#[doc = r"Proxy"]
pub struct _EPI_HB16CFG4_MODEW<'a> {
w: &'a mut W,
}
impl<'a> _EPI_HB16CFG4_MODEW<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: EPI_HB16CFG4_MODEW) -> &'a mut W {
unsafe { self.bits(variant._bits()) }
}
#[doc = "ADMUX - AD\\[15:0\\]"]
#[inline(always)]
pub fn epi_hb16cfg4_mode_admux(self) -> &'a mut W {
self.variant(EPI_HB16CFG4_MODEW::EPI_HB16CFG4_MODE_ADMUX)
}
#[doc = "ADNONMUX - D\\[15:0\\]"]
#[inline(always)]
pub fn epi_hb16cfg4_mode_ad(self) -> &'a mut W {
self.variant(EPI_HB16CFG4_MODEW::EPI_HB16CFG4_MODE_AD)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(3 << 0);
self.w.bits |= ((value as u32) & 3) << 0;
self.w
}
}
#[doc = "Possible values of the field `EPI_HB16CFG4_RDWS`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum EPI_HB16CFG4_RDWSR {
#[doc = "Active RDn is 2 EPI clocks"]
EPI_HB16CFG4_RDWS_2,
#[doc = "Active RDn is 4 EPI clocks"]
EPI_HB16CFG4_RDWS_4,
#[doc = "Active RDn is 6 EPI clocks"]
EPI_HB16CFG4_RDWS_6,
#[doc = "Active RDn is 8 EPI clocks"]
EPI_HB16CFG4_RDWS_8,
}
impl EPI_HB16CFG4_RDWSR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
match *self {
EPI_HB16CFG4_RDWSR::EPI_HB16CFG4_RDWS_2 => 0,
EPI_HB16CFG4_RDWSR::EPI_HB16CFG4_RDWS_4 => 1,
EPI_HB16CFG4_RDWSR::EPI_HB16CFG4_RDWS_6 => 2,
EPI_HB16CFG4_RDWSR::EPI_HB16CFG4_RDWS_8 => 3,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _from(value: u8) -> EPI_HB16CFG4_RDWSR {
match value {
0 => EPI_HB16CFG4_RDWSR::EPI_HB16CFG4_RDWS_2,
1 => EPI_HB16CFG4_RDWSR::EPI_HB16CFG4_RDWS_4,
2 => EPI_HB16CFG4_RDWSR::EPI_HB16CFG4_RDWS_6,
3 => EPI_HB16CFG4_RDWSR::EPI_HB16CFG4_RDWS_8,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `EPI_HB16CFG4_RDWS_2`"]
#[inline(always)]
pub fn is_epi_hb16cfg4_rdws_2(&self) -> bool {
*self == EPI_HB16CFG4_RDWSR::EPI_HB16CFG4_RDWS_2
}
#[doc = "Checks if the value of the field is `EPI_HB16CFG4_RDWS_4`"]
#[inline(always)]
pub fn is_epi_hb16cfg4_rdws_4(&self) -> bool {
*self == EPI_HB16CFG4_RDWSR::EPI_HB16CFG4_RDWS_4
}
#[doc = "Checks if the value of the field is `EPI_HB16CFG4_RDWS_6`"]
#[inline(always)]
pub fn is_epi_hb16cfg4_rdws_6(&self) -> bool {
*self == EPI_HB16CFG4_RDWSR::EPI_HB16CFG4_RDWS_6
}
#[doc = "Checks if the value of the field is `EPI_HB16CFG4_RDWS_8`"]
#[inline(always)]
pub fn is_epi_hb16cfg4_rdws_8(&self) -> bool {
*self == EPI_HB16CFG4_RDWSR::EPI_HB16CFG4_RDWS_8
}
}
#[doc = "Values that can be written to the field `EPI_HB16CFG4_RDWS`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum EPI_HB16CFG4_RDWSW {
#[doc = "Active RDn is 2 EPI clocks"]
EPI_HB16CFG4_RDWS_2,
#[doc = "Active RDn is 4 EPI clocks"]
EPI_HB16CFG4_RDWS_4,
#[doc = "Active RDn is 6 EPI clocks"]
EPI_HB16CFG4_RDWS_6,
#[doc = "Active RDn is 8 EPI clocks"]
EPI_HB16CFG4_RDWS_8,
}
impl EPI_HB16CFG4_RDWSW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _bits(&self) -> u8 {
match *self {
EPI_HB16CFG4_RDWSW::EPI_HB16CFG4_RDWS_2 => 0,
EPI_HB16CFG4_RDWSW::EPI_HB16CFG4_RDWS_4 => 1,
EPI_HB16CFG4_RDWSW::EPI_HB16CFG4_RDWS_6 => 2,
EPI_HB16CFG4_RDWSW::EPI_HB16CFG4_RDWS_8 => 3,
}
}
}
#[doc = r"Proxy"]
pub struct _EPI_HB16CFG4_RDWSW<'a> {
w: &'a mut W,
}
impl<'a> _EPI_HB16CFG4_RDWSW<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: EPI_HB16CFG4_RDWSW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "Active RDn is 2 EPI clocks"]
#[inline(always)]
pub fn epi_hb16cfg4_rdws_2(self) -> &'a mut W {
self.variant(EPI_HB16CFG4_RDWSW::EPI_HB16CFG4_RDWS_2)
}
#[doc = "Active RDn is 4 EPI clocks"]
#[inline(always)]
pub fn epi_hb16cfg4_rdws_4(self) -> &'a mut W {
self.variant(EPI_HB16CFG4_RDWSW::EPI_HB16CFG4_RDWS_4)
}
#[doc = "Active RDn is 6 EPI clocks"]
#[inline(always)]
pub fn epi_hb16cfg4_rdws_6(self) -> &'a mut W {
self.variant(EPI_HB16CFG4_RDWSW::EPI_HB16CFG4_RDWS_6)
}
#[doc = "Active RDn is 8 EPI clocks"]
#[inline(always)]
pub fn epi_hb16cfg4_rdws_8(self) -> &'a mut W {
self.variant(EPI_HB16CFG4_RDWSW::EPI_HB16CFG4_RDWS_8)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(3 << 4);
self.w.bits |= ((value as u32) & 3) << 4;
self.w
}
}
#[doc = "Possible values of the field `EPI_HB16CFG4_WRWS`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum EPI_HB16CFG4_WRWSR {
#[doc = "Active WRn is 2 EPI clocks"]
EPI_HB16CFG4_WRWS_2,
#[doc = "Active WRn is 4 EPI clocks"]
EPI_HB16CFG4_WRWS_4,
#[doc = "Active WRn is 6 EPI clocks"]
EPI_HB16CFG4_WRWS_6,
#[doc = "Active WRn is 8 EPI clocks"]
EPI_HB16CFG4_WRWS_8,
}
impl EPI_HB16CFG4_WRWSR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
match *self {
EPI_HB16CFG4_WRWSR::EPI_HB16CFG4_WRWS_2 => 0,
EPI_HB16CFG4_WRWSR::EPI_HB16CFG4_WRWS_4 => 1,
EPI_HB16CFG4_WRWSR::EPI_HB16CFG4_WRWS_6 => 2,
EPI_HB16CFG4_WRWSR::EPI_HB16CFG4_WRWS_8 => 3,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _from(value: u8) -> EPI_HB16CFG4_WRWSR {
match value {
0 => EPI_HB16CFG4_WRWSR::EPI_HB16CFG4_WRWS_2,
1 => EPI_HB16CFG4_WRWSR::EPI_HB16CFG4_WRWS_4,
2 => EPI_HB16CFG4_WRWSR::EPI_HB16CFG4_WRWS_6,
3 => EPI_HB16CFG4_WRWSR::EPI_HB16CFG4_WRWS_8,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `EPI_HB16CFG4_WRWS_2`"]
#[inline(always)]
pub fn is_epi_hb16cfg4_wrws_2(&self) -> bool {
*self == EPI_HB16CFG4_WRWSR::EPI_HB16CFG4_WRWS_2
}
#[doc = "Checks if the value of the field is `EPI_HB16CFG4_WRWS_4`"]
#[inline(always)]
pub fn is_epi_hb16cfg4_wrws_4(&self) -> bool {
*self == EPI_HB16CFG4_WRWSR::EPI_HB16CFG4_WRWS_4
}
#[doc = "Checks if the value of the field is `EPI_HB16CFG4_WRWS_6`"]
#[inline(always)]
pub fn is_epi_hb16cfg4_wrws_6(&self) -> bool {
*self == EPI_HB16CFG4_WRWSR::EPI_HB16CFG4_WRWS_6
}
#[doc = "Checks if the value of the field is `EPI_HB16CFG4_WRWS_8`"]
#[inline(always)]
pub fn is_epi_hb16cfg4_wrws_8(&self) -> bool {
*self == EPI_HB16CFG4_WRWSR::EPI_HB16CFG4_WRWS_8
}
}
#[doc = "Values that can be written to the field `EPI_HB16CFG4_WRWS`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum EPI_HB16CFG4_WRWSW {
#[doc = "Active WRn is 2 EPI clocks"]
EPI_HB16CFG4_WRWS_2,
#[doc = "Active WRn is 4 EPI clocks"]
EPI_HB16CFG4_WRWS_4,
#[doc = "Active WRn is 6 EPI clocks"]
EPI_HB16CFG4_WRWS_6,
#[doc = "Active WRn is 8 EPI clocks"]
EPI_HB16CFG4_WRWS_8,
}
impl EPI_HB16CFG4_WRWSW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _bits(&self) -> u8 {
match *self {
EPI_HB16CFG4_WRWSW::EPI_HB16CFG4_WRWS_2 => 0,
EPI_HB16CFG4_WRWSW::EPI_HB16CFG4_WRWS_4 => 1,
EPI_HB16CFG4_WRWSW::EPI_HB16CFG4_WRWS_6 => 2,
EPI_HB16CFG4_WRWSW::EPI_HB16CFG4_WRWS_8 => 3,
}
}
}
#[doc = r"Proxy"]
pub struct _EPI_HB16CFG4_WRWSW<'a> {
w: &'a mut W,
}
impl<'a> _EPI_HB16CFG4_WRWSW<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: EPI_HB16CFG4_WRWSW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "Active WRn is 2 EPI clocks"]
#[inline(always)]
pub fn epi_hb16cfg4_wrws_2(self) -> &'a mut W {
self.variant(EPI_HB16CFG4_WRWSW::EPI_HB16CFG4_WRWS_2)
}
#[doc = "Active WRn is 4 EPI clocks"]
#[inline(always)]
pub fn epi_hb16cfg4_wrws_4(self) -> &'a mut W {
self.variant(EPI_HB16CFG4_WRWSW::EPI_HB16CFG4_WRWS_4)
}
#[doc = "Active WRn is 6 EPI clocks"]
#[inline(always)]
pub fn epi_hb16cfg4_wrws_6(self) -> &'a mut W {
self.variant(EPI_HB16CFG4_WRWSW::EPI_HB16CFG4_WRWS_6)
}
#[doc = "Active WRn is 8 EPI clocks"]
#[inline(always)]
pub fn epi_hb16cfg4_wrws_8(self) -> &'a mut W {
self.variant(EPI_HB16CFG4_WRWSW::EPI_HB16CFG4_WRWS_8)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(3 << 6);
self.w.bits |= ((value as u32) & 3) << 6;
self.w
}
}
#[doc = r"Value of the field"]
pub struct EPI_HB16CFG4_BURSTR {
bits: bool,
}
impl EPI_HB16CFG4_BURSTR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _EPI_HB16CFG4_BURSTW<'a> {
w: &'a mut W,
}
impl<'a> _EPI_HB16CFG4_BURSTW<'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 &= !(1 << 16);
self.w.bits |= ((value as u32) & 1) << 16;
self.w
}
}
#[doc = r"Value of the field"]
pub struct EPI_HB16CFG4_RDCRER {
bits: bool,
}
impl EPI_HB16CFG4_RDCRER {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _EPI_HB16CFG4_RDCREW<'a> {
w: &'a mut W,
}
impl<'a> _EPI_HB16CFG4_RDCREW<'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 &= !(1 << 17);
self.w.bits |= ((value as u32) & 1) << 17;
self.w
}
}
#[doc = r"Value of the field"]
pub struct EPI_HB16CFG4_WRCRER {
bits: bool,
}
impl EPI_HB16CFG4_WRCRER {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _EPI_HB16CFG4_WRCREW<'a> {
w: &'a mut W,
}
impl<'a> _EPI_HB16CFG4_WRCREW<'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 &= !(1 << 18);
self.w.bits |= ((value as u32) & 1) << 18;
self.w
}
}
#[doc = r"Value of the field"]
pub struct EPI_HB16CFG4_ALEHIGHR {
bits: bool,
}
impl EPI_HB16CFG4_ALEHIGHR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _EPI_HB16CFG4_ALEHIGHW<'a> {
w: &'a mut W,
}
impl<'a> _EPI_HB16CFG4_ALEHIGHW<'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 &= !(1 << 19);
self.w.bits |= ((value as u32) & 1) << 19;
self.w
}
}
#[doc = r"Value of the field"]
pub struct EPI_HB16CFG4_RDHIGHR {
bits: bool,
}
impl EPI_HB16CFG4_RDHIGHR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _EPI_HB16CFG4_RDHIGHW<'a> {
w: &'a mut W,
}
impl<'a> _EPI_HB16CFG4_RDHIGHW<'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 &= !(1 << 20);
self.w.bits |= ((value as u32) & 1) << 20;
self.w
}
}
#[doc = r"Value of the field"]
pub struct EPI_HB16CFG4_WRHIGHR {
bits: bool,
}
impl EPI_HB16CFG4_WRHIGHR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _EPI_HB16CFG4_WRHIGHW<'a> {
w: &'a mut W,
}
impl<'a> _EPI_HB16CFG4_WRHIGHW<'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 &= !(1 << 21);
self.w.bits |= ((value as u32) & 1) << 21;
self.w
}
}
impl R {
#[doc = r"Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bits 0:1 - CS3n Host Bus Sub-Mode"]
#[inline(always)]
pub fn epi_hb16cfg4_mode(&self) -> EPI_HB16CFG4_MODER {
EPI_HB16CFG4_MODER::_from(((self.bits >> 0) & 3) as u8)
}
#[doc = "Bits 4:5 - CS3n Read Wait States"]
#[inline(always)]
pub fn epi_hb16cfg4_rdws(&self) -> EPI_HB16CFG4_RDWSR {
EPI_HB16CFG4_RDWSR::_from(((self.bits >> 4) & 3) as u8)
}
#[doc = "Bits 6:7 - CS3n Write Wait States"]
#[inline(always)]
pub fn epi_hb16cfg4_wrws(&self) -> EPI_HB16CFG4_WRWSR {
EPI_HB16CFG4_WRWSR::_from(((self.bits >> 6) & 3) as u8)
}
#[doc = "Bit 16 - CS3n Burst Mode"]
#[inline(always)]
pub fn epi_hb16cfg4_burst(&self) -> EPI_HB16CFG4_BURSTR {
let bits = ((self.bits >> 16) & 1) != 0;
EPI_HB16CFG4_BURSTR { bits }
}
#[doc = "Bit 17 - CS3n PSRAM Configuration Register Read"]
#[inline(always)]
pub fn epi_hb16cfg4_rdcre(&self) -> EPI_HB16CFG4_RDCRER {
let bits = ((self.bits >> 17) & 1) != 0;
EPI_HB16CFG4_RDCRER { bits }
}
#[doc = "Bit 18 - CS3n PSRAM Configuration Register Write"]
#[inline(always)]
pub fn epi_hb16cfg4_wrcre(&self) -> EPI_HB16CFG4_WRCRER {
let bits = ((self.bits >> 18) & 1) != 0;
EPI_HB16CFG4_WRCRER { bits }
}
#[doc = "Bit 19 - CS3n ALE Strobe Polarity"]
#[inline(always)]
pub fn epi_hb16cfg4_alehigh(&self) -> EPI_HB16CFG4_ALEHIGHR {
let bits = ((self.bits >> 19) & 1) != 0;
EPI_HB16CFG4_ALEHIGHR { bits }
}
#[doc = "Bit 20 - CS3n READ Strobe Polarity"]
#[inline(always)]
pub fn epi_hb16cfg4_rdhigh(&self) -> EPI_HB16CFG4_RDHIGHR {
let bits = ((self.bits >> 20) & 1) != 0;
EPI_HB16CFG4_RDHIGHR { bits }
}
#[doc = "Bit 21 - CS3n WRITE Strobe Polarity"]
#[inline(always)]
pub fn epi_hb16cfg4_wrhigh(&self) -> EPI_HB16CFG4_WRHIGHR {
let bits = ((self.bits >> 21) & 1) != 0;
EPI_HB16CFG4_WRHIGHR { bits }
}
}
impl W {
#[doc = r"Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bits 0:1 - CS3n Host Bus Sub-Mode"]
#[inline(always)]
pub fn epi_hb16cfg4_mode(&mut self) -> _EPI_HB16CFG4_MODEW {
_EPI_HB16CFG4_MODEW { w: self }
}
#[doc = "Bits 4:5 - CS3n Read Wait States"]
#[inline(always)]
pub fn epi_hb16cfg4_rdws(&mut self) -> _EPI_HB16CFG4_RDWSW {
_EPI_HB16CFG4_RDWSW { w: self }
}
#[doc = "Bits 6:7 - CS3n Write Wait States"]
#[inline(always)]
pub fn epi_hb16cfg4_wrws(&mut self) -> _EPI_HB16CFG4_WRWSW {
_EPI_HB16CFG4_WRWSW { w: self }
}
#[doc = "Bit 16 - CS3n Burst Mode"]
#[inline(always)]
pub fn epi_hb16cfg4_burst(&mut self) -> _EPI_HB16CFG4_BURSTW {
_EPI_HB16CFG4_BURSTW { w: self }
}
#[doc = "Bit 17 - CS3n PSRAM Configuration Register Read"]
#[inline(always)]
pub fn epi_hb16cfg4_rdcre(&mut self) -> _EPI_HB16CFG4_RDCREW {
_EPI_HB16CFG4_RDCREW { w: self }
}
#[doc = "Bit 18 - CS3n PSRAM Configuration Register Write"]
#[inline(always)]
pub fn epi_hb16cfg4_wrcre(&mut self) -> _EPI_HB16CFG4_WRCREW {
_EPI_HB16CFG4_WRCREW { w: self }
}
#[doc = "Bit 19 - CS3n ALE Strobe Polarity"]
#[inline(always)]
pub fn epi_hb16cfg4_alehigh(&mut self) -> _EPI_HB16CFG4_ALEHIGHW {
_EPI_HB16CFG4_ALEHIGHW { w: self }
}
#[doc = "Bit 20 - CS3n READ Strobe Polarity"]
#[inline(always)]
pub fn epi_hb16cfg4_rdhigh(&mut self) -> _EPI_HB16CFG4_RDHIGHW {
_EPI_HB16CFG4_RDHIGHW { w: self }
}
#[doc = "Bit 21 - CS3n WRITE Strobe Polarity"]
#[inline(always)]
pub fn epi_hb16cfg4_wrhigh(&mut self) -> _EPI_HB16CFG4_WRHIGHW {
_EPI_HB16CFG4_WRHIGHW { w: self }
}
}
|
pub use crate::{
api::HltvApi,
https_client::{impls::attohttpc_impl::AttoHttpcImpl, HttpsClient},
};
mod api;
mod https_client;
/// Default HLTV URL.
pub const HLTV_URL: &'static str = "https://www.hltv.org";
pub type Result<T> = std::result::Result<T, Error>;
/// General error type for this crate.
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("HTTPS lib error: {0}")]
HttpsClient(#[source] Box<dyn std::error::Error>),
#[error("IO error: {0}")]
Io(#[from] std::io::Error),
#[error("CSS parse error: {0}")]
CssParse(String),
#[error("HLTV parse error: {0}")]
HltvParse(String),
}
impl PartialEq for Error {
fn eq(&self, other: &Self) -> bool {
self.to_string() == other.to_string()
}
}
impl<'i, E: 'i + std::fmt::Debug> From<cssparser::ParseError<'i, E>> for Error {
fn from(v: cssparser::ParseError<'i, E>) -> Self {
Self::CssParse(format!("(cssparser::ParseError) {:?}", v))
}
}
/// Convert `Option::None` to this crate `Error::String`.
trait NoneErrorExt<T> {
fn css_err<E: Into<String>>(self, c: E) -> Result<T>;
fn hltv_parse_err<E: Into<String>>(self, c: E) -> Result<T>;
}
impl<T> NoneErrorExt<T> for Option<T> {
fn css_err<E: Into<String>>(self, text: E) -> Result<T> {
self.ok_or_else(|| Error::CssParse(text.into()))
}
fn hltv_parse_err<E: Into<String>>(self, text: E) -> Result<T> {
self.ok_or_else(|| Error::HltvParse(text.into()))
}
}
|
#[doc = "Reader of register SR"]
pub type R = crate::R<u32, super::SR>;
#[doc = "Reader of field `ALRAF`"]
pub type ALRAF_R = crate::R<bool, bool>;
#[doc = "Reader of field `ALRBF`"]
pub type ALRBF_R = crate::R<bool, bool>;
#[doc = "Reader of field `WUTF`"]
pub type WUTF_R = crate::R<bool, bool>;
#[doc = "Reader of field `TSF`"]
pub type TSF_R = crate::R<bool, bool>;
#[doc = "Reader of field `TSOVF`"]
pub type TSOVF_R = crate::R<bool, bool>;
#[doc = "Reader of field `ITSF`"]
pub type ITSF_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - ALRAF"]
#[inline(always)]
pub fn alraf(&self) -> ALRAF_R {
ALRAF_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - ALRBF"]
#[inline(always)]
pub fn alrbf(&self) -> ALRBF_R {
ALRBF_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - WUTF"]
#[inline(always)]
pub fn wutf(&self) -> WUTF_R {
WUTF_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - TSF"]
#[inline(always)]
pub fn tsf(&self) -> TSF_R {
TSF_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - TSOVF"]
#[inline(always)]
pub fn tsovf(&self) -> TSOVF_R {
TSOVF_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - ITSF"]
#[inline(always)]
pub fn itsf(&self) -> ITSF_R {
ITSF_R::new(((self.bits >> 5) & 0x01) != 0)
}
}
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {
#[cfg(feature = "Win32_Foundation")]
pub fn AddAtomA(lpstring: super::super::Foundation::PSTR) -> u16;
#[cfg(feature = "Win32_Foundation")]
pub fn AddAtomW(lpstring: super::super::Foundation::PWSTR) -> u16;
#[cfg(feature = "Win32_Foundation")]
pub fn AddClipboardFormatListener(hwnd: super::super::Foundation::HWND) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn ChangeClipboardChain(hwndremove: super::super::Foundation::HWND, hwndnewnext: super::super::Foundation::HWND) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn CloseClipboard() -> super::super::Foundation::BOOL;
pub fn CountClipboardFormats() -> i32;
#[cfg(feature = "Win32_Foundation")]
pub fn DdeAbandonTransaction(idinst: u32, hconv: HCONV, idtransaction: u32) -> super::super::Foundation::BOOL;
pub fn DdeAccessData(hdata: HDDEDATA, pcbdatasize: *mut u32) -> *mut u8;
pub fn DdeAddData(hdata: HDDEDATA, psrc: *const u8, cb: u32, cboff: u32) -> HDDEDATA;
pub fn DdeClientTransaction(pdata: *const u8, cbdata: u32, hconv: HCONV, hszitem: HSZ, wfmt: u32, wtype: DDE_CLIENT_TRANSACTION_TYPE, dwtimeout: u32, pdwresult: *mut u32) -> HDDEDATA;
pub fn DdeCmpStringHandles(hsz1: HSZ, hsz2: HSZ) -> i32;
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))]
pub fn DdeConnect(idinst: u32, hszservice: HSZ, hsztopic: HSZ, pcc: *const CONVCONTEXT) -> HCONV;
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))]
pub fn DdeConnectList(idinst: u32, hszservice: HSZ, hsztopic: HSZ, hconvlist: HCONVLIST, pcc: *const CONVCONTEXT) -> HCONVLIST;
pub fn DdeCreateDataHandle(idinst: u32, psrc: *const u8, cb: u32, cboff: u32, hszitem: HSZ, wfmt: u32, afcmd: u32) -> HDDEDATA;
#[cfg(feature = "Win32_Foundation")]
pub fn DdeCreateStringHandleA(idinst: u32, psz: super::super::Foundation::PSTR, icodepage: i32) -> HSZ;
#[cfg(feature = "Win32_Foundation")]
pub fn DdeCreateStringHandleW(idinst: u32, psz: super::super::Foundation::PWSTR, icodepage: i32) -> HSZ;
#[cfg(feature = "Win32_Foundation")]
pub fn DdeDisconnect(hconv: HCONV) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn DdeDisconnectList(hconvlist: HCONVLIST) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn DdeEnableCallback(idinst: u32, hconv: HCONV, wcmd: DDE_ENABLE_CALLBACK_CMD) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn DdeFreeDataHandle(hdata: HDDEDATA) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn DdeFreeStringHandle(idinst: u32, hsz: HSZ) -> super::super::Foundation::BOOL;
pub fn DdeGetData(hdata: HDDEDATA, pdst: *mut u8, cbmax: u32, cboff: u32) -> u32;
pub fn DdeGetLastError(idinst: u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn DdeImpersonateClient(hconv: HCONV) -> super::super::Foundation::BOOL;
pub fn DdeInitializeA(pidinst: *mut u32, pfncallback: PFNCALLBACK, afcmd: DDE_INITIALIZE_COMMAND, ulres: u32) -> u32;
pub fn DdeInitializeW(pidinst: *mut u32, pfncallback: PFNCALLBACK, afcmd: DDE_INITIALIZE_COMMAND, ulres: u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn DdeKeepStringHandle(idinst: u32, hsz: HSZ) -> super::super::Foundation::BOOL;
pub fn DdeNameService(idinst: u32, hsz1: HSZ, hsz2: HSZ, afcmd: DDE_NAME_SERVICE_CMD) -> HDDEDATA;
#[cfg(feature = "Win32_Foundation")]
pub fn DdePostAdvise(idinst: u32, hsztopic: HSZ, hszitem: HSZ) -> super::super::Foundation::BOOL;
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))]
pub fn DdeQueryConvInfo(hconv: HCONV, idtransaction: u32, pconvinfo: *mut CONVINFO) -> u32;
pub fn DdeQueryNextServer(hconvlist: HCONVLIST, hconvprev: HCONV) -> HCONV;
#[cfg(feature = "Win32_Foundation")]
pub fn DdeQueryStringA(idinst: u32, hsz: HSZ, psz: super::super::Foundation::PSTR, cchmax: u32, icodepage: i32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn DdeQueryStringW(idinst: u32, hsz: HSZ, psz: super::super::Foundation::PWSTR, cchmax: u32, icodepage: i32) -> u32;
pub fn DdeReconnect(hconv: HCONV) -> HCONV;
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))]
pub fn DdeSetQualityOfService(hwndclient: super::super::Foundation::HWND, pqosnew: *const super::super::Security::SECURITY_QUALITY_OF_SERVICE, pqosprev: *mut super::super::Security::SECURITY_QUALITY_OF_SERVICE) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn DdeSetUserHandle(hconv: HCONV, id: u32, huser: usize) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn DdeUnaccessData(hdata: HDDEDATA) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn DdeUninitialize(idinst: u32) -> super::super::Foundation::BOOL;
pub fn DeleteAtom(natom: u16) -> u16;
#[cfg(feature = "Win32_Foundation")]
pub fn EmptyClipboard() -> super::super::Foundation::BOOL;
pub fn EnumClipboardFormats(format: u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn FindAtomA(lpstring: super::super::Foundation::PSTR) -> u16;
#[cfg(feature = "Win32_Foundation")]
pub fn FindAtomW(lpstring: super::super::Foundation::PWSTR) -> u16;
#[cfg(feature = "Win32_Foundation")]
pub fn FreeDDElParam(msg: u32, lparam: super::super::Foundation::LPARAM) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn GetAtomNameA(natom: u16, lpbuffer: super::super::Foundation::PSTR, nsize: i32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn GetAtomNameW(natom: u16, lpbuffer: super::super::Foundation::PWSTR, nsize: i32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn GetClipboardData(uformat: u32) -> super::super::Foundation::HANDLE;
#[cfg(feature = "Win32_Foundation")]
pub fn GetClipboardFormatNameA(format: u32, lpszformatname: super::super::Foundation::PSTR, cchmaxcount: i32) -> i32;
#[cfg(feature = "Win32_Foundation")]
pub fn GetClipboardFormatNameW(format: u32, lpszformatname: super::super::Foundation::PWSTR, cchmaxcount: i32) -> i32;
#[cfg(feature = "Win32_Foundation")]
pub fn GetClipboardOwner() -> super::super::Foundation::HWND;
pub fn GetClipboardSequenceNumber() -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn GetClipboardViewer() -> super::super::Foundation::HWND;
#[cfg(feature = "Win32_Foundation")]
pub fn GetOpenClipboardWindow() -> super::super::Foundation::HWND;
pub fn GetPriorityClipboardFormat(paformatprioritylist: *const u32, cformats: i32) -> i32;
#[cfg(feature = "Win32_Foundation")]
pub fn GetUpdatedClipboardFormats(lpuiformats: *mut u32, cformats: u32, pcformatsout: *mut u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn GlobalAddAtomA(lpstring: super::super::Foundation::PSTR) -> u16;
#[cfg(feature = "Win32_Foundation")]
pub fn GlobalAddAtomExA(lpstring: super::super::Foundation::PSTR, flags: u32) -> u16;
#[cfg(feature = "Win32_Foundation")]
pub fn GlobalAddAtomExW(lpstring: super::super::Foundation::PWSTR, flags: u32) -> u16;
#[cfg(feature = "Win32_Foundation")]
pub fn GlobalAddAtomW(lpstring: super::super::Foundation::PWSTR) -> u16;
pub fn GlobalDeleteAtom(natom: u16) -> u16;
#[cfg(feature = "Win32_Foundation")]
pub fn GlobalFindAtomA(lpstring: super::super::Foundation::PSTR) -> u16;
#[cfg(feature = "Win32_Foundation")]
pub fn GlobalFindAtomW(lpstring: super::super::Foundation::PWSTR) -> u16;
#[cfg(feature = "Win32_Foundation")]
pub fn GlobalGetAtomNameA(natom: u16, lpbuffer: super::super::Foundation::PSTR, nsize: i32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn GlobalGetAtomNameW(natom: u16, lpbuffer: super::super::Foundation::PWSTR, nsize: i32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn ImpersonateDdeClientWindow(hwndclient: super::super::Foundation::HWND, hwndserver: super::super::Foundation::HWND) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InitAtomTable(nsize: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn IsClipboardFormatAvailable(format: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn OpenClipboard(hwndnewowner: super::super::Foundation::HWND) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn PackDDElParam(msg: u32, uilo: usize, uihi: usize) -> super::super::Foundation::LPARAM;
#[cfg(feature = "Win32_Foundation")]
pub fn RegisterClipboardFormatA(lpszformat: super::super::Foundation::PSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn RegisterClipboardFormatW(lpszformat: super::super::Foundation::PWSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn RemoveClipboardFormatListener(hwnd: super::super::Foundation::HWND) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn ReuseDDElParam(lparam: super::super::Foundation::LPARAM, msgin: u32, msgout: u32, uilo: usize, uihi: usize) -> super::super::Foundation::LPARAM;
#[cfg(feature = "Win32_Foundation")]
pub fn SetClipboardData(uformat: u32, hmem: super::super::Foundation::HANDLE) -> super::super::Foundation::HANDLE;
#[cfg(feature = "Win32_Foundation")]
pub fn SetClipboardViewer(hwndnewviewer: super::super::Foundation::HWND) -> super::super::Foundation::HWND;
#[cfg(feature = "Win32_Graphics_Gdi")]
pub fn SetWinMetaFileBits(nsize: u32, lpmeta16data: *const u8, hdcref: super::super::Graphics::Gdi::HDC, lpmfp: *const METAFILEPICT) -> super::super::Graphics::Gdi::HENHMETAFILE;
#[cfg(feature = "Win32_Foundation")]
pub fn UnpackDDElParam(msg: u32, lparam: super::super::Foundation::LPARAM, puilo: *mut usize, puihi: *mut usize) -> super::super::Foundation::BOOL;
}
pub const APPCLASS_MASK: i32 = 15i32;
pub const APPCMD_MASK: i32 = 4080i32;
pub const CADV_LATEACK: u32 = 65535u32;
#[repr(C)]
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))]
pub struct CONVCONTEXT {
pub cb: u32,
pub wFlags: u32,
pub wCountryID: u32,
pub iCodePage: i32,
pub dwLangID: u32,
pub dwSecurity: u32,
pub qos: super::super::Security::SECURITY_QUALITY_OF_SERVICE,
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))]
impl ::core::marker::Copy for CONVCONTEXT {}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))]
impl ::core::clone::Clone for CONVCONTEXT {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))]
pub struct CONVINFO {
pub cb: u32,
pub hUser: usize,
pub hConvPartner: HCONV,
pub hszSvcPartner: HSZ,
pub hszServiceReq: HSZ,
pub hszTopic: HSZ,
pub hszItem: HSZ,
pub wFmt: u32,
pub wType: DDE_CLIENT_TRANSACTION_TYPE,
pub wStatus: CONVINFO_STATUS,
pub wConvst: CONVINFO_CONVERSATION_STATE,
pub wLastError: u32,
pub hConvList: HCONVLIST,
pub ConvCtxt: CONVCONTEXT,
pub hwnd: super::super::Foundation::HWND,
pub hwndPartner: super::super::Foundation::HWND,
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))]
impl ::core::marker::Copy for CONVINFO {}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))]
impl ::core::clone::Clone for CONVINFO {
fn clone(&self) -> Self {
*self
}
}
pub type CONVINFO_CONVERSATION_STATE = u32;
pub const XST_ADVACKRCVD: CONVINFO_CONVERSATION_STATE = 13u32;
pub const XST_ADVDATAACKRCVD: CONVINFO_CONVERSATION_STATE = 16u32;
pub const XST_ADVDATASENT: CONVINFO_CONVERSATION_STATE = 15u32;
pub const XST_ADVSENT: CONVINFO_CONVERSATION_STATE = 11u32;
pub const XST_CONNECTED: CONVINFO_CONVERSATION_STATE = 2u32;
pub const XST_DATARCVD: CONVINFO_CONVERSATION_STATE = 6u32;
pub const XST_EXECACKRCVD: CONVINFO_CONVERSATION_STATE = 10u32;
pub const XST_EXECSENT: CONVINFO_CONVERSATION_STATE = 9u32;
pub const XST_INCOMPLETE: CONVINFO_CONVERSATION_STATE = 1u32;
pub const XST_INIT1: CONVINFO_CONVERSATION_STATE = 3u32;
pub const XST_INIT2: CONVINFO_CONVERSATION_STATE = 4u32;
pub const XST_NULL: CONVINFO_CONVERSATION_STATE = 0u32;
pub const XST_POKEACKRCVD: CONVINFO_CONVERSATION_STATE = 8u32;
pub const XST_POKESENT: CONVINFO_CONVERSATION_STATE = 7u32;
pub const XST_REQSENT: CONVINFO_CONVERSATION_STATE = 5u32;
pub const XST_UNADVACKRCVD: CONVINFO_CONVERSATION_STATE = 14u32;
pub const XST_UNADVSENT: CONVINFO_CONVERSATION_STATE = 12u32;
pub type CONVINFO_STATUS = u32;
pub const ST_ADVISE: CONVINFO_STATUS = 2u32;
pub const ST_BLOCKED: CONVINFO_STATUS = 8u32;
pub const ST_BLOCKNEXT: CONVINFO_STATUS = 128u32;
pub const ST_CLIENT: CONVINFO_STATUS = 16u32;
pub const ST_CONNECTED: CONVINFO_STATUS = 1u32;
pub const ST_INLIST: CONVINFO_STATUS = 64u32;
pub const ST_ISLOCAL: CONVINFO_STATUS = 4u32;
pub const ST_ISSELF: CONVINFO_STATUS = 256u32;
pub const ST_TERMINATED: CONVINFO_STATUS = 32u32;
#[repr(C)]
pub struct COPYDATASTRUCT {
pub dwData: usize,
pub cbData: u32,
pub lpData: *mut ::core::ffi::c_void,
}
impl ::core::marker::Copy for COPYDATASTRUCT {}
impl ::core::clone::Clone for COPYDATASTRUCT {
fn clone(&self) -> Self {
*self
}
}
pub const CP_WINANSI: i32 = 1004i32;
pub const CP_WINNEUTRAL: i32 = 1200i32;
pub const CP_WINUNICODE: i32 = 1200i32;
#[repr(C)]
pub struct DDEACK {
pub _bitfield: u16,
}
impl ::core::marker::Copy for DDEACK {}
impl ::core::clone::Clone for DDEACK {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct DDEADVISE {
pub _bitfield: u16,
pub cfFormat: i16,
}
impl ::core::marker::Copy for DDEADVISE {}
impl ::core::clone::Clone for DDEADVISE {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct DDEDATA {
pub _bitfield: u16,
pub cfFormat: i16,
pub Value: [u8; 1],
}
impl ::core::marker::Copy for DDEDATA {}
impl ::core::clone::Clone for DDEDATA {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct DDELN {
pub _bitfield: u16,
pub cfFormat: i16,
}
impl ::core::marker::Copy for DDELN {}
impl ::core::clone::Clone for DDELN {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct DDEML_MSG_HOOK_DATA {
pub uiLo: usize,
pub uiHi: usize,
pub cbData: u32,
pub Data: [u32; 8],
}
impl ::core::marker::Copy for DDEML_MSG_HOOK_DATA {}
impl ::core::clone::Clone for DDEML_MSG_HOOK_DATA {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct DDEPOKE {
pub _bitfield: u16,
pub cfFormat: i16,
pub Value: [u8; 1],
}
impl ::core::marker::Copy for DDEPOKE {}
impl ::core::clone::Clone for DDEPOKE {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct DDEUP {
pub _bitfield: u16,
pub cfFormat: i16,
pub rgb: [u8; 1],
}
impl ::core::marker::Copy for DDEUP {}
impl ::core::clone::Clone for DDEUP {
fn clone(&self) -> Self {
*self
}
}
pub type DDE_CLIENT_TRANSACTION_TYPE = u32;
pub const XTYP_ADVSTART: DDE_CLIENT_TRANSACTION_TYPE = 4144u32;
pub const XTYP_ADVSTOP: DDE_CLIENT_TRANSACTION_TYPE = 32832u32;
pub const XTYP_EXECUTE: DDE_CLIENT_TRANSACTION_TYPE = 16464u32;
pub const XTYP_POKE: DDE_CLIENT_TRANSACTION_TYPE = 16528u32;
pub const XTYP_REQUEST: DDE_CLIENT_TRANSACTION_TYPE = 8368u32;
pub const XTYP_ADVDATA: DDE_CLIENT_TRANSACTION_TYPE = 16400u32;
pub const XTYP_ADVREQ: DDE_CLIENT_TRANSACTION_TYPE = 8226u32;
pub const XTYP_CONNECT: DDE_CLIENT_TRANSACTION_TYPE = 4194u32;
pub const XTYP_CONNECT_CONFIRM: DDE_CLIENT_TRANSACTION_TYPE = 32882u32;
pub const XTYP_DISCONNECT: DDE_CLIENT_TRANSACTION_TYPE = 32962u32;
pub const XTYP_MONITOR: DDE_CLIENT_TRANSACTION_TYPE = 33010u32;
pub const XTYP_REGISTER: DDE_CLIENT_TRANSACTION_TYPE = 32930u32;
pub const XTYP_UNREGISTER: DDE_CLIENT_TRANSACTION_TYPE = 32978u32;
pub const XTYP_WILDCONNECT: DDE_CLIENT_TRANSACTION_TYPE = 8418u32;
pub const XTYP_XACT_COMPLETE: DDE_CLIENT_TRANSACTION_TYPE = 32896u32;
pub type DDE_ENABLE_CALLBACK_CMD = u32;
pub const EC_ENABLEALL: DDE_ENABLE_CALLBACK_CMD = 0u32;
pub const EC_ENABLEONE: DDE_ENABLE_CALLBACK_CMD = 128u32;
pub const EC_DISABLE: DDE_ENABLE_CALLBACK_CMD = 8u32;
pub const EC_QUERYWAITING: DDE_ENABLE_CALLBACK_CMD = 2u32;
pub const DDE_FACK: u32 = 32768u32;
pub const DDE_FACKREQ: u32 = 32768u32;
pub const DDE_FAPPSTATUS: u32 = 255u32;
pub const DDE_FBUSY: u32 = 16384u32;
pub const DDE_FDEFERUPD: u32 = 16384u32;
pub const DDE_FNOTPROCESSED: u32 = 0u32;
pub const DDE_FRELEASE: u32 = 8192u32;
pub const DDE_FREQUESTED: u32 = 4096u32;
pub type DDE_INITIALIZE_COMMAND = u32;
pub const APPCLASS_MONITOR: DDE_INITIALIZE_COMMAND = 1u32;
pub const APPCLASS_STANDARD: DDE_INITIALIZE_COMMAND = 0u32;
pub const APPCMD_CLIENTONLY: DDE_INITIALIZE_COMMAND = 16u32;
pub const APPCMD_FILTERINITS: DDE_INITIALIZE_COMMAND = 32u32;
pub const CBF_FAIL_ALLSVRXACTIONS: DDE_INITIALIZE_COMMAND = 258048u32;
pub const CBF_FAIL_ADVISES: DDE_INITIALIZE_COMMAND = 16384u32;
pub const CBF_FAIL_CONNECTIONS: DDE_INITIALIZE_COMMAND = 8192u32;
pub const CBF_FAIL_EXECUTES: DDE_INITIALIZE_COMMAND = 32768u32;
pub const CBF_FAIL_POKES: DDE_INITIALIZE_COMMAND = 65536u32;
pub const CBF_FAIL_REQUESTS: DDE_INITIALIZE_COMMAND = 131072u32;
pub const CBF_FAIL_SELFCONNECTIONS: DDE_INITIALIZE_COMMAND = 4096u32;
pub const CBF_SKIP_ALLNOTIFICATIONS: DDE_INITIALIZE_COMMAND = 3932160u32;
pub const CBF_SKIP_CONNECT_CONFIRMS: DDE_INITIALIZE_COMMAND = 262144u32;
pub const CBF_SKIP_DISCONNECTS: DDE_INITIALIZE_COMMAND = 2097152u32;
pub const CBF_SKIP_REGISTRATIONS: DDE_INITIALIZE_COMMAND = 524288u32;
pub const CBF_SKIP_UNREGISTRATIONS: DDE_INITIALIZE_COMMAND = 1048576u32;
pub const MF_CALLBACKS: DDE_INITIALIZE_COMMAND = 134217728u32;
pub const MF_CONV: DDE_INITIALIZE_COMMAND = 1073741824u32;
pub const MF_ERRORS: DDE_INITIALIZE_COMMAND = 268435456u32;
pub const MF_HSZ_INFO: DDE_INITIALIZE_COMMAND = 16777216u32;
pub const MF_LINKS: DDE_INITIALIZE_COMMAND = 536870912u32;
pub const MF_POSTMSGS: DDE_INITIALIZE_COMMAND = 67108864u32;
pub const MF_SENDMSGS: DDE_INITIALIZE_COMMAND = 33554432u32;
pub type DDE_NAME_SERVICE_CMD = u32;
pub const DNS_REGISTER: DDE_NAME_SERVICE_CMD = 1u32;
pub const DNS_UNREGISTER: DDE_NAME_SERVICE_CMD = 2u32;
pub const DNS_FILTERON: DDE_NAME_SERVICE_CMD = 4u32;
pub const DNS_FILTEROFF: DDE_NAME_SERVICE_CMD = 8u32;
pub const DMLERR_ADVACKTIMEOUT: u32 = 16384u32;
pub const DMLERR_BUSY: u32 = 16385u32;
pub const DMLERR_DATAACKTIMEOUT: u32 = 16386u32;
pub const DMLERR_DLL_NOT_INITIALIZED: u32 = 16387u32;
pub const DMLERR_DLL_USAGE: u32 = 16388u32;
pub const DMLERR_EXECACKTIMEOUT: u32 = 16389u32;
pub const DMLERR_FIRST: u32 = 16384u32;
pub const DMLERR_INVALIDPARAMETER: u32 = 16390u32;
pub const DMLERR_LAST: u32 = 16401u32;
pub const DMLERR_LOW_MEMORY: u32 = 16391u32;
pub const DMLERR_MEMORY_ERROR: u32 = 16392u32;
pub const DMLERR_NOTPROCESSED: u32 = 16393u32;
pub const DMLERR_NO_CONV_ESTABLISHED: u32 = 16394u32;
pub const DMLERR_NO_ERROR: u32 = 0u32;
pub const DMLERR_POKEACKTIMEOUT: u32 = 16395u32;
pub const DMLERR_POSTMSG_FAILED: u32 = 16396u32;
pub const DMLERR_REENTRANCY: u32 = 16397u32;
pub const DMLERR_SERVER_DIED: u32 = 16398u32;
pub const DMLERR_SYS_ERROR: u32 = 16399u32;
pub const DMLERR_UNADVACKTIMEOUT: u32 = 16400u32;
pub const DMLERR_UNFOUND_QUEUE_ID: u32 = 16401u32;
pub type HCONV = isize;
pub type HCONVLIST = isize;
pub const HDATA_APPOWNED: u32 = 1u32;
pub type HDDEDATA = isize;
pub type HSZ = isize;
#[repr(C)]
pub struct HSZPAIR {
pub hszSvc: HSZ,
pub hszTopic: HSZ,
}
impl ::core::marker::Copy for HSZPAIR {}
impl ::core::clone::Clone for HSZPAIR {
fn clone(&self) -> Self {
*self
}
}
pub const MAX_MONITORS: u32 = 4u32;
#[repr(C)]
#[cfg(feature = "Win32_Graphics_Gdi")]
pub struct METAFILEPICT {
pub mm: i32,
pub xExt: i32,
pub yExt: i32,
pub hMF: super::super::Graphics::Gdi::HMETAFILE,
}
#[cfg(feature = "Win32_Graphics_Gdi")]
impl ::core::marker::Copy for METAFILEPICT {}
#[cfg(feature = "Win32_Graphics_Gdi")]
impl ::core::clone::Clone for METAFILEPICT {
fn clone(&self) -> Self {
*self
}
}
pub const MF_MASK: u32 = 4278190080u32;
pub const MH_CLEANUP: u32 = 4u32;
pub const MH_CREATE: u32 = 1u32;
pub const MH_DELETE: u32 = 3u32;
pub const MH_KEEP: u32 = 2u32;
#[repr(C)]
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))]
pub struct MONCBSTRUCT {
pub cb: u32,
pub dwTime: u32,
pub hTask: super::super::Foundation::HANDLE,
pub dwRet: u32,
pub wType: u32,
pub wFmt: u32,
pub hConv: HCONV,
pub hsz1: HSZ,
pub hsz2: HSZ,
pub hData: HDDEDATA,
pub dwData1: usize,
pub dwData2: usize,
pub cc: CONVCONTEXT,
pub cbData: u32,
pub Data: [u32; 8],
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))]
impl ::core::marker::Copy for MONCBSTRUCT {}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))]
impl ::core::clone::Clone for MONCBSTRUCT {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct MONCONVSTRUCT {
pub cb: u32,
pub fConnect: super::super::Foundation::BOOL,
pub dwTime: u32,
pub hTask: super::super::Foundation::HANDLE,
pub hszSvc: HSZ,
pub hszTopic: HSZ,
pub hConvClient: HCONV,
pub hConvServer: HCONV,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for MONCONVSTRUCT {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for MONCONVSTRUCT {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct MONERRSTRUCT {
pub cb: u32,
pub wLastError: u32,
pub dwTime: u32,
pub hTask: super::super::Foundation::HANDLE,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for MONERRSTRUCT {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for MONERRSTRUCT {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct MONHSZSTRUCTA {
pub cb: u32,
pub fsAction: super::super::Foundation::BOOL,
pub dwTime: u32,
pub hsz: HSZ,
pub hTask: super::super::Foundation::HANDLE,
pub str: [super::super::Foundation::CHAR; 1],
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for MONHSZSTRUCTA {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for MONHSZSTRUCTA {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct MONHSZSTRUCTW {
pub cb: u32,
pub fsAction: super::super::Foundation::BOOL,
pub dwTime: u32,
pub hsz: HSZ,
pub hTask: super::super::Foundation::HANDLE,
pub str: [u16; 1],
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for MONHSZSTRUCTW {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for MONHSZSTRUCTW {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct MONLINKSTRUCT {
pub cb: u32,
pub dwTime: u32,
pub hTask: super::super::Foundation::HANDLE,
pub fEstablished: super::super::Foundation::BOOL,
pub fNoData: super::super::Foundation::BOOL,
pub hszSvc: HSZ,
pub hszTopic: HSZ,
pub hszItem: HSZ,
pub wFmt: u32,
pub fServer: super::super::Foundation::BOOL,
pub hConvServer: HCONV,
pub hConvClient: HCONV,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for MONLINKSTRUCT {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for MONLINKSTRUCT {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct MONMSGSTRUCT {
pub cb: u32,
pub hwndTo: super::super::Foundation::HWND,
pub dwTime: u32,
pub hTask: super::super::Foundation::HANDLE,
pub wMsg: u32,
pub wParam: super::super::Foundation::WPARAM,
pub lParam: super::super::Foundation::LPARAM,
pub dmhd: DDEML_MSG_HOOK_DATA,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for MONMSGSTRUCT {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for MONMSGSTRUCT {
fn clone(&self) -> Self {
*self
}
}
pub const MSGF_DDEMGR: u32 = 32769u32;
pub type PFNCALLBACK = ::core::option::Option<unsafe extern "system" fn(wtype: u32, wfmt: u32, hconv: HCONV, hsz1: HSZ, hsz2: HSZ, hdata: HDDEDATA, dwdata1: usize, dwdata2: usize) -> HDDEDATA>;
pub const QID_SYNC: u32 = 4294967295u32;
pub const TIMEOUT_ASYNC: u32 = 4294967295u32;
pub const WM_DDE_ACK: u32 = 996u32;
pub const WM_DDE_ADVISE: u32 = 994u32;
pub const WM_DDE_DATA: u32 = 997u32;
pub const WM_DDE_EXECUTE: u32 = 1000u32;
pub const WM_DDE_FIRST: u32 = 992u32;
pub const WM_DDE_INITIATE: u32 = 992u32;
pub const WM_DDE_LAST: u32 = 1000u32;
pub const WM_DDE_POKE: u32 = 999u32;
pub const WM_DDE_REQUEST: u32 = 998u32;
pub const WM_DDE_TERMINATE: u32 = 993u32;
pub const WM_DDE_UNADVISE: u32 = 995u32;
pub const XCLASS_BOOL: u32 = 4096u32;
pub const XCLASS_DATA: u32 = 8192u32;
pub const XCLASS_FLAGS: u32 = 16384u32;
pub const XCLASS_MASK: u32 = 64512u32;
pub const XCLASS_NOTIFICATION: u32 = 32768u32;
pub const XTYPF_ACKREQ: u32 = 8u32;
pub const XTYPF_NOBLOCK: u32 = 2u32;
pub const XTYPF_NODATA: u32 = 4u32;
pub const XTYP_MASK: u32 = 240u32;
pub const XTYP_SHIFT: u32 = 4u32;
|
use std::io::{self, BufReader};
use proconio::{input, source::line::LineSource};
fn main() {
let stdin = io::stdin();
let mut stdin = LineSource::new(BufReader::new(stdin));
input! {
from &mut stdin,
n: usize,
};
let (mut l, mut r) = (0, n);
for _ in 0..20 {
let m = (l + r) / 2;
println!("? {}", m + 1);
input! {
from &mut stdin,
c: u8,
};
if c == 0 {
l = m;
} else {
r = m;
}
if l + 1 == r {
// s[l] = 0 != 1 = s[r]
println!("! {}", l + 1);
return;
}
}
unreachable!();
}
|
// Ubah data dari tipe string ke integer
//
fn main() {
let x = "10".to_string();
let y: i32 = x.parse().unwrap();
let z = x.parse::<i32>().unwrap();
println!("y= {:?}", y);
println!("z= {:?}", z);
let a: i32 = 10;
let b: i64 = a as i64;
println!("b= {:?}", b);
} |
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize, Default, Debug)]
pub struct Config {
workers: u16,
}
|
// #![cfg_attr(feature = "dev", allow(unstable_features))]
// #![cfg_attr(feature = "dev", feature(plugin))]
// #![cfg_attr(feature = "dev", plugin(clippy))]
// #![deny(missing_docs,
// missing_debug_implementations, missing_copy_implementations,
// trivial_casts, trivial_numeric_casts,
// unsafe_code,
// unstable_features,
// unused_import_braces, unused_qualifications)]
#![warn(missing_docs,
missing_debug_implementations, missing_copy_implementations,
trivial_casts, trivial_numeric_casts,
unsafe_code, unstable_features,
unused_import_braces, unused_qualifications)]
extern crate byteorder;
pub mod gba_mem;
pub mod gba_cpu;
use std::env;
use std::fs::File;
pub use gba_cpu::arm_cpu::ARM7;
pub use gba_mem::Memory;
fn main() {
let pak_rom_filename = env::args()
.nth(1)
.expect("PAK ROM argument not specified");
let mut m = Memory::new(pak_rom_filename.as_str()).unwrap();
m.write32::<u32>(0x02000000, 0xdeadbeef);
println!("{:#x}", m.read::<u8>(0x02000000));
let cpu = ARM7::default();
println!("{}", cpu);
}
|
#[macro_export]
macro_rules! morgan_stake_controller {
() => {
("morgan_stake_controller".to_string(), morgan_stake_api::id())
};
}
use morgan_stake_api::stake_instruction::process_instruction;
morgan_interface::morgan_entrypoint!(process_instruction);
|
use crate::flags::Flags;
pub struct Registers {
pub a: u8,
pub b: u8,
pub c: u8,
pub d: u8,
pub e: u8,
pub f: Flags,
pub h: u8,
pub l: u8,
}
impl Registers {
pub fn new() -> Registers {
Registers {
a: 0,
b: 0,
c: 0,
d: 0,
e: 0,
f: Flags::new(),
h: 0,
l: 0,
}
}
pub fn get_af(&self) -> u16 {
(self.a as u16) << 8 | u8::from(&self.f) as u16
}
pub fn set_af(&mut self, value: u16) {
let a = ((value & 0xff00) >> 8) as u8;
let f = Flags::from((value & 0x00ff) as u8);
self.a = a;
self.f = f;
}
pub fn get_bc(&self) -> u16 {
(self.b as u16) << 8 | self.c as u16
}
pub fn set_bc(&mut self, value: u16) {
let b = ((value & 0xff00) >> 8) as u8;
let c = (value & 0x00ff) as u8;
self.b = b;
self.c = c;
}
pub fn get_de(&self) -> u16 {
(self.d as u16) << 8 | self.e as u16
}
pub fn set_de(&mut self, value: u16) {
let d = ((value & 0xff00) >> 8) as u8;
let e = (value & 0x00ff) as u8;
self.d = d;
self.e = e;
}
pub fn get_hl(&self) -> u16 {
(self.h as u16) << 8 | self.l as u16
}
pub fn set_hl(&mut self, value: u16) {
let h = ((value & 0xff00) >> 8) as u8;
let l = (value & 0x00ff) as u8;
self.h = h;
self.l = l;
}
}
|
/*!
A message-only window enables you to send and receive messages. It is not visible, has no z-order, cannot be enumerated, and does not
receive broadcast messages. The window simply dispatches messages.
A MessageWindow do not have any builder parameter, but still provides the API for the derive macro.
Requires the `message-window` feature.
## Example
```
use native_windows_gui as nwg;
let mut window = Default::default();
nwg::MessageWindow::builder().build(&mut window);
```
When making a system-tray application (with TrayNotification), this is the recommended top level window type.
*/
use super::ControlHandle;
use crate::win32::window::create_message_window;
use crate::NwgError;
/**
A message only top level window. At least one top level window is required to make a NWG application.
See the module documentation
*/
#[derive(Default, PartialEq, Eq)]
pub struct MessageWindow {
pub handle: ControlHandle
}
impl MessageWindow {
pub fn builder() -> MessageWindowBuilder {
MessageWindowBuilder {}
}
}
impl Drop for MessageWindow {
fn drop(&mut self) {
self.handle.destroy();
}
}
pub struct MessageWindowBuilder {
}
impl MessageWindowBuilder {
pub fn build(self, out: &mut MessageWindow) -> Result<(), NwgError> {
*out = Default::default();
out.handle = create_message_window()?;
Ok(())
}
}
|
//! Provides error types for the installer tools.
use notion_fail::{ExitCode, NotionFail};
use failure;
#[derive(Debug, Fail, NotionFail)]
#[fail(display = "Failed to download version {}\n{}", version, error)]
#[notion_fail(code = "NetworkError")]
pub(crate) struct DownloadError {
version: String,
error: String,
}
impl DownloadError {
pub(crate) fn for_version(version: String) -> impl FnOnce(&failure::Error) -> DownloadError {
move |error| DownloadError {
version: version,
error: error.to_string(),
}
}
}
|
use super::node::{ExternTensorGraphCondition, NodeEntry};
use crate::ast;
use crate::error::{GraphCallError, Result};
use crate::externs::{ExternIR, ExternIRShapes};
use crate::graph::Graph;
use crate::tensor::IRData;
use crate::variable::{assert_equal, BuildValue, Link};
#[allow(non_upper_case_globals)]
pub mod builtins {
pub const INPUTS: &[&str] = &[INPUT_NAME];
pub(super) const INPUT_NAME: &str = "AssertShape";
pub(super) const NODE__Transform: &str = "Transform";
pub(super) const NODE__ToLinear: &str = "ToLinear";
pub(super) const NODE__Concat: &str = "Concat";
}
use builtins::*;
pub struct GraphNodeEntry<'a, 'b, 'c>
where
'a: 'b,
'b: 'c,
{
pub root: &'c mut NodeEntry<'a, 'b>,
pub node: ast::GraphNode,
}
// ----------------------
// BEGIN Default nodes
// ----------------------
struct InputNode;
impl<'a, 'b, 'c> GraphNodeBuilder<InputNode> for GraphNodeEntry<'a, 'b, 'c> {
fn build(self) -> Result<()> {
let node = self.node;
ExternTensorGraphCondition {
nodes: &[&node].iter().map(|&x| (x.id, x.clone())).collect(),
names: &["Input"],
ty_inputs: Some(ast::GraphInputsType::UseLast),
args: Some(&[]),
is_sized: Some(true),
repeatable: Some(false),
is_id_zero: true,
}
.test()?;
let ir = ExternIR::new_first(
ast::ExternNodeType::Default,
INPUT_NAME.to_string(),
make_empty_graph(&self.root).into(),
None,
node.shapes,
);
self.root.tensor_graph.push(ir.into());
Ok(())
}
}
struct DefaultNode;
impl<'a, 'b, 'c> GraphNodeBuilder<DefaultNode> for GraphNodeEntry<'a, 'b, 'c> {
fn build(self) -> Result<()> {
let root = self.root;
let id = self.node.id;
for call in self.node.calls.into_iter() {
// Step 1. get the node
let mut callee = root.get(&call.name)?;
let graph = root.graph.borrow();
callee.set_id(id);
callee.set_repeat(graph.replace_to(call.repeat)?);
// Step 2. apply variables
if let Some(args) = call.args {
let args = args
.into_iter()
.map(|(k, v)| {
let value = graph.replace_to(Some(v))?;
Ok((k, value))
})
.collect::<Result<_>>()?;
callee.apply_variables(args, true)?;
}
// Step 3. apply IO
let expected_inputs = callee.get_inputs();
let given_inputs = unwrap_dict(call.inputs.unwrap_or_default())?;
*callee.get_inputs_mut() = expected_inputs
.keys()
.map(|k| match given_inputs.get(k) {
Some(x) => x.clone(),
None => ast::Out::with_name(k.clone()),
})
.map(|x| (x.name.clone(), x))
.collect();
let expected_outputs = callee.get_inputs();
*callee.get_outputs_mut() = expected_outputs
.keys()
.map(|k| ast::Out::new(id + 1, k.clone()))
.map(|x| (x.name.clone(), x))
.collect();
// Step 4. merge shapes
if root.tensor_graph.is_some() {
let last_outputs = ast::Shapes::new(
callee
.get_inputs_mut()
.iter_mut()
.map(|(k, x)| Ok((k.clone(), root.fetch_shape(x)?)))
.collect::<Result<_>>()?,
);
let new_inputs = callee.get_input_shapes();
if let Some(new_inputs) = new_inputs {
last_outputs.link_to(new_inputs)?;
// identity
if let Some(new_outputs) = callee.get_output_shapes() {
let mut new_outputs_ref = new_outputs.0.borrow_mut();
for (name, out) in new_outputs_ref.iter_mut() {
if out.is_none() {
let new_outputs_ref = new_inputs.0.borrow();
*out = new_outputs_ref[name].clone();
}
}
}
}
} else {
for x in callee.get_inputs_mut().values_mut() {
x.id = Some(1);
}
}
// Step 5. store
root.tensor_graph.push(callee);
}
// Step 6. merge dedicated shapes
if let Some(shapes) = self.node.shapes {
if let Some(last_outputs) = root.get_output_shapes() {
shapes.link_to(last_outputs)?;
}
}
Ok(())
}
}
// ----------------------
// BEGIN Built-in nodes
// ----------------------
fn get_extern_io(
id: u64,
root: &NodeEntry,
inputs: Vec<String>,
outputs: Vec<String>,
) -> Result<(ast::Outs, ast::Outs)> {
let inputs: ast::Outs = inputs
.into_iter()
.map(|x| {
let mut out = ast::Out::with_name(x.clone());
root.fetch_shape(&mut out)?;
Ok((x, out))
})
.collect::<Result<_>>()?;
let outputs = outputs
.into_iter()
.map(|x| ast::Out::new(id + 1, x))
.map(|x| ((x.name.clone()), x))
.collect();
Ok((inputs, outputs))
}
fn build_extern(
ty: ast::ExternNodeType,
id: u64,
root: &NodeEntry,
name: String,
graph: Graph,
(input, io_input): (ast::Shapes, Vec<String>),
(output, io_output): (ast::Shapes, Vec<String>),
) -> Result<ExternIR> {
let (io_input, io_output) = get_extern_io(id, root, io_input, io_output)?;
Ok(ExternIR {
ty,
data: IRData {
id,
name,
graph: graph.into(),
input: io_input,
output: io_output,
},
shapes: ExternIRShapes {
input: Some(input),
output: Some(output),
},
})
}
fn build_transform(
entry: GraphNodeEntry,
names: &'static [&'static str; 1],
linear: bool,
) -> Result<()> {
let root = entry.root;
let node = entry.node;
let id = node.id;
ExternTensorGraphCondition {
nodes: &[&node].iter().map(|&x| (x.id, x.clone())).collect(),
names,
ty_inputs: Some(ast::GraphInputsType::UseLast),
args: Some(&[]),
is_sized: Some(!linear),
repeatable: Some(false),
is_id_zero: false,
}
.test()?;
// Step 1. get the IO
let inputs = root
.get_output_shapes()
.ok_or(GraphCallError::GenericShapes)?;
let outputs = if linear {
ast::Shapes::new(
inputs
.0
.borrow()
.iter()
.map(|(k, v)| (k.clone(), v.as_ref().map(|x| ast::Shape(vec![x.product()]))))
.collect(),
)
} else {
node.shapes.unwrap()
};
if !linear {
// Step 2. match the tuple
let inputs = inputs.0.borrow();
let outputs = outputs.0.borrow();
if inputs.len() != outputs.len() || inputs.keys().any(|x| !outputs.contains_key(x)) {
return GraphCallError::MismatchedShapeKeys {
expected: inputs.keys().cloned().collect(),
given: outputs.keys().cloned().collect(),
}
.into();
}
// Step 3. match the size
for ((name, input), output) in inputs.iter().zip(outputs.values()) {
let input = unwrap_value(name, input.as_ref())?.product().build();
let output = unwrap_value(name, output.as_ref())?.product().build();
assert_equal(input, output)?;
}
}
// Step 4. store variables
let graph = make_graph_with_one_var(
&root,
"output shapes",
Some(ast::Value::Map(
outputs
.0
.borrow()
.iter()
.map(|(k, v)| (k.clone(), v.as_ref().map(|x| x.0.clone().into())))
.collect(),
)),
);
// Step 5. store
let io_inputs: Vec<_> = inputs.0.borrow().keys().cloned().collect();
let io_outputs = io_inputs.clone();
let ir = build_extern(
ast::ExternNodeType::Default,
id,
root,
names[0].to_string(),
graph,
(inputs.clone(), io_inputs),
(outputs, io_outputs),
)?;
root.tensor_graph.push(ir.into());
Ok(())
}
struct Transform;
impl<'a, 'b, 'c> GraphNodeBuilder<Transform> for GraphNodeEntry<'a, 'b, 'c> {
fn build(self) -> Result<()> {
build_transform(self, &[NODE__Transform], false)
}
}
struct ToLinear;
impl<'a, 'b, 'c> GraphNodeBuilder<ToLinear> for GraphNodeEntry<'a, 'b, 'c> {
fn build(self) -> Result<()> {
build_transform(self, &[NODE__ToLinear], true)
}
}
struct Concat;
impl<'a, 'b, 'c> GraphNodeBuilder<Concat> for GraphNodeEntry<'a, 'b, 'c> {
fn build(self) -> Result<()> {
let root = self.root;
let mut node = self.node;
let id = node.id;
ExternTensorGraphCondition {
nodes: &[&node].iter().map(|&x| (x.id, x.clone())).collect(),
names: &[NODE__Concat],
ty_inputs: Some(ast::GraphInputsType::List),
args: Some(&["axis"]),
is_sized: Some(false),
repeatable: Some(false),
is_id_zero: false,
}
.test()?;
let call = node.calls.pop().unwrap();
let mut args = call.args.unwrap();
// Step 1. get the axis
let axis = args.remove("axis");
let axis = root.graph.borrow().replace_to(axis)?.unwrap();
let axis = axis.build();
let mut axis = axis
.unwrap_int()
.ok_or_else(|| GraphCallError::MismatchedArgType {
expected: ast::LetType::UInt,
given: axis.ty(),
})?;
// Step 2. get the inputs
let mut io_inputs = call.inputs.unwrap().unwrap_list().unwrap();
let inputs: Vec<_> = io_inputs
.iter_mut()
.map(|x| root.fetch_shape(x))
.collect::<Result<_>>()?;
if inputs.is_empty() {
return GraphCallError::EmptyInputs.into();
}
// Step 3. concat the inputs
let mut tensor_base: Vec<_> = match &inputs[0] {
Some(shapes) => shapes.0.iter().map(Some).collect(),
None => return GraphCallError::GenericShapes.into(),
};
let tensor_dims = tensor_base.len() as i64;
if axis < 0 {
axis = -axis - tensor_dims;
}
if axis < 0 || axis >= tensor_dims {
return GraphCallError::MismatchedAxis {
val_min: 0,
val_max: tensor_dims - 1,
given: axis,
}
.into();
}
let axis = axis as usize;
let tensor_dims = tensor_base.len();
let mut target_dim = vec![tensor_base[axis].unwrap().clone()];
tensor_base[axis] = None;
for (index, shape) in inputs.iter().enumerate().skip(1) {
let shape = match shape {
Some(x) => &x.0,
None => return GraphCallError::GenericListInputShape { index }.into(),
};
// test tensor dimensions
{
let expected = tensor_dims;
let given = shape.len();
if expected != given {
return GraphCallError::MismatchedShapes { expected, given }.into();
}
}
// test each tensor dimension
for (d0, d1) in tensor_base.iter().zip(shape.iter()) {
if let Some(d0) = d0 {
let d0 = d0.build();
let d1 = d0.build();
assert_equal(d0, d1)?;
} else {
target_dim.push(d1.clone());
}
}
}
let dim = ast::Shape(target_dim).sum();
tensor_base[axis] = Some(&dim);
let outputs: Vec<_> = tensor_base
.into_iter()
.map(|x| x.unwrap().clone())
.collect();
// Step 4. store variables
let graph = make_graph_with_one_var(&root, "axis", Some((axis as i64).into()));
// Step 5. store
let inputs = inputs
.iter()
.enumerate()
.map(|(i, x)| (i.to_string(), x.as_ref().cloned()))
.collect();
let inputs = ast::Shapes::new(inputs);
let outputs = ast::Shape(outputs);
let outputs = [("x", outputs)]
.iter()
.map(|(k, v)| (k.to_string(), Some(v.clone())))
.collect();
let outputs = ast::Shapes::new(outputs);
let io_inputs = io_inputs.into_iter().map(|x| x.name).collect();
let io_outputs = vec!["x".to_string()];
let ir = build_extern(
ast::ExternNodeType::Default,
id,
root,
call.name,
graph,
(inputs, io_inputs),
(outputs, io_outputs),
)?;
root.tensor_graph.push(ir.into());
Ok(())
}
}
// ----------------------
// MATCH Built-in nodes
// ----------------------
macro_rules! match_builtins(
($s:ident => $( $t:ty ),*,) => {
match $s.node.calls[0].name.as_str() {
$( stringify!($t) => GraphNodeBuilder::<$t>::build($s) ),*,
_ => GraphNodeBuilder::<DefaultNode>::build($s),
}
}
);
impl<'a, 'b, 'c> GraphNodeEntry<'a, 'b, 'c> {
fn is_input(&self) -> bool {
self.node.id == 0
}
pub fn build(self) -> Result<()> {
if self.is_input() {
// input node
GraphNodeBuilder::<InputNode>::build(self)
} else {
match_builtins!(self =>
Transform,
ToLinear,
Concat,
)
}
}
}
// ----------------------
// END Built-in nodes
// ----------------------
trait GraphNodeBuilder<B>
where
Self: Sized,
{
fn build(self) -> Result<()>;
}
fn make_empty_graph(root: &NodeEntry) -> Graph {
Graph::new(&root.ctx.root.seed)
}
fn make_graph_with_one_var(root: &NodeEntry, name: &str, value: Option<ast::Value>) -> Graph {
Graph::with_one_var(&root.ctx.root.seed, name, value)
}
fn unwrap_dict(inputs: ast::GraphInputs) -> Result<ast::Outs> {
let given = inputs.ty();
inputs.unwrap_dict().ok_or_else(|| {
GraphCallError::MismatchedInputsType {
expected: ast::GraphInputsType::Dict,
given,
}
.into()
})
}
fn unwrap_value<T>(name: &str, value: Option<T>) -> Result<T> {
value.ok_or_else(|| {
GraphCallError::GenericShape {
name: name.to_string(),
}
.into()
})
}
|
use super::{Block, Statement, Value, Ident, Item, ItemArg};
pub fn print(block: &Block) -> String {
let mut out = String::new();
print_block(block, &mut out, 0);
out
}
fn pad_level(string: &mut String, level: u64) {
for _ in 0..level {
string.push_str(" ");
}
}
fn print_block(block: &Block, out: &mut String, level: u64) {
for statement in &block.statements {
print_statement(statement, out, level);
}
}
fn print_statement(stmt: &Statement, out: &mut String, level: u64) {
for (attr_name, attr_value) in &stmt.attributes {
pad_level(out, level);
out.push_str("@");
out.push_str(attr_name);
out.push_str(" ");
print_value(attr_value, out, level);
out.push_str("\n");
}
pad_level(out, level);
for (idx, item) in stmt.items.iter().enumerate() {
print_value(item, out, level);
if idx != stmt.items.len() - 1 {
out.push_str(" => ");
}
}
out.push_str(";\n");
}
fn print_value(value: &Value, out: &mut String, level: u64) {
match *value {
Value::String { is_block: false, ref string } => {
out.push_str("\"");
out.push_str(string);
out.push_str("\"");
},
Value::Item(Item { ref name, ref args, ref block }) => {
print_ident(name, out, level);
// Arguments
if args.len() != 0 {
out.push_str("(");
for (idx, &ItemArg { ref tag, ref value }) in args.iter().enumerate() {
if let &Some(ref tag_i) = tag {
out.push_str(tag_i);
out.push_str(": ");
}
print_value(&value, out, level);
if idx != args.len() - 1 {
out.push_str(", ");
}
}
out.push_str(")");
}
// Block
if block.statements.len() != 0 {
out.push_str(" {\n");
print_block(&block, out, level+1);
pad_level(out, level);
out.push_str("}");
}
},
_ => unimplemented!(),
}
}
fn print_ident(ident: &Ident, out: &mut String, _level: u64) {
match *ident {
Ident::Simple(ref string) => {
out.push_str(string);
}
Ident::RootNs(ref path) => {
for node in path {
out.push_str("::");
out.push_str(node);
}
}
}
}
|
// This file is part of syslog2. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/syslog2/master/COPYRIGHT. No part of syslog2, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
// Copyright © 2016 The developers of syslog2. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/syslog2/master/COPYRIGHT.
extern crate libc;
use Facility;
use Priority;
use LogMask;
use super::syslogSenders::Rfc3164Facility;
use self::libc::c_int;
#[allow(non_camel_case_types)]
#[derive(Debug, Copy, Clone)]
#[repr(i32)] // We'd like to use c_int here, but the compiler won't let us
#[cfg(not(target_os = "windows"))]
pub enum Severity
{
LOG_EMERG = self::libc::LOG_EMERG,
LOG_ALERT = self::libc::LOG_ALERT,
LOG_CRIT = self::libc::LOG_CRIT,
LOG_ERR = self::libc::LOG_ERR,
LOG_WARNING = self::libc::LOG_WARNING,
LOG_NOTICE = self::libc::LOG_NOTICE,
LOG_INFO = self::libc::LOG_INFO,
LOG_DEBUG = self::libc::LOG_DEBUG,
}
/// Windows values are 'fakes' to allow some compatibility
#[allow(non_camel_case_types)]
#[derive(Debug, Copy, Clone)]
#[repr(i32)] // We'd like to use c_int here, but the compiler won't let us
#[cfg(target_os = "windows")]
pub enum Severity
{
LOG_EMERG = 0,
LOG_ALERT = 1,
LOG_CRIT = 2,
LOG_ERR = 3,
LOG_WARNING = 4,
LOG_NOTICE = 5,
LOG_INFO = 6,
LOG_DEBUG = 7,
}
/// Always inlined to replicate the behaviour of a C 'function' macro
#[inline(always)]
const fn LOG_MASK(pri: Severity) -> LogMask
{
1 << (pri as c_int)
}
/// Always inlined to replicate the behaviour of a C 'function' macro
#[inline(always)]
const fn LOG_UPTO(toppri: Severity) -> LogMask
{
(1 << ((toppri as c_int) + 1)) - 1
}
impl Severity
{
#[inline(always)]
pub const fn toPriorityForCurrentLoggingFacility(self) -> Priority
{
self as c_int
}
/// Similar to LOG_MAKEPRI on all systems except:-
/// - not defined on OpenBSD, BitRig or Solaris
/// - only defined in Android bionic from March 2015
/// - incorrectly defined in musl to ((f as c_int) << 3) | (p as c_int); see the mailing list posts as to why: http://www.openwall.com/lists/musl/2015/10/12/2
/// - historically differed in glibc
#[inline(always)]
pub const fn toPriority(self, facility: Facility) -> Priority
{
(facility as c_int) | (self as c_int)
}
#[inline(always)]
pub const fn toPriorityRfc3164(self, rfc3164Facility: Rfc3164Facility) -> Priority
{
(rfc3164Facility as c_int) | (self as c_int)
}
/// If a message is masked then it is recorded, otherwise it is dropped
/// Always inlined to replicate the behaviour of a C 'function' macro
#[inline(always)]
pub const fn mask(self) -> LogMask
{
LOG_MASK(self)
}
/// Creates a log mask that includes all priorities upto and including `toppri`
/// "Upto" in this case means that LOG_EMERG is least and LOG_DEBUG is most
/// This is a little counter-intuitive - it's the reverse of what many people think of
/// eg specifying LOG_ERR in the priority logs LOG_EMERG, LOG_CRIT and LOG_ERR
/// Always inlined to replicate the behaviour of a C 'function' macro
#[inline(always)]
pub const fn mask_upto(self) -> LogMask
{
LOG_UPTO(self)
}
pub const fn mask_all_but_self(self) -> LogMask
{
!self.mask()
}
pub const fn mask_and(self, other: Severity) -> LogMask
{
self.mask() | other.mask()
}
}
|
use input_i_scanner::InputIScanner;
use join::Join;
fn main() {
let stdin = std::io::stdin();
let mut _i_i = InputIScanner::from(stdin.lock());
macro_rules! scan {
(($($t: ty),+)) => {
($(scan!($t)),+)
};
($t: ty) => {
_i_i.scan::<$t>() as $t
};
(($($t: ty),+); $n: expr) => {
std::iter::repeat_with(|| scan!(($($t),+))).take($n).collect::<Vec<_>>()
};
($t: ty; $n: expr) => {
std::iter::repeat_with(|| scan!($t)).take($n).collect::<Vec<_>>()
};
}
let mut k = scan!(usize);
let mut ans = Vec::new();
while k > 0 {
ans.push(k % 2);
k /= 2;
}
ans.reverse();
let ans = ans
.iter()
.map(|d| match d {
0 => 0,
1 => 2,
_ => unreachable!(),
})
.join("");
println!("{}", ans);
}
// 2 1
// 20 2
// 22 3
// 200 4
// 202 5
// 220 6
// 222 7
// 2000 8
// 2002 9
// 2020 10
// 2022 11
// 2200 12
// 2202 13
// 2222 14
|
/// Every data packet transmitted has data specific to either the Event or
/// Actor managers. This value is written to differentiate those parts of the
/// payload.
#[derive(Copy, Clone, Debug, PartialEq)]
#[repr(u8)]
pub enum ManagerType {
/// An EventManager
Event = 1,
/// An ActorManager
Actor = 2,
/// An CommandManager
Command = 3,
/// Unknown Manager
Unknown = 255,
}
impl From<u8> for ManagerType {
fn from(orig: u8) -> Self {
match orig {
1 => return ManagerType::Event,
2 => return ManagerType::Actor,
3 => return ManagerType::Command,
_ => return ManagerType::Unknown,
};
}
}
|
//! A windowing shell for Iced, on top of [`winit`].
//!
//! 
//!
//! `iced_winit` offers some convenient abstractions on top of [`iced_native`]
//! to quickstart development when using [`winit`].
//!
//! It exposes a renderer-agnostic [`Application`] trait that can be implemented
//! and then run with a simple call. The use of this trait is optional.
//!
//! Additionally, a [`conversion`] module is available for users that decide to
//! implement a custom event loop.
//!
//! [`iced_native`]: https://github.com/hecrj/iced/tree/master/native
//! [`winit`]: https://github.com/rust-windowing/winit
//! [`Application`]: trait.Application.html
//! [`conversion`]: conversion
#![deny(missing_docs)]
#![deny(missing_debug_implementations)]
#![deny(unused_results)]
#![deny(unsafe_code)]
#![deny(rust_2018_idioms)]
#[doc(no_inline)]
pub use iced_native::*;
pub use winit;
pub mod conversion;
pub mod settings;
mod application;
mod clipboard;
mod subscription;
// We disable debug capabilities on release builds unless the `debug` feature
// is explicitly enabled.
#[cfg(feature = "debug")]
#[path = "debug/basic.rs"]
mod debug;
#[cfg(not(feature = "debug"))]
#[path = "debug/null.rs"]
mod debug;
pub use application::Application;
pub use settings::Settings;
use clipboard::Clipboard;
use debug::Debug;
|
use ::cpu::exits::VcpuExit;
use ::memory::MmapMemorySlot;
pub trait Accelerator {
fn init_vcpu(&mut self);
fn memory_region_add(&self, mem: &MmapMemorySlot);
fn vcpu_run(&mut self, vcpu_index: usize) -> VcpuExit;
}
|
use assert_cmd::prelude::*;
use predicates::prelude::*;
use std::process::Command;
#[test]
fn run_with_defaults() -> Result<(), Box<dyn std::error::Error>> {
Command::cargo_bin("lokisay")
.expect("binary exists")
.assert()
.success()
.stdout(predicate::str::contains("Meow!"));
Ok(())
}
#[test]
fn fail_on_non_existing_file() -> Result<(), Box<dyn std::error::Error>> {
Command::cargo_bin("lokisay")
.expect("binary exists")
.args(&["-f", "~/file_doesnt_exist.txt"])
.assert()
.failure()
.stderr(predicate::str::contains("No such file or directory"));
Ok(())
}
|
// Copyright 2021 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use once_cell::sync::Lazy;
use semver::BuildMetadata;
use semver::Prerelease;
use semver::Version;
pub static METASRV_COMMIT_VERSION: Lazy<String> = Lazy::new(|| {
let build_semver = option_env!("DATABEND_GIT_SEMVER");
let git_sha = option_env!("VERGEN_GIT_SHA");
let rustc_semver = option_env!("VERGEN_RUSTC_SEMVER");
let timestamp = option_env!("VERGEN_BUILD_TIMESTAMP");
match (build_semver, git_sha, rustc_semver, timestamp) {
#[cfg(not(feature = "simd"))]
(Some(v1), Some(v2), Some(v3), Some(v4)) => format!("{}-{}({}-{})", v1, v2, v3, v4),
#[cfg(feature = "simd")]
(Some(v1), Some(v2), Some(v3), Some(v4)) => {
format!("{}-{}-simd({}-{})", v1, v2, v3, v4)
}
_ => String::new(),
}
});
pub static METASRV_SEMVER: Lazy<Version> = Lazy::new(|| {
let build_semver = option_env!("DATABEND_GIT_SEMVER");
let semver = build_semver.expect("DATABEND_GIT_SEMVER can not be None");
let semver = semver.strip_prefix('v').unwrap_or(semver);
Version::parse(semver).unwrap_or_else(|e| panic!("Invalid semver: {:?}: {}", semver, e))
});
/// Oldest compatible nightly meta-client version
pub static MIN_METACLI_SEMVER: Version = Version {
major: 0,
minor: 9,
patch: 41,
pre: Prerelease::EMPTY,
build: BuildMetadata::EMPTY,
};
pub fn to_digit_ver(v: &Version) -> u64 {
v.major * 1_000_000 + v.minor * 1_000 + v.patch
}
pub fn from_digit_ver(u: u64) -> Version {
println!("{}", u);
Version::new(u / 1_000_000, u / 1_000 % 1_000, u % 1_000)
}
|
// 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.
//! This module contains methods for creating OpenID requests and interpreting
//! responses.
use crate::constants::USER_INFO_URI;
use crate::error::{AuthProviderError, ResultExt};
use crate::http::{HttpRequest, HttpRequestBuilder};
use crate::oauth::{self, AccessToken, RefreshToken};
use fidl_fuchsia_auth::{AuthProviderStatus, UserProfileInfo};
use hyper::StatusCode;
use log::warn;
use serde_derive::Deserialize;
use serde_json::from_str;
type AuthProviderResult<T> = Result<T, AuthProviderError>;
#[derive(Debug, PartialEq)]
pub struct IdToken(pub String);
/// Response type for OpenID user info requests.
#[derive(Debug, Deserialize)]
struct OpenIdUserInfoResponse {
pub sub: String,
pub name: Option<String>,
pub profile: Option<String>,
pub picture: Option<String>,
}
/// Response type for an OpenID ID token request.
#[derive(Debug, Deserialize)]
struct OpenIdTokenResponse {
pub id_token: String,
pub expires_in: u64,
}
/// Error response for OpenID requests.
#[derive(Debug, Deserialize)]
struct OpenIdErrorResponse {
pub error: String,
}
/// Construct an `HttpRequest` for an OpenID user info request.
pub fn build_user_info_request(access_token: AccessToken) -> AuthProviderResult<HttpRequest> {
HttpRequestBuilder::new(USER_INFO_URI.as_str(), "GET")
.with_header("Authorization", format!("Bearer {}", access_token.0))
.finish()
}
/// Construct an `HttpRequest` to request an OpenID ID token.
pub fn build_id_token_request(
refresh_token: RefreshToken,
audience: Option<String>,
) -> AuthProviderResult<HttpRequest> {
// OpenID standard dictates that id_token is returned as part of an Oauth
// access token response. Thus, the request is really just an Oauth request.
oauth::build_request_with_refresh_token(refresh_token, vec![], audience)
}
/// Parse an OpenID user info response.
pub fn parse_user_info_response(
response_body: Option<String>,
status_code: StatusCode,
) -> AuthProviderResult<UserProfileInfo> {
match (response_body.as_ref(), status_code) {
(Some(response), StatusCode::OK) => {
let OpenIdUserInfoResponse { sub, name, profile, picture } =
serde_json::from_str::<OpenIdUserInfoResponse>(&response)
.auth_provider_status(AuthProviderStatus::OauthServerError)?;
Ok(UserProfileInfo { id: sub, display_name: name, url: profile, image_url: picture })
}
(Some(response), status) if status.is_client_error() => {
let error_response = from_str::<OpenIdErrorResponse>(&response)
.auth_provider_status(AuthProviderStatus::OauthServerError)?;
warn!("Got unexpected error code for OpenId user info: {}", error_response.error);
Err(AuthProviderError::new(AuthProviderStatus::OauthServerError))
}
_ => Err(AuthProviderError::new(AuthProviderStatus::OauthServerError)),
}
}
/// Parse an OpenID ID token response.
pub fn parse_id_token_response(
response_body: Option<String>,
status_code: StatusCode,
) -> AuthProviderResult<(IdToken, u64)> {
match (response_body.as_ref(), status_code) {
(Some(response), StatusCode::OK) => {
let OpenIdTokenResponse { id_token, expires_in } =
serde_json::from_str::<OpenIdTokenResponse>(&response)
.auth_provider_status(AuthProviderStatus::OauthServerError)?;
Ok((IdToken(id_token), expires_in))
}
(Some(response), status) if status.is_client_error() => {
let error_response = from_str::<OpenIdErrorResponse>(&response)
.auth_provider_status(AuthProviderStatus::OauthServerError)?;
warn!("Got unexpected error code while retrieving ID token: {}", error_response.error);
Err(AuthProviderError::new(AuthProviderStatus::OauthServerError))
}
_ => Err(AuthProviderError::new(AuthProviderStatus::OauthServerError)),
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_parse_user_info_success() {
// All optional arguments returned
let http_result = String::from(
"{\"sub\": \"id-123\", \"name\": \"Amanda\", \"profile\": \"profile-url\", \
\"picture\": \"picture-url\"}",
);
let user_profile_info =
parse_user_info_response(Some(http_result), StatusCode::OK).unwrap();
assert_eq!(
user_profile_info,
UserProfileInfo {
id: String::from("id-123"),
display_name: Some(String::from("Amanda")),
url: Some(String::from("profile-url")),
image_url: Some(String::from("picture-url")),
}
);
// Only ID provided
let http_result = String::from("{\"sub\": \"id-321\"}");
let user_profile_info =
parse_user_info_response(Some(http_result), StatusCode::OK).unwrap();
assert_eq!(
user_profile_info,
UserProfileInfo {
id: String::from("id-321"),
display_name: None,
url: None,
image_url: None,
}
);
}
#[test]
fn test_parse_user_info_failures() {
// Bad token case
let invalid_http_result = String::from("{\"error\": \"invalid_token\"}");
let result = parse_user_info_response(Some(invalid_http_result), StatusCode::UNAUTHORIZED);
assert_eq!(result.unwrap_err().status, AuthProviderStatus::OauthServerError);
// Server error case
let result = parse_user_info_response(None, StatusCode::INTERNAL_SERVER_ERROR);
assert_eq!(result.unwrap_err().status, AuthProviderStatus::OauthServerError);
// Malformed response case
let invalid_http_result = String::from("\\\\malformed\\\\");
let result = parse_user_info_response(Some(invalid_http_result), StatusCode::OK);
assert_eq!(result.unwrap_err().status, AuthProviderStatus::OauthServerError);
}
#[test]
fn test_parse_id_token_response_success() {
let http_result = "{\"id_token\": \"test-id-token\", \"expires_in\": 3600}".to_string();
let (id_token, expires_in) =
parse_id_token_response(Some(http_result), StatusCode::OK).unwrap();
assert_eq!(id_token, IdToken("test-id-token".to_string()));
assert_eq!(expires_in, 3600);
}
#[test]
fn test_parse_id_token_response_failures() {
// Bad token case
let invalid_http_result = "{\"error\": \"invalid_token\"}".to_string();
let result = parse_id_token_response(Some(invalid_http_result), StatusCode::UNAUTHORIZED);
assert_eq!(result.unwrap_err().status, AuthProviderStatus::OauthServerError);
// Server error case
let result = parse_id_token_response(None, StatusCode::INTERNAL_SERVER_ERROR);
assert_eq!(result.unwrap_err().status, AuthProviderStatus::OauthServerError);
// Malformed response case
let invalid_http_result = "\\\\malformed\\\\".to_string();
let result = parse_id_token_response(Some(invalid_http_result), StatusCode::OK);
assert_eq!(result.unwrap_err().status, AuthProviderStatus::OauthServerError);
}
}
|
#![feature(allocator_api)]
// CHIP-8 EMU
use crate::vm::Vm;
use std::env;
use minifb::{Window, WindowOptions};
mod vm;
mod instruction;
mod stack;
mod opcode;
mod register;
mod display;
mod keymap;
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() <= 1 {
panic!("Please pass a filename to the command line.");
}
let mut window = Window::new(
"Test - ESC to exit",
640,
320,
WindowOptions::default(),
)
.unwrap_or_else(|e| {
panic!("{}", e);
});
window.limit_update_rate(Some(std::time::Duration::from_micros(16400)));
let mut vm = Vm::new();
vm.start();
match std::fs::read(&args[1]) {
Ok(bytes) => { vm.load(bytes); }
Err(e) => {
if e.kind() == std::io::ErrorKind::NotFound {
eprintln!("File not found!");
return;
}
panic!("{}", e);
}
}
println!("Executing...");
vm.update();
vm.execute(&mut window);
vm.stop();
}
|
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
// Copyright © 2019 The developers of linux-epoll. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT.
/// Start of Authority (`SOA`) data.
#[derive(Debug, Clone)]
pub struct StartOfAuthority<'a>
{
/// `MNAME`.
///
/// This is the FQDN of the primary name server.
pub primary_name_server: WithCompressionParsedName<'a>,
/// `RNAME`.
///
/// First label is the name `@`, eg `hostmaster.example.com.` is the email address `hostmaster@example.com`.
pub responsible_person_email_address: WithCompressionParsedName<'a>,
/// All other fields.
///
/// Not necesarily aligned, so may fault on 32-bit ARM.
pub footer: &'a StartOfAuthorityFooter,
}
|
#![allow(dead_code)]
use crate::base::dff::ClockState::{Tick, Tock};
use crate::base::logic::Word;
use crate::base::{dff::Clock, logic::mux};
use crate::base::{dff::Dff, logic::bit};
#[derive(Debug, Copy, Clone)]
pub struct Bit {
dff: Dff,
}
impl Bit {
pub fn new() -> Self {
Self { dff: Dff::new() }
}
// clock(t), a(t-1), load(t-1)
pub fn input(&mut self, clock_t: &Clock, input: bit, load: bit) {
let clock_t_1 = match clock_t.state {
Tick => {
let mut c = Clock::new();
c.next();
c
}
Tock => Clock::new(),
};
let out_t_1 = self.output(&clock_t_1);
// Save out(t) into DFF
// if load(t-1) then out(t) = in(t-1)
// else out(t) = out(t-1)
self.dff.input(clock_t, mux(out_t_1, input, load));
}
pub fn output(self, clock: &Clock) -> bit {
// Get out(t) from DFF
self.dff.output(clock)
}
pub fn run(&mut self, clock_t: &Clock, input: bit, load: bit) -> bit {
self.input(clock_t, input, load);
self.output(clock_t)
}
}
#[derive(Debug, Clone, Copy)]
pub struct Register {
bits: [Bit; 16],
}
impl Register {
pub fn new() -> Self {
Self {
bits: [Bit::new(); 16],
}
}
pub fn input(&mut self, clock_t: &Clock, input: Word, load: bit) {
self.bits[0].input(clock_t, input[0], load);
self.bits[1].input(clock_t, input[1], load);
self.bits[2].input(clock_t, input[2], load);
self.bits[3].input(clock_t, input[3], load);
self.bits[4].input(clock_t, input[4], load);
self.bits[5].input(clock_t, input[5], load);
self.bits[6].input(clock_t, input[6], load);
self.bits[7].input(clock_t, input[7], load);
self.bits[8].input(clock_t, input[8], load);
self.bits[9].input(clock_t, input[9], load);
self.bits[10].input(clock_t, input[10], load);
self.bits[11].input(clock_t, input[11], load);
self.bits[12].input(clock_t, input[12], load);
self.bits[13].input(clock_t, input[13], load);
self.bits[14].input(clock_t, input[14], load);
self.bits[15].input(clock_t, input[15], load);
}
pub fn output(self, clock: &Clock) -> Word {
Word::new([
self.bits[0].output(clock),
self.bits[1].output(clock),
self.bits[2].output(clock),
self.bits[3].output(clock),
self.bits[4].output(clock),
self.bits[5].output(clock),
self.bits[6].output(clock),
self.bits[7].output(clock),
self.bits[8].output(clock),
self.bits[9].output(clock),
self.bits[10].output(clock),
self.bits[11].output(clock),
self.bits[12].output(clock),
self.bits[13].output(clock),
self.bits[14].output(clock),
self.bits[15].output(clock),
])
}
pub fn run(&mut self, clock_t: &Clock, input: Word, load: bit) -> Word {
self.input(clock_t, input, load);
self.output(clock_t)
}
}
#[cfg(test)]
mod tests {
use super::*;
use bit::{I, O};
#[test]
fn for_bit() {
let mut clock = Clock::new();
let mut bit = Bit::new();
bit.input(&clock, I, I);
// Tick prev: O, cur: I
assert_eq!(bit.output(&clock), O);
clock.next();
bit.input(&clock, O, O);
// Tock prev: I, cur: I load=0の時、cur=prevとなるので古い値がが引き継がれてゆく。保存
assert_eq!(bit.output(&clock), I);
clock.next();
bit.input(&clock, O, O);
// Tick prev: I, cur: I
assert_eq!(bit.output(&clock), I);
clock.next();
bit.input(&clock, O, O);
// Tock prev: I, cur: I
assert_eq!(bit.output(&clock), I);
clock.next();
bit.input(&clock, O, I);
// Tick prev: I, cur: O
assert_eq!(bit.output(&clock), I);
clock.next();
// Tock prev: O, cur: O
bit.input(&clock, O, O);
assert_eq!(bit.output(&clock), O);
}
#[test]
fn for_bit2() {
let mut clock = Clock::new();
let mut bit = Bit::new();
let out1 = bit.run(&clock, I, I);
// Tick prev: O, cur: I
assert_eq!(out1, O);
clock.next();
let out2 = bit.run(&clock, O, O);
// Tock prev: I, cur: I
assert_eq!(out2, I);
clock.next();
let out3 = bit.run(&clock, O, O);
// Tick prev: I, cur: I
assert_eq!(out3, I);
clock.next();
let out4 = bit.run(&clock, O, O);
// Tock prev: I, cur: I
assert_eq!(out4, I);
clock.next();
let out5 = bit.run(&clock, O, I);
// Tick prev: I, cur: O
assert_eq!(out5, I);
clock.next();
// Tock prev: O, cur: O
let out6 = bit.run(&clock, O, O);
assert_eq!(out6, O);
}
#[test]
fn for_register() {
let zero = Word::new([O; 16]);
let one = Word::new([I; 16]);
let mut clock = Clock::new();
let mut register = Register::new();
assert_eq!(register.output(&clock), zero);
register.input(&clock, one, I);
assert_eq!(register.output(&clock), zero);
clock.next();
register.input(&clock, one, O);
assert_eq!(register.output(&clock), one);
clock.next();
register.input(&clock, one, O);
assert_eq!(register.output(&clock), one);
clock.next();
register.input(&clock, zero, O);
assert_eq!(register.output(&clock), one);
clock.next();
register.input(&clock, zero, I);
assert_eq!(register.output(&clock), one);
clock.next();
register.input(&clock, zero, O);
assert_eq!(register.output(&clock), zero);
}
#[test]
fn for_register2() {
let something = Word::new([O, I, O, I, O, I, O, I, O, I, O, I, O, I, O, I]);
let zero = Word::new([O; 16]);
let mut clock = Clock::new();
let mut register = Register::new();
assert_eq!(register.run(&clock, something, I), zero);
clock.next();
assert_eq!(register.run(&clock, something, O), something);
clock.next();
assert_eq!(register.run(&clock, something, O), something);
clock.next();
assert_eq!(register.run(&clock, zero, O), something);
clock.next();
assert_eq!(register.run(&clock, zero, I), something);
clock.next();
assert_eq!(register.run(&clock, zero, O), zero);
}
}
|
extern crate jpeg_decoder as jpeg;
use jpeg::PixelFormat;
use std::io::{BufReader, Read};
pub enum Error {
Jpeg(jpeg::Error),
FormatMismatch,
MetricMismatch,
}
pub fn fuzz(data: impl Read) -> Result<f64, Error> {
let required_width = 32;
let required_height = 32;
let mut decoder = jpeg::Decoder::new(BufReader::new(data));
match decoder.read_info() {
Ok(_) => {}
Err(err) => return Err(Error::Jpeg(err)),
};
let info = match decoder.info() {
Some(info) => info,
None => return Err(Error::FormatMismatch),
};
if info.width != required_width || info.height != required_height
|| info.pixel_format != PixelFormat::RGB24
{
return Err(Error::FormatMismatch);
};
let pixels = match decoder.decode() {
Ok(pixels) => pixels,
Err(err) => return Err(Error::Jpeg(err)),
};
let mut reds: u64 = 0;
for pixel in pixels.chunks(3) {
if let &[r, g, b] = pixel {
if r > 50 && r as u16 >= (2 * g as u16) && r as u16 >= (2 * b as u16) {
reds += 1;
}
}
}
let size = required_width * required_height;
let metric = reds as f64 / size as f64;
if metric > 0.5 {
Ok(metric)
} else {
Err(Error::MetricMismatch)
}
}
|
#![recursion_limit = "128"]
use lazy_static::lazy_static;
use regex::{Captures, Regex};
use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::io::{BufRead, BufReader, BufWriter, Write};
use std::str::FromStr;
mod mapper;
mod scanner;
mod mod_line_scanner;
use mod_line_scanner::*;
mod mod_definition;
use mod_definition::*;
lazy_static! {
static ref MOD_NAME: Regex = Regex::new(
"^\
(?P<prefix>[ \t]*#modname[ \t]+\")\
(?P<name>[^\"]+)\
(?P<suffix>\".*)$\
"
)
.unwrap();
static ref END: Regex = Regex::new("^[ \t]*#end").unwrap();
static ref SPELL_BLOCK_START: Regex = Regex::new("^[ \t]*#(newspell|selectspell)").unwrap();
static ref SPELL_EFFECT: Regex = Regex::new("^\
(?P<prefix>[ \t]*#effect[ \t]+)\
(?P<id>[-]?[[:digit:]]+)\
(?P<suffix>.*)$\
").unwrap();
static ref SPELL_DAMAGE: Regex = Regex::new("^\
(?P<prefix>[ \t]*#damage[ \t]+)\
(?P<id>[-]?[[:digit:]]+)\
(?P<suffix>.*)$\
").unwrap();
static ref SPELL_COPY_ID: Regex = Regex::new("^\
(?P<prefix>[ \t]*#copyspell[ \t]+)\
(?P<id>[-]?[[:digit:]]+)\
(?P<suffix>.*)$\
").unwrap();
static ref SPELL_COPY_NAME: Regex = Regex::new("^\
(?P<prefix>[ \t]*#copyspell[ \t]+\")\
(?P<name>[^\"]+)\
(?P<suffix>\".*)$\
").unwrap();
static ref SPELL_SELECT_ID: Regex = Regex::new("^\
(?P<prefix>[ \t]*#selectspell[ \t]+)\
(?P<id>[-]?[[:digit:]]+)\
(?P<suffix>.*)$\
").unwrap();
static ref SPELL_SELECT_NAME: Regex = Regex::new("^\
(?P<prefix>[ \t]*#selectspell[ \t]+\")\
(?P<name>[^\"]+)\
(?P<suffix>\".*)$\
").unwrap();
static ref MOD_NAME_LINE: Regex = Regex::new("#modname").unwrap();
static ref MOD_ICON_LINE: Regex = Regex::new("#icon").unwrap();
static ref MOD_VERSION_LINE: Regex = Regex::new("#version").unwrap();
static ref MOD_DOMVERSION_LINE: Regex = Regex::new("#domversion").unwrap();
static ref MOD_DESCRIPTION_LINE: Regex = Regex::new("#description[ \t]+\"[^\"]*\"").unwrap();
// n.b. check for `MOD_DESCRIPTION_LINE` first
static ref MOD_DESCRIPTION_START: Regex = Regex::new("#description").unwrap();
// This must be the worst line of code I've ever written lol
static ref MOD_DESCRIPTION_STOP: Regex = Regex::new("\"").unwrap();
static ref SUMMONING_EFFECTS: HashSet<u64> = {
let v = vec![
1, 21, 31, 37, 38, 43, 50, 54, 62, 89, 93, 119, 126, 130, 137,
10001, 10021, 10031, 10037, 10038, 10043, 10050, 10054, 10062, 10089, 10093, 10119, 10126, 10130, 10137];
v.into_iter().collect()
};
static ref ENCHANTMENT_EFFECTS: HashSet<u64> = {
let v = vec![81, 10081, 10082, 10084, 10085, 10086];
v.into_iter().collect()
};
}
// Unfortunately when we encounter a #damage it may refer to a monster, a montag, or an enchantment
// and we can't know until we've also looked at the spell's #effect
pub enum LazyString {
S(String),
// FIXME: does doesn't actually need to be a thunk, could be Ref<Option<String>>
Thunk(Box<dyn Fn() -> String>),
}
impl std::fmt::Debug for LazyString {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Self::S(owned) => owned.fmt(f),
Self::Thunk(boxed_fn) => (boxed_fn)().fmt(f),
}
}
}
fn main() {
println!(
r#"
___ ___ _____ __ ___ __ __ __
/ \/___\/\/\ \_ \/\ \ \/ _ \ / / /__\/__\
/ /\ // // \ / /\/ \/ / /_\// / /_\ / \//
/ /_// \_// /\/\ \/\/ /_/ /\ / /_\\/ /___//__/ _ \
/___,'\___/\/ \/\____/\_\ \/\____/\____/\__/\/ \_/
Domingler will scan the folder you put it in.
This probably needs to be your dominions mods folder
which can be opened from ingame via Tools & Manuals.
However you can also make a specific folder containing
only the mods that you want to mingle.
Press [enter] to continue..."#
);
{
let stdin = std::io::stdin();
let _ = stdin.lock().lines().next().unwrap().unwrap();
}
let mut mod_file_paths: Vec<String> = vec![];
let current_dir_contents = std::fs::read_dir(".").unwrap();
for result_current_dir_item in current_dir_contents {
if let Ok(current_dir_item) = result_current_dir_item {
let file_name = current_dir_item.file_name();
let file_path: &std::path::Path = file_name.as_ref();
if let Some(extension) = file_path.extension() {
if extension == "dm" {
if let Some(file_name) = file_path.file_stem() {
if file_name != "domingler" {
mod_file_paths.push(file_path.to_str().unwrap().to_owned());
} else {
println!("Ignoring domingler.dm");
}
}
}
}
}
}
println!("Found files:");
for mod_file_path in &mod_file_paths {
println!(" - {}", mod_file_path);
}
println!();
println!("Press [enter] to parse files...");
{
let stdin = std::io::stdin();
let _ = stdin.lock().lines().next().unwrap().unwrap();
}
// TODO: no real point loading these all into memory
let mod_files: Vec<(String, Vec<String>)> = mod_file_paths.iter()
.map(|path| {
let file = File::open(path).unwrap();
let file_buff = BufReader::new(file);
let line_iter = file_buff.lines().map(|result| {
match result {
Ok(x) => x,
Err(e) => {
println!("Mod '{}' was not valid UTF-8 and domingler cannot read it until its encoding is changed.", path);
println!("Press any key to quit...");
{
let stdin = std::io::stdin();
let _ = stdin.lock().lines().next().unwrap().unwrap();
}
panic!("Mod '{}' was not valid UTF-8 and domingler cannot read it until its encoding is changed.", path);
}
}
});
let lines: Vec<String> = line_iter.collect();
(path.to_owned(), lines)
})
.collect();
let parsed_mods = scanner::scan_all_mods(&mod_files);
scanner::print_mod_id_usages(&parsed_mods);
println!("Press [enter] to generate domingler.dm out of the scanned mods...");
{
let stdin = std::io::stdin();
let _ = stdin.lock().lines().next().unwrap().unwrap();
}
let remapped_ids = mapper::remap_ids(&parsed_mods);
// TODO: add the mod names to the description
let mut lines: Vec<LazyString> = vec![
LazyString::S("#modname \"domingler mod\"".to_owned()),
LazyString::S(format!(
"#description \"a combination of: some shit or whatever\""
)),
];
// TODO: pick an era and then also map all nations to same era?
mapper::apply_remapped_ids(&mut lines, &remapped_ids);
let new_file = File::create("./domingler.dm").unwrap();
let mut writer = BufWriter::new(new_file);
for line in lines {
match line {
LazyString::S(line_string) => write!(&mut writer, "{}\n", line_string).unwrap(),
LazyString::Thunk(line_fn) => write!(&mut writer, "{}\n", line_fn()).unwrap(),
}
}
println!();
println!("Successfully created domingler.dm!");
println!("If you got warnings about copyspell above, you will need");
println!("to manually edit those lines. You may also want to edit");
println!("the nation's eras to be the same.");
println!("Press [enter] to exit.");
{
let stdin = std::io::stdin();
let _ = stdin.lock().lines().next().unwrap().unwrap();
}
}
fn replace_use(line: &str, map: &HashMap<u32, u32>, regex: &Regex) -> Option<String> {
if let Some(capture) = regex.captures(&line) {
let found_id = u32::from_str(capture.name("id").unwrap().as_str()).unwrap();
if let Some(new_id) = map.get(&found_id) {
let new_line: String = regex
.replace(&line, |ref captures: &Captures| -> String {
format!("{}{}{}", &captures["prefix"], new_id, &captures["suffix"])
})
.to_string();
Some(new_line)
} else {
Some(line.to_owned())
}
} else {
None
}
}
|
use cpal::EventLoop;
use cpal::{StreamData, UnknownTypeOutputBuffer};
fn main() {
println!("Hello, world!");
let event_loop = EventLoop::new();
let device = cpal::default_output_device().expect("No output device available");
let mut supported_formats_range = device
.supported_output_formats()
.expect("error while querying formats");
let format = supported_formats_range
.next()
.expect("no supported formats?!")
.with_max_sample_rate();
println!("{:?}", &format);
let stream_id = event_loop.build_output_stream(&device, &format).unwrap();
event_loop.play_stream(stream_id);
let sample_rate = 1.0 / format.sample_rate.0 as f32;
let freq = 440.0; //Hz
let increment = 2.0 * std::f32::consts::PI * freq * sample_rate;
let volume = 0.5;
let mut counter: f32 = 0.0;
let mut is_right = false;
// This will lock up your thread, so should be moved to a different thread
event_loop.run(move |_stream_id, stream_data| match stream_data {
StreamData::Output {
buffer: UnknownTypeOutputBuffer::U16(mut buffer),
} => {
for elem in buffer.iter_mut() {
let target = counter.sin() * volume;
let half = (u16::max_value() / 2) as f32;
let val = (half + half * target) as u16;
if is_right {
*elem = val;
counter += increment;
} else {
*elem = half as u16;
}
is_right = !is_right;
}
}
StreamData::Output {
buffer: UnknownTypeOutputBuffer::I16(mut buffer),
} => {
for elem in buffer.iter_mut() {
let target = counter.sin() * volume;
let val = (target * i16::max_value() as f32) as i16;
if is_right {
*elem = val;
counter += increment;
} else {
*elem = 0;
}
is_right = !is_right;
}
}
StreamData::Output {
buffer: UnknownTypeOutputBuffer::F32(mut buffer),
} => {
for elem in buffer.iter_mut() {
let target = counter.sin() * volume;
if is_right {
*elem = target;
counter += increment;
} else {
*elem = 0.0;
}
is_right = !is_right;
}
}
_ => (),
});
}
|
#![allow(dead_code)]
use std::io;
use std::io::prelude::*;
mod evaluator;
mod object;
mod reader;
fn main() -> io::Result<()> {
const PROMPT: &str = "> ";
loop {
print!("{}", PROMPT);
io::stdout().flush()?;
let mut input = String::new();
io::stdin().read_line(&mut input)?;
match reader::read(&input) {
Ok(objects) => {
objects.iter().for_each(|object| println!("{}", object));
}
Err(e) => println!("Something went wrong: {}", e),
};
}
}
|
// cargo run --bin zmq_reply
#[macro_use]
extern crate json;
fn main() {
let context = zmq::Context::new();
let responder = context.socket(zmq::REP).unwrap();
assert!(responder.bind("tcp://*:5555").is_ok());
let mut msg = zmq::Message::new();
loop {
responder.recv(&mut msg, 0).unwrap();
let request = json::parse(msg.as_str().unwrap()).unwrap();
let length = request["string"].as_str().unwrap().len();
let response = object!{
"length": length
};
responder.send(json::stringify(response).as_bytes(), 0).unwrap();
}
}
|
use crate::Error;
pub fn register_app(app: super::Application) -> Result<(), Error> {
use super::LaunchCommand;
fn inner(app: super::Application) -> anyhow::Result<()> {
use anyhow::Context as _;
use winreg::{enums::HKEY_CURRENT_USER, RegKey};
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
let mut icon_path = std::env::current_exe()
.context("unable to retrieve current executable path")?
.into_os_string();
let command = match app.command {
LaunchCommand::Bin { path, args } => {
icon_path = path.clone().into();
super::create_command(path, args, "\"%1\"")
}
LaunchCommand::Url(url) => {
// Unfortunately it doesn't seem like we can just forward one
// url to another, so we actually have to lookup the command
// for the registered handler for the scheme and copy it
let handler = format!(r#"Software\Classes\{}\shell\open\command"#, url.scheme());
let key = hkcu.open_subkey(&handler).with_context(|| {
format!("the '{}' scheme hasn't been registered", url.scheme())
})?;
let command: String = key.get_value("").with_context(|| {
format!("unable to read value for '{}' scheme", url.scheme())
})?;
// The registered scheme handler should be pointing at an executable
// so we retrieve that to use as the icon path, instead of the default
// of using the path of the current executable
let exe_path = match command.strip_prefix('"') {
Some(cmd) => {
match cmd.find('"') {
Some(ind) => cmd[..ind].to_owned(),
None => {
// If there's not a closing quote just assume something
// is wrong and return the whole string
command.clone()
}
}
}
None => command.split(' ').next().unwrap().to_owned(),
};
icon_path = exe_path.into();
command
}
LaunchCommand::Steam(steam_id) => {
let key = hkcu
.open_subkey(r#"Software\Valve\Steam"#)
.context("unable to locate Steam registry entry")?;
let steam_path: String = key
.get_value("SteamExe")
.context("unable to locate path to steam executable")?;
// The Discord RPC lib does this, but seems a bit weird that
// Steam would potentially write it in a way that would break
// random stuff requiring windows path separators, but who knows!
let steam_path = steam_path.replace('/', "\\");
format!(r#""{}" steam://rungameid/{}"#, steam_path, steam_id)
}
};
let id = app.id;
let discord_handler = format!(r#"Software\Classes\discord-{}"#, id);
let (disc_key, _disp) = hkcu
.create_subkey(&discord_handler)
.context("unable to create discord handler")?;
let name = app.name.unwrap_or_else(|| id.to_string());
disc_key.set_value("", &format!("URL:Run {} protocol", name))?;
disc_key.set_value("URL Protocol", &"")?;
icon_path.push(",0");
disc_key.set_value("DefaultIcon", &&*icon_path)?;
let (open_key, _disp) = disc_key
.create_subkey(r#"shell\open\command"#)
.context("unable to create open key")?;
open_key.set_value("", &command)?;
Ok(())
}
inner(app).map_err(Error::AppRegistration)
}
|
use async_trait::async_trait;
use rbatis::core::db::DBExecResult;
use rbatis::core::Result;
use rbatis::crud::{CRUD, CRUDTable};
use rbatis::plugin::page::{IPageRequest, Page};
use rbatis::rbatis::Rbatis;
use rbatis::wrapper::Wrapper;
use serde::{de, Deserialize, Deserializer, Serializer};
use serde::de::Unexpected;
pub use crate::ma::data::{MTokenAddress, TxShared};
pub use crate::ma::data_eth::{EthErc20Face, MEthChainToken, MEthChainTx, MEthErc20Tx};
pub use crate::ma::detail::{MTokenShared, MWallet};
pub use crate::ma::detail_eth::{MEthChainTokenAuth, MEthChainTokenDefault};
pub use crate::ma::mnemonic::MMnemonic;
pub trait Shared {
fn get_id(&self) -> String;
fn set_id(&mut self, id: String);
fn get_create_time(&self) -> i64;
fn set_create_time(&mut self, create_time: i64);
fn get_update_time(&self) -> i64;
fn set_update_time(&mut self, update_time: i64);
}
pub trait BeforeSave {
fn before_save(&mut self);
}
pub trait BeforeUpdate {
fn before_update(&mut self);
}
#[async_trait]
pub trait Dao<T: CRUDTable + Shared> {
/// 调用 before_save 然后 insert 到数据 database,
async fn save(&mut self, rb: &rbatis::rbatis::Rbatis, tx_id: &str) -> Result<DBExecResult>;
/// 调用 before_save 然后 insert 到数据 database,
async fn save_batch(rb: &rbatis::rbatis::Rbatis, tx_id: &str, ms: &mut [T]) -> Result<DBExecResult>;
/// 如果id为空,调用save,
/// 如果id不为空,调用update_by_id, 且 last_insert_id为none
async fn save_update(&mut self, rb: &rbatis::rbatis::Rbatis, tx_id: &str) -> Result<DBExecResult>;
async fn remove_by_wrapper(rb: &rbatis::rbatis::Rbatis, tx_id: &str, w: &Wrapper) -> Result<u64> where T: 'async_trait;
async fn remove_by_id(rb: &rbatis::rbatis::Rbatis, tx_id: &str, id: &T::IdType) -> Result<u64> where T: 'async_trait;
async fn remove_batch_by_id(rb: &rbatis::rbatis::Rbatis, tx_id: &str, ids: &[T::IdType]) -> Result<u64> where T: 'async_trait;
/// 调用 before_update 然后 update 到数据 database,
async fn update_by_wrapper(&mut self, rb: &rbatis::rbatis::Rbatis, tx_id: &str, w: &Wrapper, update_null_value: bool) -> Result<u64>;
/// 调用 before_update 然后 update 到数据 database,
async fn update_by_id(&mut self, rb: &rbatis::rbatis::Rbatis, tx_id: &str) -> Result<u64>;
/// 调用 before_update 然后 update 到数据 database,
async fn update_batch_by_id(rb: &rbatis::rbatis::Rbatis, tx_id: &str, ids: &mut [T]) -> Result<u64>;
/// 查询唯一的一条记录,如果记录大于1条或没有,都会报错
async fn fetch_by_wrapper(rb: &rbatis::rbatis::Rbatis, tx_id: &str, w: &Wrapper) -> Result<Option<T>> where T: 'async_trait;
/// 查询唯一的一条记录,如果记录大于1条或没有,都会报错
async fn fetch_by_id(rb: &rbatis::rbatis::Rbatis, tx_id: &str, id: &T::IdType) -> Result<Option<T>> where T: 'async_trait;
async fn fetch_page_by_wrapper(rb: &rbatis::rbatis::Rbatis, tx_id: &str, w: &Wrapper, page: &dyn IPageRequest) -> Result<Page<T>> where T: 'async_trait;
///fetch all record
async fn list(rb: &rbatis::rbatis::Rbatis, tx_id: &str) -> Result<Vec<T>> where T: 'async_trait;
async fn list_by_wrapper(rb: &rbatis::rbatis::Rbatis, tx_id: &str, w: &Wrapper) -> Result<Vec<T>> where T: 'async_trait;
async fn list_by_ids(rb: &rbatis::rbatis::Rbatis, tx_id: &str, ids: &[T::IdType]) -> Result<Vec<T>> where T: 'async_trait;
///使用 exist检查是否有数据
async fn exist_by_wrapper(rb: &rbatis::rbatis::Rbatis, tx_id: &str, w: &Wrapper) -> Result<bool> where T: 'async_trait;
///使用count计算数据的条数
async fn count_by_wrapper(rb: &rbatis::rbatis::Rbatis, tx_id: &str, w: &Wrapper) -> Result<i64> where T: 'async_trait;
}
#[async_trait]
impl<T> Dao<T> for T where
T: CRUDTable + Shared + BeforeSave + BeforeUpdate,
{
async fn save(&mut self, rb: &Rbatis, tx_id: &str) -> Result<DBExecResult> {
self.before_save();
rb.save(tx_id, self).await
}
async fn save_batch(rb: &Rbatis, tx_id: &str, ms: &mut [T]) -> Result<DBExecResult> {
for it in ms.iter_mut() {
it.before_save();
}
rb.save_batch(tx_id, ms).await
}
async fn save_update(&mut self, rb: &rbatis::rbatis::Rbatis, tx_id: &str) -> Result<DBExecResult> {
if Shared::get_id(self).is_empty() {
self.save(rb, tx_id).await
} else {
let r = self.update_by_id(rb, tx_id).await?;
Ok(DBExecResult {
rows_affected: r,
last_insert_id: None,
})
}
}
async fn remove_by_wrapper(rb: &Rbatis, tx_id: &str, w: &Wrapper) -> Result<u64> where T: 'async_trait {
// self.set_update_time(kits::now_ts_seconds());
rb.remove_by_wrapper::<T>(tx_id, w).await
}
async fn remove_by_id(rb: &Rbatis, tx_id: &str, id: &T::IdType) -> Result<u64> where T: 'async_trait {
rb.remove_by_id::<T>(tx_id, id).await
}
async fn remove_batch_by_id(rb: &Rbatis, tx_id: &str, ids: &[T::IdType]) -> Result<u64> where T: 'async_trait {
rb.remove_batch_by_id::<T>(tx_id, ids).await
}
async fn update_by_wrapper(&mut self, rb: &Rbatis, tx_id: &str, w: &Wrapper, update_null_value: bool) -> Result<u64> {
self.before_update();
rb.update_by_wrapper(tx_id, self, w, update_null_value).await
}
async fn update_by_id(&mut self, rb: &Rbatis, tx_id: &str) -> Result<u64> {
self.before_update();
rb.update_by_id(tx_id, self).await
}
async fn update_batch_by_id(rb: &Rbatis, tx_id: &str, ids: &mut [T]) -> Result<u64> {
for it in ids.iter_mut() {
it.before_update();
}
rb.update_batch_by_id(tx_id, ids).await
}
async fn fetch_by_wrapper(rb: &Rbatis, tx_id: &str, w: &Wrapper) -> Result<Option<T>> where T: 'async_trait {
rb.fetch_by_wrapper(tx_id, w).await
}
async fn fetch_by_id(rb: &Rbatis, tx_id: &str, id: &T::IdType) -> Result<Option<T>> where T: 'async_trait {
rb.fetch_by_id(tx_id, id).await
}
async fn fetch_page_by_wrapper(rb: &Rbatis, tx_id: &str, w: &Wrapper, page: &dyn IPageRequest) -> Result<Page<T>> where T: 'async_trait {
rb.fetch_page_by_wrapper(tx_id, w, page).await
}
async fn list(rb: &Rbatis, tx_id: &str) -> Result<Vec<T>> where T: 'async_trait {
rb.fetch_list(tx_id).await
// rb.list(tx_id).await
}
async fn list_by_wrapper(rb: &Rbatis, tx_id: &str, w: &Wrapper) -> Result<Vec<T>> where T: 'async_trait {
rb.fetch_list_by_wrapper(tx_id, w).await
}
async fn list_by_ids(rb: &Rbatis, tx_id: &str, ids: &[T::IdType]) -> Result<Vec<T>> where T: 'async_trait {
rb.fetch_list_by_ids(tx_id, ids).await
}
async fn exist_by_wrapper(rb: &rbatis::rbatis::Rbatis, tx_id: &str, w: &Wrapper) -> Result<bool> where T: 'async_trait {
let w = w.clone();
let sql = {
if w.sql.is_empty() {
format!("SELECT EXISTS ( SELECT 1 FROM {} )", T::table_name())
} else {
format!("SELECT EXISTS ( SELECT 1 FROM {} WHERE {} )", T::table_name(), w.sql)
}
};
let re: i32 = rb.fetch_prepare(tx_id, &sql, &w.args).await?;
Ok(re != 0)
}
async fn count_by_wrapper(rb: &rbatis::rbatis::Rbatis, tx_id: &str, w: &Wrapper) -> Result<i64> where T: 'async_trait {
let w = w.clone();
let sql = {
if w.sql.is_empty() {
format!("SELECT COUNT(*) FROM {} ", T::table_name())
} else {
format!("SELECT COUNT(*) FROM {} WHERE {} ", T::table_name(), w.sql)
}
};
let re: i64 = rb.fetch_prepare(tx_id, &sql, &w.args).await?;
Ok(re)
}
}
pub fn bool_from_u32<'de, D>(deserializer: D) -> std::result::Result<bool, D::Error>
where D: Deserializer<'de>,
{
match u32::deserialize(deserializer)? {
crate::CFalse => Ok(false),
crate::CTrue => Ok(true),
other => Err(de::Error::invalid_value(
Unexpected::Unsigned(other as u64),
&"zero or one",
)),
}
}
pub fn bool_to_u32<S>(x: &bool, s: S) -> std::result::Result<S::Ok, S::Error>
where S: Serializer,
{
let b = {
if *x {
crate::CTrue
} else {
crate::CFalse
}
};
s.serialize_u32(b)
} |
pub mod graphics;
pub mod printer;
mod scripting;
pub use scripting::*;
|
use std::io::{Read, Result as IOResult};
use crate::PrimitiveRead;
#[derive(Clone)]
pub struct BoneWeight {
pub weight: [f32; 3],
pub bone: [i8; 3],
pub bones_count: u8,
}
impl BoneWeight {
pub fn read(read: &mut dyn Read) -> IOResult<Self> {
let weight = [ read.read_f32()?, read.read_f32()?, read.read_f32()? ];
let bone = [ read.read_i8()?, read.read_i8()?, read.read_i8()? ];
let bones_count = read.read_u8()?;
Ok(Self {
weight,
bone,
bones_count
})
}
}
|
#[doc = "Reader of register DSI_VMCCR"]
pub type R = crate::R<u32, super::DSI_VMCCR>;
#[doc = "Reader of field `VMT`"]
pub type VMT_R = crate::R<u8, u8>;
#[doc = "Reader of field `LPVSAE`"]
pub type LPVSAE_R = crate::R<bool, bool>;
#[doc = "Reader of field `LPVBPE`"]
pub type LPVBPE_R = crate::R<bool, bool>;
#[doc = "Reader of field `LPVFPE`"]
pub type LPVFPE_R = crate::R<bool, bool>;
#[doc = "Reader of field `LPVAE`"]
pub type LPVAE_R = crate::R<bool, bool>;
#[doc = "Reader of field `LPHBPE`"]
pub type LPHBPE_R = crate::R<bool, bool>;
#[doc = "Reader of field `LPHFE`"]
pub type LPHFE_R = crate::R<bool, bool>;
#[doc = "Reader of field `FBTAAE`"]
pub type FBTAAE_R = crate::R<bool, bool>;
#[doc = "Reader of field `LPCE`"]
pub type LPCE_R = crate::R<bool, bool>;
impl R {
#[doc = "Bits 0:1 - Video mode Type"]
#[inline(always)]
pub fn vmt(&self) -> VMT_R {
VMT_R::new((self.bits & 0x03) as u8)
}
#[doc = "Bit 2 - Low-Power Vertical Sync time Enable"]
#[inline(always)]
pub fn lpvsae(&self) -> LPVSAE_R {
LPVSAE_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - Low-power Vertical Back-Porch Enable"]
#[inline(always)]
pub fn lpvbpe(&self) -> LPVBPE_R {
LPVBPE_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - Low-power Vertical Front-Porch Enable"]
#[inline(always)]
pub fn lpvfpe(&self) -> LPVFPE_R {
LPVFPE_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - Low-Power Vertical Active Enable"]
#[inline(always)]
pub fn lpvae(&self) -> LPVAE_R {
LPVAE_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - Low-power Horizontal Back-Porch Enable"]
#[inline(always)]
pub fn lphbpe(&self) -> LPHBPE_R {
LPHBPE_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 7 - Low-Power Horizontal Front-Porch Enable"]
#[inline(always)]
pub fn lphfe(&self) -> LPHFE_R {
LPHFE_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 8 - Frame BTA Acknowledge Enable"]
#[inline(always)]
pub fn fbtaae(&self) -> FBTAAE_R {
FBTAAE_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 9 - Low-Power Command Enable"]
#[inline(always)]
pub fn lpce(&self) -> LPCE_R {
LPCE_R::new(((self.bits >> 9) & 0x01) != 0)
}
}
|
// #![feature(existential_type)]
// #![feature(impl_trait_in_bindings)]
//! A toolkit for the construction and use of hexagonal maps,
//! e.g. in the context of game programming.
pub mod geo;
pub mod grid;
pub mod ui;
pub mod search;
|
use std::io::{stdin};
use num_derive::{FromPrimitive, ToPrimitive};
use num_traits::{FromPrimitive};
#[derive(FromPrimitive, ToPrimitive, Debug)]
enum ParameterMode {
Position = 0,
Immediate = 1,
}
#[derive(FromPrimitive, Debug)]
enum Opcode {
Add = 1,
Multiply = 2,
Input = 3,
Output = 4,
JumpIfTrue = 5,
JumpIfFalse = 6,
LessThan = 7,
Equals = 8,
Quit = 99,
}
fn parameter_count(opcode: &Opcode) -> u32 {
match opcode {
Opcode::Add => 2,
Opcode::Multiply => 2,
Opcode::Input => 0,
Opcode::Output => 1,
Opcode::JumpIfTrue => 2,
Opcode::JumpIfFalse => 2,
Opcode::LessThan => 2,
Opcode::Equals => 2,
Opcode::Quit => 0,
}
}
// TODO: make an enum containing typed parameters
// TODO: try intoiter
fn parse_instruction(input: i32) -> (Vec<ParameterMode>, Opcode) {
let opcode = Opcode::from_i32(input % 100).expect("Invalid Opcode");
let modes = (0..parameter_count(&opcode))
.map(|i|
ParameterMode::from_i32(1 & (input / (100 * 10i32.pow(i))))
.expect("Invalid Parameter Mode"))
.collect();
(modes, opcode)
}
fn parameters(parameter_modes: &[ParameterMode], data: &[i32], ip: usize) -> Vec<i32> {
parameter_modes.iter().enumerate().map(|(i, x)| {
match x {
ParameterMode::Position => data[data[ip + i] as usize],
ParameterMode::Immediate => data[ip + i],
}
}).collect()
}
fn parse_data(input: &str) -> Result<Vec<i32>, String> {
if let Ok(data) = input.trim().split(',').map(|x|x.parse::<i32>()).collect() {
return Ok(data)
}
Err(format!("Unable to parse program input: {}", input))
}
fn main() {
let mut data = match std::env::args().nth(1) {
Some(input) => {
parse_data(&input).unwrap()
},
None => {
parse_data(include_str!("../data/data.txt")).unwrap()
}
};
let mut ip = 0;
loop {
let (parameter_modes, opcode) = parse_instruction(data[ip]);
ip += 1;
let parameters = parameters(¶meter_modes, &data, ip);
ip += parameters.len();
match opcode {
Opcode::Add => {
let dst = data[ip] as usize;
data[dst] = parameters[0] + parameters[1];
ip += 1;
},
Opcode::Multiply => {
let dst = data[ip] as usize;
data[dst] = parameters[0] * parameters[1];
ip += 1;
},
Opcode::Input => {
let dst = data[ip] as usize;
let mut input_buffer = String::new();
stdin().read_line(&mut input_buffer).expect("Unable to read user input");
data[dst] = input_buffer.trim().parse::<i32>().expect(&format!("Unable to read user integer({}):", input_buffer));
ip += 1;
},
Opcode::Output => {
println!("{}", parameters[0]);
},
Opcode::JumpIfTrue => {
if parameters[0] != 0 { ip = parameters[1] as usize }
},
Opcode::JumpIfFalse => {
if parameters[0] == 0 { ip = parameters[1] as usize }
},
Opcode::LessThan => {
let dst = data[ip] as usize;
data[dst] = (parameters[0] < parameters[1]) as i32;
ip += 1;
},
Opcode::Equals => {
let dst = data[ip] as usize;
data[dst] = (parameters[0] == parameters[1]) as i32;
ip += 1;
},
Opcode::Quit => break,
}
}
}
|
use super::{PyDict, PyDictRef, PyList, PyStr, PyStrRef, PyType, PyTypeRef};
use crate::common::hash::PyHash;
use crate::{
class::PyClassImpl,
function::{Either, FuncArgs, PyArithmeticValue, PyComparisonValue, PySetterValue},
types::{Constructor, PyComparisonOp},
AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyResult, VirtualMachine,
};
use itertools::Itertools;
/// object()
/// --
///
/// The base class of the class hierarchy.
///
/// When called, it accepts no arguments and returns a new featureless
/// instance that has no instance attributes and cannot be given any.
#[pyclass(module = false, name = "object")]
#[derive(Debug)]
pub struct PyBaseObject;
impl PyPayload for PyBaseObject {
fn class(ctx: &Context) -> &'static Py<PyType> {
ctx.types.object_type
}
}
impl Constructor for PyBaseObject {
type Args = FuncArgs;
fn py_new(cls: PyTypeRef, _args: Self::Args, vm: &VirtualMachine) -> PyResult {
// more or less __new__ operator
let dict = if cls.is(vm.ctx.types.object_type) {
None
} else {
Some(vm.ctx.new_dict())
};
// Ensure that all abstract methods are implemented before instantiating instance.
if let Some(abs_methods) = cls.get_attr(identifier!(vm, __abstractmethods__)) {
if let Some(unimplemented_abstract_method_count) = abs_methods.length_opt(vm) {
let methods: Vec<PyStrRef> = abs_methods.try_to_value(vm)?;
let methods: String =
Itertools::intersperse(methods.iter().map(|name| name.as_str()), ", ")
.collect();
let unimplemented_abstract_method_count = unimplemented_abstract_method_count?;
let name = cls.name().to_string();
match unimplemented_abstract_method_count {
0 => {}
1 => {
return Err(vm.new_type_error(format!(
"Can't instantiate abstract class {} with abstract method {}",
name, methods
)));
}
2.. => {
return Err(vm.new_type_error(format!(
"Can't instantiate abstract class {} with abstract methods {}",
name, methods
)));
}
_ => unreachable!("unimplemented_abstract_method_count is always positive"),
}
}
}
Ok(crate::PyRef::new_ref(PyBaseObject, cls, dict).into())
}
}
#[pyclass(with(Constructor), flags(BASETYPE))]
impl PyBaseObject {
#[pyslot]
fn slot_richcompare(
zelf: &PyObject,
other: &PyObject,
op: PyComparisonOp,
vm: &VirtualMachine,
) -> PyResult<Either<PyObjectRef, PyComparisonValue>> {
Self::cmp(zelf, other, op, vm).map(Either::B)
}
#[inline(always)]
fn cmp(
zelf: &PyObject,
other: &PyObject,
op: PyComparisonOp,
vm: &VirtualMachine,
) -> PyResult<PyComparisonValue> {
let res = match op {
PyComparisonOp::Eq => {
if zelf.is(other) {
PyComparisonValue::Implemented(true)
} else {
PyComparisonValue::NotImplemented
}
}
PyComparisonOp::Ne => {
let cmp = zelf
.class()
.mro_find_map(|cls| cls.slots.richcompare.load())
.unwrap();
let value = match cmp(zelf, other, PyComparisonOp::Eq, vm)? {
Either::A(obj) => PyArithmeticValue::from_object(vm, obj)
.map(|obj| obj.try_to_bool(vm))
.transpose()?,
Either::B(value) => value,
};
value.map(|v| !v)
}
_ => PyComparisonValue::NotImplemented,
};
Ok(res)
}
/// Return self==value.
#[pymethod(magic)]
fn eq(
zelf: PyObjectRef,
value: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<PyComparisonValue> {
Self::cmp(&zelf, &value, PyComparisonOp::Eq, vm)
}
/// Return self!=value.
#[pymethod(magic)]
fn ne(
zelf: PyObjectRef,
value: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<PyComparisonValue> {
Self::cmp(&zelf, &value, PyComparisonOp::Ne, vm)
}
/// Return self<value.
#[pymethod(magic)]
fn lt(
zelf: PyObjectRef,
value: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<PyComparisonValue> {
Self::cmp(&zelf, &value, PyComparisonOp::Lt, vm)
}
/// Return self<=value.
#[pymethod(magic)]
fn le(
zelf: PyObjectRef,
value: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<PyComparisonValue> {
Self::cmp(&zelf, &value, PyComparisonOp::Le, vm)
}
/// Return self>=value.
#[pymethod(magic)]
fn ge(
zelf: PyObjectRef,
value: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<PyComparisonValue> {
Self::cmp(&zelf, &value, PyComparisonOp::Ge, vm)
}
/// Return self>value.
#[pymethod(magic)]
fn gt(
zelf: PyObjectRef,
value: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<PyComparisonValue> {
Self::cmp(&zelf, &value, PyComparisonOp::Gt, vm)
}
/// Implement setattr(self, name, value).
#[pymethod]
fn __setattr__(
obj: PyObjectRef,
name: PyStrRef,
value: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<()> {
obj.generic_setattr(&name, PySetterValue::Assign(value), vm)
}
/// Implement delattr(self, name).
#[pymethod]
fn __delattr__(obj: PyObjectRef, name: PyStrRef, vm: &VirtualMachine) -> PyResult<()> {
obj.generic_setattr(&name, PySetterValue::Delete, vm)
}
#[pyslot]
fn slot_setattro(
obj: &PyObject,
attr_name: &Py<PyStr>,
value: PySetterValue,
vm: &VirtualMachine,
) -> PyResult<()> {
obj.generic_setattr(attr_name, value, vm)
}
/// Return str(self).
#[pymethod(magic)]
fn str(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyStrRef> {
// FIXME: try tp_repr first and fallback to object.__repr__
zelf.repr(vm)
}
#[pyslot]
fn slot_repr(zelf: &PyObject, vm: &VirtualMachine) -> PyResult<PyStrRef> {
let class = zelf.class();
match (
class
.qualname(vm)
.downcast_ref::<PyStr>()
.map(|n| n.as_str()),
class.module(vm).downcast_ref::<PyStr>().map(|m| m.as_str()),
) {
(None, _) => Err(vm.new_type_error("Unknown qualified name".into())),
(Some(qualname), Some(module)) if module != "builtins" => Ok(PyStr::from(format!(
"<{}.{} object at {:#x}>",
module,
qualname,
zelf.get_id()
))
.into_ref(&vm.ctx)),
_ => Ok(PyStr::from(format!(
"<{} object at {:#x}>",
class.slot_name(),
zelf.get_id()
))
.into_ref(&vm.ctx)),
}
}
/// Return repr(self).
#[pymethod(magic)]
fn repr(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyStrRef> {
Self::slot_repr(&zelf, vm)
}
#[pyclassmethod(magic)]
fn subclasshook(_args: FuncArgs, vm: &VirtualMachine) -> PyObjectRef {
vm.ctx.not_implemented()
}
#[pyclassmethod(magic)]
fn init_subclass(_cls: PyTypeRef) {}
#[pymethod(magic)]
pub fn dir(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyList> {
let attributes = obj.class().get_attributes();
let dict = PyDict::from_attributes(attributes, vm)?.into_ref(&vm.ctx);
// Get instance attributes:
if let Some(object_dict) = obj.dict() {
vm.call_method(
dict.as_object(),
identifier!(vm, update).as_str(),
(object_dict,),
)?;
}
let attributes: Vec<_> = dict.into_iter().map(|(k, _v)| k).collect();
Ok(PyList::from(attributes))
}
#[pymethod(magic)]
fn format(obj: PyObjectRef, format_spec: PyStrRef, vm: &VirtualMachine) -> PyResult<PyStrRef> {
if !format_spec.is_empty() {
return Err(vm.new_type_error(format!(
"unsupported format string passed to {}.__format__",
obj.class().name()
)));
}
obj.str(vm)
}
#[pyslot]
#[pymethod(magic)]
fn init(_zelf: PyObjectRef, _args: FuncArgs, _vm: &VirtualMachine) -> PyResult<()> {
Ok(())
}
#[pygetset(name = "__class__")]
fn get_class(obj: PyObjectRef) -> PyTypeRef {
obj.class().to_owned()
}
#[pygetset(name = "__class__", setter)]
fn set_class(instance: PyObjectRef, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
if instance.payload_is::<PyBaseObject>() {
match value.downcast::<PyType>() {
Ok(cls) => {
// FIXME(#1979) cls instances might have a payload
instance.set_class(cls, vm);
Ok(())
}
Err(value) => {
let value_class = value.class();
let type_repr = &value_class.name();
Err(vm.new_type_error(format!(
"__class__ must be set to a class, not '{type_repr}' object"
)))
}
}
} else {
Err(vm.new_type_error(
"__class__ assignment only supported for types without a payload".to_owned(),
))
}
}
/// Return getattr(self, name).
#[pyslot]
pub(crate) fn getattro(obj: &PyObject, name: &Py<PyStr>, vm: &VirtualMachine) -> PyResult {
vm_trace!("object.__getattribute__({:?}, {:?})", obj, name);
obj.as_object().generic_getattr(name, vm)
}
#[pymethod(magic)]
fn getattribute(obj: PyObjectRef, name: PyStrRef, vm: &VirtualMachine) -> PyResult {
Self::getattro(&obj, &name, vm)
}
#[pymethod(magic)]
fn reduce(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult {
common_reduce(obj, 0, vm)
}
#[pymethod(magic)]
fn reduce_ex(obj: PyObjectRef, proto: usize, vm: &VirtualMachine) -> PyResult {
let __reduce__ = identifier!(vm, __reduce__);
if let Some(reduce) = vm.get_attribute_opt(obj.clone(), __reduce__)? {
let object_reduce = vm.ctx.types.object_type.get_attr(__reduce__).unwrap();
let typ_obj: PyObjectRef = obj.class().to_owned().into();
let class_reduce = typ_obj.get_attr(__reduce__, vm)?;
if !class_reduce.is(&object_reduce) {
return reduce.call((), vm);
}
}
common_reduce(obj, proto, vm)
}
#[pyslot]
fn slot_hash(zelf: &PyObject, _vm: &VirtualMachine) -> PyResult<PyHash> {
Ok(zelf.get_id() as _)
}
/// Return hash(self).
#[pymethod(magic)]
fn hash(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyHash> {
Self::slot_hash(&zelf, vm)
}
#[pymethod(magic)]
fn sizeof(zelf: PyObjectRef) -> usize {
zelf.class().slots.basicsize
}
}
pub fn object_get_dict(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyDictRef> {
obj.dict()
.ok_or_else(|| vm.new_attribute_error("This object has no __dict__".to_owned()))
}
pub fn object_set_dict(obj: PyObjectRef, dict: PyDictRef, vm: &VirtualMachine) -> PyResult<()> {
obj.set_dict(dict)
.map_err(|_| vm.new_attribute_error("This object has no __dict__".to_owned()))
}
pub fn init(ctx: &Context) {
PyBaseObject::extend_class(ctx, ctx.types.object_type);
}
fn common_reduce(obj: PyObjectRef, proto: usize, vm: &VirtualMachine) -> PyResult {
if proto >= 2 {
let reducelib = vm.import("__reducelib", None, 0)?;
let reduce_2 = reducelib.get_attr("reduce_2", vm)?;
reduce_2.call((obj,), vm)
} else {
let copyreg = vm.import("copyreg", None, 0)?;
let reduce_ex = copyreg.get_attr("_reduce_ex", vm)?;
reduce_ex.call((obj, proto), vm)
}
}
|
pub use super::client::*;
pub use super::from_db::*;
pub use super::operations::utils::{gen_cuid, KeyId, KeyKind};
pub use super::operations::*;
pub use super::to_db::*;
pub use googapis::google::datastore::v1::{Entity, Key};
|
#[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::CFG {
#[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 = "Possible values of the field `Enable`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ENABLER {
#[doc = "Disabled. The SPI is disabled and the internal state machine and counters are reset."]
DISABLED_THE_SPI_IS,
#[doc = "Enabled. The SPI is enabled for operation."]
ENABLED_THE_SPI_IS_,
}
impl ENABLER {
#[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 as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
ENABLER::DISABLED_THE_SPI_IS => false,
ENABLER::ENABLED_THE_SPI_IS_ => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> ENABLER {
match value {
false => ENABLER::DISABLED_THE_SPI_IS,
true => ENABLER::ENABLED_THE_SPI_IS_,
}
}
#[doc = "Checks if the value of the field is `DISABLED_THE_SPI_IS`"]
#[inline]
pub fn is_disabled_the_spi_is(&self) -> bool {
*self == ENABLER::DISABLED_THE_SPI_IS
}
#[doc = "Checks if the value of the field is `ENABLED_THE_SPI_IS_`"]
#[inline]
pub fn is_enabled_the_spi_is_(&self) -> bool {
*self == ENABLER::ENABLED_THE_SPI_IS_
}
}
#[doc = "Possible values of the field `Master`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum MASTERR {
#[doc = "Slave mode. The SPI will operate in slave mode. SCK, MOSI, and the SSEL signals are inputs, MISO is an output."]
SLAVE_MODE_THE_SPI_,
#[doc = "Master mode. The SPI will operate in master mode. SCK, MOSI, and the SSEL signals are outputs, MISO is an input."]
MASTER_MODE_THE_SPI,
}
impl MASTERR {
#[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 as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
MASTERR::SLAVE_MODE_THE_SPI_ => false,
MASTERR::MASTER_MODE_THE_SPI => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> MASTERR {
match value {
false => MASTERR::SLAVE_MODE_THE_SPI_,
true => MASTERR::MASTER_MODE_THE_SPI,
}
}
#[doc = "Checks if the value of the field is `SLAVE_MODE_THE_SPI_`"]
#[inline]
pub fn is_slave_mode_the_spi_(&self) -> bool {
*self == MASTERR::SLAVE_MODE_THE_SPI_
}
#[doc = "Checks if the value of the field is `MASTER_MODE_THE_SPI`"]
#[inline]
pub fn is_master_mode_the_spi(&self) -> bool {
*self == MASTERR::MASTER_MODE_THE_SPI
}
}
#[doc = "Possible values of the field `LSBF`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum LSBFR {
#[doc = "Standard. Data is transmitted and received in standard MSB first order."]
STANDARD_DATA_IS_TR,
#[doc = "Reverse. Data is transmitted and received in reverse order (LSB first)."]
REVERSE_DATA_IS_TRA,
}
impl LSBFR {
#[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 as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
LSBFR::STANDARD_DATA_IS_TR => false,
LSBFR::REVERSE_DATA_IS_TRA => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> LSBFR {
match value {
false => LSBFR::STANDARD_DATA_IS_TR,
true => LSBFR::REVERSE_DATA_IS_TRA,
}
}
#[doc = "Checks if the value of the field is `STANDARD_DATA_IS_TR`"]
#[inline]
pub fn is_standard_data_is_tr(&self) -> bool {
*self == LSBFR::STANDARD_DATA_IS_TR
}
#[doc = "Checks if the value of the field is `REVERSE_DATA_IS_TRA`"]
#[inline]
pub fn is_reverse_data_is_tra(&self) -> bool {
*self == LSBFR::REVERSE_DATA_IS_TRA
}
}
#[doc = "Possible values of the field `CPHA`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CPHAR {
#[doc = "Change. The SPI captures serial data on the first clock transition of the frame (when the clock changes away from the rest state). Data is changed on the following edge."]
CHANGE_THE_SPI_CAPT,
#[doc = "Capture. The SPI changes serial data on the first clock transition of the frame (when the clock changes away from the rest state). Data is captured on the following edge."]
CAPTURE_THE_SPI_CHA,
}
impl CPHAR {
#[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 as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
CPHAR::CHANGE_THE_SPI_CAPT => false,
CPHAR::CAPTURE_THE_SPI_CHA => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> CPHAR {
match value {
false => CPHAR::CHANGE_THE_SPI_CAPT,
true => CPHAR::CAPTURE_THE_SPI_CHA,
}
}
#[doc = "Checks if the value of the field is `CHANGE_THE_SPI_CAPT`"]
#[inline]
pub fn is_change_the_spi_capt(&self) -> bool {
*self == CPHAR::CHANGE_THE_SPI_CAPT
}
#[doc = "Checks if the value of the field is `CAPTURE_THE_SPI_CHA`"]
#[inline]
pub fn is_capture_the_spi_cha(&self) -> bool {
*self == CPHAR::CAPTURE_THE_SPI_CHA
}
}
#[doc = "Possible values of the field `CPOL`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CPOLR {
#[doc = "Low. The rest state of the clock (between frames) is low."]
LOW_THE_REST_STATE_,
#[doc = "High. The rest state of the clock (between frames) is high."]
HIGH_THE_REST_STATE,
}
impl CPOLR {
#[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 as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
CPOLR::LOW_THE_REST_STATE_ => false,
CPOLR::HIGH_THE_REST_STATE => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> CPOLR {
match value {
false => CPOLR::LOW_THE_REST_STATE_,
true => CPOLR::HIGH_THE_REST_STATE,
}
}
#[doc = "Checks if the value of the field is `LOW_THE_REST_STATE_`"]
#[inline]
pub fn is_low_the_rest_state_(&self) -> bool {
*self == CPOLR::LOW_THE_REST_STATE_
}
#[doc = "Checks if the value of the field is `HIGH_THE_REST_STATE`"]
#[inline]
pub fn is_high_the_rest_state(&self) -> bool {
*self == CPOLR::HIGH_THE_REST_STATE
}
}
#[doc = "Possible values of the field `Loop`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum LOOPR {
#[doc = "Disabled."]
DISABLED_,
#[doc = "Enabled."]
ENABLED_,
}
impl LOOPR {
#[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 as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
LOOPR::DISABLED_ => false,
LOOPR::ENABLED_ => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> LOOPR {
match value {
false => LOOPR::DISABLED_,
true => LOOPR::ENABLED_,
}
}
#[doc = "Checks if the value of the field is `DISABLED_`"]
#[inline]
pub fn is_disabled_(&self) -> bool {
*self == LOOPR::DISABLED_
}
#[doc = "Checks if the value of the field is `ENABLED_`"]
#[inline]
pub fn is_enabled_(&self) -> bool {
*self == LOOPR::ENABLED_
}
}
#[doc = "Possible values of the field `SPOL`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SPOLR {
#[doc = "Low. The SSEL pin is active low. The value in the SSEL fields of the RXDAT, TXDATCTL, and TXCTL registers related to SSEL is not inverted relative to the pins."]
LOW_THE_SSEL_PIN_IS,
#[doc = "High. The SSEL pin is active high. The value in the SSEL fields of the RXDAT, TXDATCTL, and TXCTL registers related to SSEL is inverted relative to the pins."]
HIGH_THE_SSEL_PIN_I,
}
impl SPOLR {
#[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 as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
SPOLR::LOW_THE_SSEL_PIN_IS => false,
SPOLR::HIGH_THE_SSEL_PIN_I => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> SPOLR {
match value {
false => SPOLR::LOW_THE_SSEL_PIN_IS,
true => SPOLR::HIGH_THE_SSEL_PIN_I,
}
}
#[doc = "Checks if the value of the field is `LOW_THE_SSEL_PIN_IS`"]
#[inline]
pub fn is_low_the_ssel_pin_is(&self) -> bool {
*self == SPOLR::LOW_THE_SSEL_PIN_IS
}
#[doc = "Checks if the value of the field is `HIGH_THE_SSEL_PIN_I`"]
#[inline]
pub fn is_high_the_ssel_pin_i(&self) -> bool {
*self == SPOLR::HIGH_THE_SSEL_PIN_I
}
}
#[doc = "Values that can be written to the field `Enable`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ENABLEW {
#[doc = "Disabled. The SPI is disabled and the internal state machine and counters are reset."]
DISABLED_THE_SPI_IS,
#[doc = "Enabled. The SPI is enabled for operation."]
ENABLED_THE_SPI_IS_,
}
impl ENABLEW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
ENABLEW::DISABLED_THE_SPI_IS => false,
ENABLEW::ENABLED_THE_SPI_IS_ => true,
}
}
}
#[doc = r" Proxy"]
pub struct _ENABLEW<'a> {
w: &'a mut W,
}
impl<'a> _ENABLEW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: ENABLEW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Disabled. The SPI is disabled and the internal state machine and counters are reset."]
#[inline]
pub fn disabled_the_spi_is(self) -> &'a mut W {
self.variant(ENABLEW::DISABLED_THE_SPI_IS)
}
#[doc = "Enabled. The SPI is enabled for operation."]
#[inline]
pub fn enabled_the_spi_is_(self) -> &'a mut W {
self.variant(ENABLEW::ENABLED_THE_SPI_IS_)
}
#[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
}
}
#[doc = "Values that can be written to the field `Master`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum MASTERW {
#[doc = "Slave mode. The SPI will operate in slave mode. SCK, MOSI, and the SSEL signals are inputs, MISO is an output."]
SLAVE_MODE_THE_SPI_,
#[doc = "Master mode. The SPI will operate in master mode. SCK, MOSI, and the SSEL signals are outputs, MISO is an input."]
MASTER_MODE_THE_SPI,
}
impl MASTERW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
MASTERW::SLAVE_MODE_THE_SPI_ => false,
MASTERW::MASTER_MODE_THE_SPI => true,
}
}
}
#[doc = r" Proxy"]
pub struct _MASTERW<'a> {
w: &'a mut W,
}
impl<'a> _MASTERW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: MASTERW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Slave mode. The SPI will operate in slave mode. SCK, MOSI, and the SSEL signals are inputs, MISO is an output."]
#[inline]
pub fn slave_mode_the_spi_(self) -> &'a mut W {
self.variant(MASTERW::SLAVE_MODE_THE_SPI_)
}
#[doc = "Master mode. The SPI will operate in master mode. SCK, MOSI, and the SSEL signals are outputs, MISO is an input."]
#[inline]
pub fn master_mode_the_spi(self) -> &'a mut W {
self.variant(MASTERW::MASTER_MODE_THE_SPI)
}
#[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 = "Values that can be written to the field `LSBF`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum LSBFW {
#[doc = "Standard. Data is transmitted and received in standard MSB first order."]
STANDARD_DATA_IS_TR,
#[doc = "Reverse. Data is transmitted and received in reverse order (LSB first)."]
REVERSE_DATA_IS_TRA,
}
impl LSBFW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
LSBFW::STANDARD_DATA_IS_TR => false,
LSBFW::REVERSE_DATA_IS_TRA => true,
}
}
}
#[doc = r" Proxy"]
pub struct _LSBFW<'a> {
w: &'a mut W,
}
impl<'a> _LSBFW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: LSBFW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Standard. Data is transmitted and received in standard MSB first order."]
#[inline]
pub fn standard_data_is_tr(self) -> &'a mut W {
self.variant(LSBFW::STANDARD_DATA_IS_TR)
}
#[doc = "Reverse. Data is transmitted and received in reverse order (LSB first)."]
#[inline]
pub fn reverse_data_is_tra(self) -> &'a mut W {
self.variant(LSBFW::REVERSE_DATA_IS_TRA)
}
#[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 = "Values that can be written to the field `CPHA`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CPHAW {
#[doc = "Change. The SPI captures serial data on the first clock transition of the frame (when the clock changes away from the rest state). Data is changed on the following edge."]
CHANGE_THE_SPI_CAPT,
#[doc = "Capture. The SPI changes serial data on the first clock transition of the frame (when the clock changes away from the rest state). Data is captured on the following edge."]
CAPTURE_THE_SPI_CHA,
}
impl CPHAW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
CPHAW::CHANGE_THE_SPI_CAPT => false,
CPHAW::CAPTURE_THE_SPI_CHA => true,
}
}
}
#[doc = r" Proxy"]
pub struct _CPHAW<'a> {
w: &'a mut W,
}
impl<'a> _CPHAW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: CPHAW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Change. The SPI captures serial data on the first clock transition of the frame (when the clock changes away from the rest state). Data is changed on the following edge."]
#[inline]
pub fn change_the_spi_capt(self) -> &'a mut W {
self.variant(CPHAW::CHANGE_THE_SPI_CAPT)
}
#[doc = "Capture. The SPI changes serial data on the first clock transition of the frame (when the clock changes away from the rest state). Data is captured on the following edge."]
#[inline]
pub fn capture_the_spi_cha(self) -> &'a mut W {
self.variant(CPHAW::CAPTURE_THE_SPI_CHA)
}
#[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 = "Values that can be written to the field `CPOL`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CPOLW {
#[doc = "Low. The rest state of the clock (between frames) is low."]
LOW_THE_REST_STATE_,
#[doc = "High. The rest state of the clock (between frames) is high."]
HIGH_THE_REST_STATE,
}
impl CPOLW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
CPOLW::LOW_THE_REST_STATE_ => false,
CPOLW::HIGH_THE_REST_STATE => true,
}
}
}
#[doc = r" Proxy"]
pub struct _CPOLW<'a> {
w: &'a mut W,
}
impl<'a> _CPOLW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: CPOLW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Low. The rest state of the clock (between frames) is low."]
#[inline]
pub fn low_the_rest_state_(self) -> &'a mut W {
self.variant(CPOLW::LOW_THE_REST_STATE_)
}
#[doc = "High. The rest state of the clock (between frames) is high."]
#[inline]
pub fn high_the_rest_state(self) -> &'a mut W {
self.variant(CPOLW::HIGH_THE_REST_STATE)
}
#[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 = "Values that can be written to the field `Loop`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum LOOPW {
#[doc = "Disabled."]
DISABLED_,
#[doc = "Enabled."]
ENABLED_,
}
impl LOOPW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
LOOPW::DISABLED_ => false,
LOOPW::ENABLED_ => true,
}
}
}
#[doc = r" Proxy"]
pub struct _LOOPW<'a> {
w: &'a mut W,
}
impl<'a> _LOOPW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: LOOPW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Disabled."]
#[inline]
pub fn disabled_(self) -> &'a mut W {
self.variant(LOOPW::DISABLED_)
}
#[doc = "Enabled."]
#[inline]
pub fn enabled_(self) -> &'a mut W {
self.variant(LOOPW::ENABLED_)
}
#[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 = "Values that can be written to the field `SPOL`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SPOLW {
#[doc = "Low. The SSEL pin is active low. The value in the SSEL fields of the RXDAT, TXDATCTL, and TXCTL registers related to SSEL is not inverted relative to the pins."]
LOW_THE_SSEL_PIN_IS,
#[doc = "High. The SSEL pin is active high. The value in the SSEL fields of the RXDAT, TXDATCTL, and TXCTL registers related to SSEL is inverted relative to the pins."]
HIGH_THE_SSEL_PIN_I,
}
impl SPOLW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
SPOLW::LOW_THE_SSEL_PIN_IS => false,
SPOLW::HIGH_THE_SSEL_PIN_I => true,
}
}
}
#[doc = r" Proxy"]
pub struct _SPOLW<'a> {
w: &'a mut W,
}
impl<'a> _SPOLW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: SPOLW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Low. The SSEL pin is active low. The value in the SSEL fields of the RXDAT, TXDATCTL, and TXCTL registers related to SSEL is not inverted relative to the pins."]
#[inline]
pub fn low_the_ssel_pin_is(self) -> &'a mut W {
self.variant(SPOLW::LOW_THE_SSEL_PIN_IS)
}
#[doc = "High. The SSEL pin is active high. The value in the SSEL fields of the RXDAT, TXDATCTL, and TXCTL registers related to SSEL is inverted relative to the pins."]
#[inline]
pub fn high_the_ssel_pin_i(self) -> &'a mut W {
self.variant(SPOLW::HIGH_THE_SSEL_PIN_I)
}
#[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
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bit 0 - SPI enable."]
#[inline]
pub fn enable(&self) -> ENABLER {
ENABLER::_from({
const MASK: bool = true;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 2 - Master mode select."]
#[inline]
pub fn master(&self) -> MASTERR {
MASTERR::_from({
const MASK: bool = true;
const OFFSET: u8 = 2;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 3 - LSB First mode enable."]
#[inline]
pub fn lsbf(&self) -> LSBFR {
LSBFR::_from({
const MASK: bool = true;
const OFFSET: u8 = 3;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 4 - Clock Phase select. ."]
#[inline]
pub fn cpha(&self) -> CPHAR {
CPHAR::_from({
const MASK: bool = true;
const OFFSET: u8 = 4;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 5 - Clock Polarity select."]
#[inline]
pub fn cpol(&self) -> CPOLR {
CPOLR::_from({
const MASK: bool = true;
const OFFSET: u8 = 5;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 7 - Loopback mode enable. Loopback mode applies only to Master mode, and connects transmit and receive data connected together to allow simple software testing."]
#[inline]
pub fn loop_(&self) -> LOOPR {
LOOPR::_from({
const MASK: bool = true;
const OFFSET: u8 = 7;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 8 - SSEL Polarity select."]
#[inline]
pub fn spol(&self) -> SPOLR {
SPOLR::_from({
const MASK: bool = true;
const OFFSET: u8 = 8;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
}
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 0 - SPI enable."]
#[inline]
pub fn enable(&mut self) -> _ENABLEW {
_ENABLEW { w: self }
}
#[doc = "Bit 2 - Master mode select."]
#[inline]
pub fn master(&mut self) -> _MASTERW {
_MASTERW { w: self }
}
#[doc = "Bit 3 - LSB First mode enable."]
#[inline]
pub fn lsbf(&mut self) -> _LSBFW {
_LSBFW { w: self }
}
#[doc = "Bit 4 - Clock Phase select. ."]
#[inline]
pub fn cpha(&mut self) -> _CPHAW {
_CPHAW { w: self }
}
#[doc = "Bit 5 - Clock Polarity select."]
#[inline]
pub fn cpol(&mut self) -> _CPOLW {
_CPOLW { w: self }
}
#[doc = "Bit 7 - Loopback mode enable. Loopback mode applies only to Master mode, and connects transmit and receive data connected together to allow simple software testing."]
#[inline]
pub fn loop_(&mut self) -> _LOOPW {
_LOOPW { w: self }
}
#[doc = "Bit 8 - SSEL Polarity select."]
#[inline]
pub fn spol(&mut self) -> _SPOLW {
_SPOLW { w: self }
}
}
|
use std::borrow::Borrow;
use std::fmt::Display;
use std::ops::Deref;
use ordered_float::OrderedFloat;
use graph_lib::algo::trees::Trees;
use mymcts::MyMcts;
use policy::policy::Policy;
use policy::score::Score;
use policy::win_score::ExploreScore;
use rust_tools::screen::layout::layout::L;
use sim_result::SimResult;
use rules::Action;
use crate::mcts::{Mcts, MctsNode};
use crate::rules::Rules;
pub struct Explorer<A: Action, S: Rules<A>> {
mcts: MyMcts<A, S>,
simulation_factor: usize,
_foo: Option<(S)>,
}
impl<A: Action, S: Rules<A>> Explorer<A, S> {
pub fn new(simulation_factor: usize, state: S) -> Explorer<A, S> {
Explorer {
mcts: MyMcts::new(state),
simulation_factor,
_foo: None,
}
}
pub fn mcts(&self) -> &MyMcts<A, S> {
&self.mcts
}
pub fn mcts_mut(&mut self) -> &mut MyMcts<A, S> {
&mut self.mcts
}
pub fn explore<Sim: Policy<A, S>, Select: Score>(
&mut self,
sim_policy: &Sim,
select_policy: &Select)
-> MctsNode<A>
{
// log::debug!("* Exploration:");
let selected = self.mcts.selection(select_policy);
let (_action, expansion) = self.mcts.expansion(&selected, sim_policy);
let res = self.simulation(sim_policy);
self.mcts.backpropagation(&expansion, res);
expansion
}
fn simulation<Sim: Policy<A, S>>(&mut self, policy: &Sim) -> SimResult {
let res = match self.simulation_factor {
1 => self.mcts.state_mut().simulation(policy),
_ => {
let mut result = SimResult::new();
let mut state = self.mcts.state().fork();
for _i in 0..self.simulation_factor {
result.merge(&state.fork().simulation(policy));
}
result
}
};
// log::debug!("Simulation: {}", res);
res
}
}
|
use crate::image::Image;
pub use crate::prelude::*;
use crate::widget::Widget;
use fltk_sys::table::*;
use std::{
ffi::{CStr, CString},
mem,
os::raw,
};
/// Creates a table
#[derive(WidgetExt, GroupExt, TableExt, Debug)]
pub struct Table {
_inner: *mut Fl_Table,
_tracker: *mut fltk_sys::fl::Fl_Widget_Tracker,
}
/// Creates a table row
#[derive(WidgetExt, GroupExt, TableExt, Debug)]
pub struct TableRow {
_inner: *mut Fl_Table_Row,
_tracker: *mut fltk_sys::fl::Fl_Widget_Tracker,
}
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum TableRowSelectMode {
SelectNone,
SelectSingle,
SelectMulti,
}
impl TableRow {
pub fn set_type(&mut self, val: TableRowSelectMode) {
assert!(!self.was_deleted());
unsafe { Fl_Table_Row_set_type(self._inner, val as i32) }
}
pub fn get_type(&self) -> TableRowSelectMode {
assert!(!self.was_deleted());
unsafe { mem::transmute(Fl_Table_Row_get_type(self._inner)) }
}
pub fn row_selected(&mut self, row: i32) -> bool {
unsafe {
assert!(!self.was_deleted());
match Fl_Table_Row_row_selected(self._inner, row) {
0 => false,
_ => true,
}
}
}
pub fn select_row(&mut self, row: i32) -> Result<(), FltkError> {
unsafe {
assert!(!self.was_deleted());
match Fl_Table_Row_select_row(self._inner, row) {
1 => Ok(()),
0 => Err(FltkError::Internal(FltkErrorKind::TableError)),
-1 => Err(FltkError::Internal(FltkErrorKind::TableError)),
_ => unreachable!(),
}
}
}
pub fn select_all_rows(&mut self) {
assert!(!self.was_deleted());
unsafe { Fl_Table_Row_select_all_rows(self._inner) }
}
}
|
use eosio::{AccountName, ActionName, PermissionName};
use structopt::StructOpt;
/// Set or update blockchain state
#[derive(StructOpt, Debug)]
pub enum Set {
/// Create or update the code on an account
Code(SetCode),
/// Create or update the abi on an account
Abi(SetAbi),
/// Create or update the contract on an account
Contract(SetContract),
/// set or update blockchain account state
Account(SetAccount),
/// set or update blockchain action state
Action(SetAction),
}
/// Create or update the code on an account
#[derive(StructOpt, Debug)]
pub struct SetCode {
/// The account to set code for
pub account: AccountName,
/// The fullpath containing the contract WASM
pub code_file: Option<String>,
/// Remove code on an account
#[structopt(short, long)]
pub clear: bool,
/// Don't check for duplicate
#[structopt(long)]
pub suppress_duplicate_check: bool,
#[structopt(flatten)]
pub transaction_opts: super::TransactionOpts,
}
/// Create or update the abi on an account
#[derive(StructOpt, Debug)]
pub struct SetAbi {
/// The account to set the ABI for
pub account: AccountName,
/// The fullpath containing the contract ABI
pub abi_file: Option<String>,
/// Remove code on an account
#[structopt(short, long)]
pub clear: bool,
/// Don't check for duplicate
#[structopt(long)]
pub suppress_duplicate_check: bool,
#[structopt(flatten)]
pub transaction_opts: super::TransactionOpts,
}
/// Create or update the contract on an account
#[derive(StructOpt, Debug)]
pub struct SetContract {
/// The account to set the ABI for
pub account: AccountName,
/// The path containing the .wasm and .abi
pub contract_dir: Option<String>,
/// The file containing the contract WASM relative to contract-dir
pub wasm_file: Option<String>,
/// The ABI for the contract relative to contract-dir
pub abi_file: Option<String>,
/// The ABI for the contract relative to contract-dir
#[structopt(short, long)]
pub abi: Option<String>,
/// Remove code on an account
#[structopt(short, long)]
pub clear: bool,
/// Don't check for duplicate
#[structopt(long)]
pub suppress_duplicate_check: bool,
#[structopt(flatten)]
pub transaction_opts: super::TransactionOpts,
}
/// set or update blockchain account state
#[derive(StructOpt, Debug)]
pub enum SetAccount {
/// set parameters dealing with account permissions
Permission(SetAccountPermission),
}
/// set parameters dealing with account permissions
#[derive(StructOpt, Debug)]
pub struct SetAccountPermission {
/// The account to set/delete a permission authority for
pub account: AccountName,
/// The permission name to set/delete an authority for
pub permission: PermissionName,
/// [delete] NULL, [create/update] public key, JSON string or filename defining
/// the authority, [code] contract name
pub authority: Option<String>,
/// [create] The permission name of this parents permission
#[structopt(default_value = "active")]
pub parent: PermissionName,
/// [code] add 'eosio.code' permission to specified permission authority
#[structopt(long)]
pub add_code: bool,
/// [code] remove 'eosio.code' permission from specified permission authority
#[structopt(long)]
pub remove_code: bool,
#[structopt(flatten)]
pub transaction_opts: super::TransactionOpts,
}
/// set or update blockchain action state
#[derive(StructOpt, Debug)]
pub enum SetAction {
/// set parameters dealing with account permissions
Permission(SetActionPermission),
}
/// set parameters dealing with account permissions
#[derive(StructOpt, Debug)]
pub struct SetActionPermission {
/// The account to set/delete a permission authority for
pub account: AccountName,
/// The account that owns the code for the action,
pub code: AccountName,
/// the type of action
pub type_: ActionName,
/// [delete] NULL, [set/update] The permission name require for executing
/// the given action
pub requirement: PermissionName,
#[structopt(flatten)]
pub transaction_opts: super::TransactionOpts,
}
|
use crate::db::{add_task, query_tasks, update_task, Pool};
use actix_web::{get, patch, post, web, HttpResponse, Responder};
use raskd::models::{Incoming, Outgoing, QueryParams};
#[post("/task")]
async fn post_tasks(db: web::Data<Pool>, data: web::Json<Incoming>) -> impl Responder {
let conn = db.clone().get().unwrap();
let res = add_task(conn, data.into_inner());
match res {
Ok(r) => HttpResponse::Ok().json(r),
Err(e) => HttpResponse::Ok().json(Outgoing::Error {
msg: format!("{}", e),
}),
}
}
#[get("/task")]
async fn get_tasks(db: web::Data<Pool>, param: web::Query<QueryParams>) -> impl Responder {
let conn = db.clone().get().unwrap();
match query_tasks(conn, param.into_inner()) {
Ok(r) => HttpResponse::Ok().json(r),
Err(e) => HttpResponse::Ok().json(Outgoing::Error {
msg: format!("{}", e),
}),
}
}
#[patch("/task")]
async fn patch_task(db: web::Data<Pool>, data: web::Json<Incoming>) -> impl Responder {
let conn = db.clone().get().unwrap();
match update_task(conn, data.into_inner()) {
Ok(r) => HttpResponse::Ok().json(r),
Err(e) => HttpResponse::Ok().json(Outgoing::Error {
msg: format!("{}", e),
}),
}
}
|
// Copyright 2020. The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
use crate::{
base_node::states::{BlockSyncStrategy, ListeningInfo, Shutdown, Starting, Waiting},
chain_storage::ChainMetadata,
proof_of_work::Difficulty,
};
use std::fmt::{Display, Error, Formatter};
use tari_comms::peer_manager::NodeId;
#[derive(Clone, Debug, PartialEq)]
pub enum BaseNodeState {
Starting(Starting),
BlockSync(BlockSyncStrategy, ChainMetadata, Vec<NodeId>),
// The best network chain metadata
Listening(ListeningInfo),
// We're in a paused state, and will return to Listening after a timeout
Waiting(Waiting),
Shutdown(Shutdown),
}
#[derive(Debug, Clone, PartialEq)]
pub enum StateEvent {
Initialized,
MetadataSynced(SyncStatus),
BlocksSynchronized,
BlockSyncFailure,
FallenBehind(SyncStatus),
NetworkSilence,
FatalError(String),
Continue,
UserQuit,
}
/// Some state transition functions must return `SyncStatus`. The sync status indicates how far behind the network's
/// blockchain the local node is. It can either be very far behind (`BehindHorizon`), in which case we will just
/// synchronise against the pruning horizon; we're somewhat behind (`Lagging`) and need to download the missing
/// blocks to catch up, or we are `UpToDate`.
#[derive(Debug, Clone, PartialEq)]
pub enum SyncStatus {
// We are behind the chain tip.
Lagging(ChainMetadata, Vec<NodeId>),
UpToDate,
}
impl Display for SyncStatus {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
use SyncStatus::*;
match self {
Lagging(m, v) => write!(
f,
"Lagging behind {} peers (#{}, Difficulty: {})",
v.len(),
m.height_of_longest_chain.unwrap_or(0),
m.accumulated_difficulty.unwrap_or_else(Difficulty::min)
),
UpToDate => f.write_str("UpToDate"),
}
}
}
impl Display for StateEvent {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
use StateEvent::*;
match self {
Initialized => f.write_str("Initialized"),
MetadataSynced(s) => write!(f, "Synchronized metadata - {}", s),
BlocksSynchronized => f.write_str("Synchronised Blocks"),
BlockSyncFailure => f.write_str("Block Synchronization Failure"),
FallenBehind(s) => write!(f, "Fallen behind main chain - {}", s),
NetworkSilence => f.write_str("Network Silence"),
Continue => f.write_str("Continuing"),
FatalError(e) => write!(f, "Fatal Error - {}", e),
UserQuit => f.write_str("User Termination"),
}
}
}
impl Display for BaseNodeState {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
let s = match self {
Self::Starting(_) => "Initializing",
Self::BlockSync(_, _, _) => "Synchronizing blocks",
Self::Listening(_) => "Listening",
Self::Shutdown(_) => "Shutting down",
Self::Waiting(_) => "Waiting",
};
f.write_str(s)
}
}
|
// Copyright 2016 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.
use astconv::AstConv;
use super::{FnCtxt, PlaceOp, Needs};
use super::method::MethodCallee;
use rustc::infer::InferOk;
use rustc::session::DiagnosticMessageId;
use rustc::traits;
use rustc::ty::{self, Ty, TraitRef};
use rustc::ty::{ToPredicate, TypeFoldable};
use rustc::ty::adjustment::{Adjustment, Adjust, OverloadedDeref};
use syntax_pos::Span;
use syntax::ast::Ident;
use std::iter;
#[derive(Copy, Clone, Debug)]
enum AutoderefKind {
Builtin,
Overloaded,
}
pub struct Autoderef<'a, 'gcx: 'tcx, 'tcx: 'a> {
fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
steps: Vec<(Ty<'tcx>, AutoderefKind)>,
cur_ty: Ty<'tcx>,
obligations: Vec<traits::PredicateObligation<'tcx>>,
at_start: bool,
include_raw_pointers: bool,
span: Span,
}
impl<'a, 'gcx, 'tcx> Iterator for Autoderef<'a, 'gcx, 'tcx> {
type Item = (Ty<'tcx>, usize);
fn next(&mut self) -> Option<Self::Item> {
let tcx = self.fcx.tcx;
debug!("autoderef: steps={:?}, cur_ty={:?}",
self.steps,
self.cur_ty);
if self.at_start {
self.at_start = false;
debug!("autoderef stage #0 is {:?}", self.cur_ty);
return Some((self.cur_ty, 0));
}
if self.steps.len() >= *tcx.sess.recursion_limit.get() {
// We've reached the recursion limit, error gracefully.
let suggested_limit = *tcx.sess.recursion_limit.get() * 2;
let msg = format!("reached the recursion limit while auto-dereferencing {:?}",
self.cur_ty);
let error_id = (DiagnosticMessageId::ErrorId(55), Some(self.span), msg.clone());
let fresh = tcx.sess.one_time_diagnostics.borrow_mut().insert(error_id);
if fresh {
struct_span_err!(tcx.sess,
self.span,
E0055,
"reached the recursion limit while auto-dereferencing {:?}",
self.cur_ty)
.span_label(self.span, "deref recursion limit reached")
.help(&format!(
"consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
suggested_limit))
.emit();
}
return None;
}
if self.cur_ty.is_ty_var() {
return None;
}
// Otherwise, deref if type is derefable:
let (kind, new_ty) =
if let Some(mt) = self.cur_ty.builtin_deref(self.include_raw_pointers) {
(AutoderefKind::Builtin, mt.ty)
} else {
let ty = self.overloaded_deref_ty(self.cur_ty)?;
(AutoderefKind::Overloaded, ty)
};
if new_ty.references_error() {
return None;
}
self.steps.push((self.cur_ty, kind));
debug!("autoderef stage #{:?} is {:?} from {:?}",
self.steps.len(),
new_ty,
(self.cur_ty, kind));
self.cur_ty = new_ty;
Some((self.cur_ty, self.steps.len()))
}
}
impl<'a, 'gcx, 'tcx> Autoderef<'a, 'gcx, 'tcx> {
fn overloaded_deref_ty(&mut self, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
debug!("overloaded_deref_ty({:?})", ty);
let tcx = self.fcx.tcx();
// <cur_ty as Deref>
let trait_ref = TraitRef {
def_id: tcx.lang_items().deref_trait()?,
substs: tcx.mk_substs_trait(self.cur_ty, &[]),
};
let cause = traits::ObligationCause::misc(self.span, self.fcx.body_id);
let obligation = traits::Obligation::new(cause.clone(),
self.fcx.param_env,
trait_ref.to_predicate());
if !self.fcx.predicate_may_hold(&obligation) {
debug!("overloaded_deref_ty: cannot match obligation");
return None;
}
let mut selcx = traits::SelectionContext::new(self.fcx);
let normalized_ty = traits::normalize_projection_type(&mut selcx,
self.fcx.param_env,
ty::ProjectionTy::from_ref_and_name(
tcx,
trait_ref,
Ident::from_str("Target"),
),
cause,
0,
&mut self.obligations);
debug!("overloaded_deref_ty({:?}) = {:?}", ty, normalized_ty);
Some(self.fcx.resolve_type_vars_if_possible(&normalized_ty))
}
/// Returns the final type, generating an error if it is an
/// unresolved inference variable.
pub fn unambiguous_final_ty(&self) -> Ty<'tcx> {
self.fcx.structurally_resolved_type(self.span, self.cur_ty)
}
/// Returns the final type we ended up with, which may well be an
/// inference variable (we will resolve it first, if possible).
pub fn maybe_ambiguous_final_ty(&self) -> Ty<'tcx> {
self.fcx.resolve_type_vars_if_possible(&self.cur_ty)
}
pub fn step_count(&self) -> usize {
self.steps.len()
}
/// Returns the adjustment steps.
pub fn adjust_steps(&self, needs: Needs)
-> Vec<Adjustment<'tcx>> {
self.fcx.register_infer_ok_obligations(self.adjust_steps_as_infer_ok(needs))
}
pub fn adjust_steps_as_infer_ok(&self, needs: Needs)
-> InferOk<'tcx, Vec<Adjustment<'tcx>>> {
let mut obligations = vec![];
let targets = self.steps.iter().skip(1).map(|&(ty, _)| ty)
.chain(iter::once(self.cur_ty));
let steps: Vec<_> = self.steps.iter().map(|&(source, kind)| {
if let AutoderefKind::Overloaded = kind {
self.fcx.try_overloaded_deref(self.span, source, needs)
.and_then(|InferOk { value: method, obligations: o }| {
obligations.extend(o);
if let ty::TyRef(region, _, mutbl) = method.sig.output().sty {
Some(OverloadedDeref {
region,
mutbl,
})
} else {
None
}
})
} else {
None
}
}).zip(targets).map(|(autoderef, target)| {
Adjustment {
kind: Adjust::Deref(autoderef),
target
}
}).collect();
InferOk {
obligations,
value: steps
}
}
/// also dereference through raw pointer types
/// e.g. assuming ptr_to_Foo is the type `*const Foo`
/// fcx.autoderef(span, ptr_to_Foo) => [*const Foo]
/// fcx.autoderef(span, ptr_to_Foo).include_raw_ptrs() => [*const Foo, Foo]
pub fn include_raw_pointers(mut self) -> Self {
self.include_raw_pointers = true;
self
}
pub fn finalize(self) {
let fcx = self.fcx;
fcx.register_predicates(self.into_obligations());
}
pub fn into_obligations(self) -> Vec<traits::PredicateObligation<'tcx>> {
self.obligations
}
}
impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
pub fn autoderef(&'a self, span: Span, base_ty: Ty<'tcx>) -> Autoderef<'a, 'gcx, 'tcx> {
Autoderef {
fcx: self,
steps: vec![],
cur_ty: self.resolve_type_vars_if_possible(&base_ty),
obligations: vec![],
at_start: true,
include_raw_pointers: false,
span,
}
}
pub fn try_overloaded_deref(&self,
span: Span,
base_ty: Ty<'tcx>,
needs: Needs)
-> Option<InferOk<'tcx, MethodCallee<'tcx>>> {
self.try_overloaded_place_op(span, base_ty, &[], needs, PlaceOp::Deref)
}
}
|
use anyhow::{anyhow, bail, ensure, Result};
use std::str::from_utf8;
use std::str::FromStr;
const MAX_CHARSTRING_LEN: usize = 255;
pub struct StringBuffer<'a> {
raw: &'a [u8],
pos: usize,
}
impl<'a> StringBuffer<'a> {
pub fn new(raw: &'a str) -> Self {
debug_assert!(!raw.is_empty());
StringBuffer {
raw: raw.as_bytes(),
pos: 0,
}
}
pub fn read_text(&mut self) -> Result<Vec<Vec<u8>>> {
let mut data = Vec::new();
loop {
let slice = self.read_char_string()?;
data.push(slice);
if self.is_eos() {
break;
}
}
ensure!(!data.is_empty(), "quote isn't in pair",);
Ok(data)
}
pub fn read_char_string(&mut self) -> Result<Vec<u8>> {
self.skip_whitespace();
if self.is_eos() || self.raw[self.pos] != b'"' {
bail!("text isn't quoted");
}
self.pos += 1;
let mut data = Vec::new();
let mut escape = false;
while !self.is_eos() {
let c = self.raw[self.pos];
if c == b'\\' && !escape {
escape = true;
self.pos += 1;
} else {
if c == b'"' && !escape {
self.pos += 1;
if data.is_empty() {
bail!("empty text slice");
} else {
return Ok(data);
}
} else if escape && c.is_ascii_digit() {
if self.raw.len() - self.pos < 3 {
bail!("num is short than 3 bytes");
}
let num: u8 = from_utf8(&self.raw[self.pos..(self.pos + 3)])?.parse()?;
data.push(num);
self.pos += 3;
} else {
data.push(c);
self.pos += 1;
}
escape = false;
if data.len() > MAX_CHARSTRING_LEN {
bail!("txt len is too long");
}
}
}
bail!("quote isn't in pair");
}
fn skip_whitespace(&mut self) {
while !self.is_eos() && self.raw[self.pos].is_ascii_whitespace() {
self.pos += 1
}
}
pub fn read<T>(&mut self) -> Result<T>
where
T: FromStr,
<T as std::str::FromStr>::Err: ToString,
{
if let Some(s) = self.read_str() {
s.parse::<T>().map_err(|e| anyhow!(e.to_string()))
} else {
bail!("empty string",)
}
}
pub fn read_str(&mut self) -> Option<&'a str> {
self.skip_whitespace();
let start = self.pos;
while !self.is_eos() && !self.raw[self.pos].is_ascii_whitespace() {
self.pos += 1;
}
if self.pos == start {
None
} else {
Some(from_utf8(&self.raw[start..self.pos]).unwrap())
}
}
pub fn read_left(&mut self) -> Option<&'a str> {
if self.is_eos() {
None
} else {
let ret = Some(from_utf8(&self.raw[self.pos..]).unwrap());
self.pos = self.raw.len();
ret
}
}
pub fn left_str(mut self) -> Option<&'a str> {
self.read_left()
}
fn is_eos(&self) -> bool {
self.pos == self.raw.len()
}
}
impl<'a> Iterator for StringBuffer<'a> {
type Item = &'a str;
fn next(&mut self) -> Option<&'a str> {
self.read_str()
}
}
#[cfg(test)]
mod test {
use super::StringBuffer;
#[test]
fn test_parser_iterator() {
let s = " example.org. 100 IN SOA xxx.net. ns.example.org. 100 1800 900 604800 86400 ";
let mut iter = StringBuffer::new(s);
let mut split_white = s.split_whitespace();
let mut label_count = 0;
loop {
if let Some(label) = iter.next() {
assert_eq!(label, split_white.next().unwrap());
label_count += 1;
} else {
break;
}
}
assert_eq!(label_count, 11);
}
#[test]
fn test_into_string() {
let s = " example.org. 100 IN SOA xxx.net. ns.example.org. 100 1800 900 604800 86400 ";
let mut iter = StringBuffer::new(s);
iter.next();
iter.next();
assert_eq!(
iter.left_str().unwrap(),
" IN SOA xxx.net. ns.example.org. 100 1800 900 604800 86400 "
);
}
#[test]
fn test_read_text() {
let s = r#" "abc" "edf""#;
let data = StringBuffer::new(s).read_text().unwrap();
assert_eq!(data.len(), 2);
assert_eq!(data[0], "abc".as_bytes().to_vec());
assert_eq!(data[1], "edf".as_bytes().to_vec());
let s = r#" "abc edf""#;
let data = StringBuffer::new(s).read_text().unwrap();
assert_eq!(data.len(), 1);
assert_eq!(data[0], "abc edf".as_bytes().to_vec());
let s = r#" "abc\"cd\" edf""#;
let data = StringBuffer::new(s).read_text().unwrap();
assert_eq!(data.len(), 1);
assert_eq!(data[0], r#"abc"cd" edf"#.as_bytes().to_vec());
let s = r#""a\011d""#;
let data = StringBuffer::new(s).read_text().unwrap();
assert_eq!(data.len(), 1);
assert_eq!(data[0][1], 11);
}
}
|
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
// Copyright © 2019 The developers of linux-epoll. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT.
const SizeOfVER: usize = 1;
const SizeOfREP: usize = 1;
const SizeOfRSV: usize = 1;
const SizeOfATYP: usize = 1;
const MaximumSizeOfHostName: usize = 253;
const MaximumSizeOfBNDADDR: usize = Self::MaximumSizeOfHostName + 1;
const SizeOfBNDPORT: usize = 2;
struct Socks5ConnectReply<'yielder, SD: SocketData>
{
unencrypted_stream: UnencryptedStream<'yielder, SD>,
small_reply_packet_buffer: [u8; SizeOfVER + SizeOfREP + SizeOfRSV + SizeOfATYP + MaximumSizeOfBNDADDR + SizeOfBNDPORT],
bytes_read_so_far: usize,
}
impl<'yielder, SD: SocketData> Socks5ConnectReply<'yielder, SD>
{
#[inline(always)]
pub(crate) fn read_reply(unencrypted_stream: UnencryptedStream<'yielder, SD>) -> Result<(UnencryptedStream<'yielder, SD>, BoundSocketAddress), CompleteError>
{
use self::Socks5ProtocolFailureError::*;
#[inline(always)]
fn error(error: Socks5ProtocolFailureError) -> Result<(), CompleteError>
{
Err(CompleteError::ProtocolViolation(Box::new(error)))
}
const SizeOfVER: usize = 1;
const SizeOfREP: usize = 1;
const SizeOfRSV: usize = 1;
const SizeOfATYP: usize = 1;
const SizeOfBNDPORT: usize = 2;
let mut this = Self
{
unencrypted_stream,
small_reply_packet_buffer: unsafe { uninitialized() },
bytes_read_so_far: 0,
};
this.read_reply_bytes()?;
let version = unsafe { *this.small_reply_packet_buffer.get_unchecked(0) } ;
if version != Socks5Connect::Version
{
return error(VersionInvalid(version))
}
if unlikely!(this.bytes_read_so_far == SizeOfVER)
{
this.read_reply_bytes()?;
}
let rep = unsafe { *this.small_reply_packet_buffer.get_unchecked(SizeOfVER) };
match rep
{
0x00 => (),
0x01 => return error(GeneralSocksServerFailure),
0x02 => return error(ConnectionNotAllowedByRuleset),
0x03 => return error(NetworkUnreachable),
0x04 => return error(HostUnreachable),
0x05 => return error(ConnectionRefused),
0x06 => return error(TimeToLiveExpired),
0x07 => return error(CommandNotSupported),
0x08 => return error(AddressTypeNotSupported),
_ => return error(UnassignedError(rep)),
}
if unlikely!(this.bytes_read_so_far == SizeOfVER + SizeOfREP)
{
this.read_reply_bytes()?;
}
let rsv = unsafe { *this.small_reply_packet_buffer.get_unchecked(SizeOfVER + SizeOfREP) };
if unlikely!(rsv != 0x00)
{
return error(ReplyRsvFieldWasNotZero)
}
if unlikely!(this.bytes_read_so_far == SizeOfVER + SizeOfREP + SizeOfRSV)
{
this.read_reply_bytes()?;
}
let atyp = unsafe { *this.small_reply_packet_buffer.get_unchecked(SizeOfVER + SizeOfREP + SizeOfRSV) };
const SizeOfFixedHeader: usize = SizeOfVER + SizeOfREP + SizeOfRSV + SizeOfATYP;
use self::InternetProtocolAddressOrHostName::*;
let (bind_address, dst_addr_length) = match atyp
{
0x01 =>
{
const dst_addr_length: usize = 4;
while(unlikely!(this.bytes_read_so_far < SizeOfFixedHeader + dst_addr_length))
{
this.read_reply_bytes()?
}
// NOTE: Works on ARM 32-bit as BIND.ADDR is 4-byte (32-bit) aligned.
let bind_address = InternetProtocolAddress(IpAddr::from(unsafe { *(this.small_reply_packet_buffer.get_unchecked(SizeOfFixedHeader) as *mut u8 as *mut [u8; dst_addr_length]) }));
(bind_address, dst_addr_length)
}
0x04 =>
{
const dst_addr_length: usize = 16;
while(unlikely!(self.bytes_read_so_far < SizeOfFixedHeader + dst_addr_length))
{
this.read_reply_bytes()?
}
// NOTE: Works on ARM 32-bit as BIND.ADDR is 4-byte (32-bit) aligned.
let bind_address = InternetProtocolAddress(IpAddr::from(unsafe { *(this.small_reply_packet_buffer.get_unchecked(SizeOfFixedHeader) as *mut u8 as *mut [u8; dst_addr_length]) }));
(bind_address, dst_addr_length)
}
0x03 =>
{
const SizeOfNumberOfOctetsOfHostName: usize = 1;
if unlikely!(this.bytes_read_so_far == SizeOfFixedHeader)
{
this.read_reply_bytes()?;
}
let number_of_octets_in_host_name = (unsafe { *this.small_reply_packet_buffer.get_unchecked(SizeOfFixedHeader) });
if unlikely!(number_of_octets_in_host_name == 0)
{
return error(HostNameInReplyWasEmpty)
}
if unlikely!(number_of_octets_in_host_name > MaximumSizeOfHostName as u8)
{
return error(HostNameInReplyWasTooLarge(number_of_octets_in_host_name))
}
let number_of_octets_in_host_name = number_of_octets_in_host_name as usize;
let dst_addr_length = SizeOfNumberOfOctetsOfHostName + number_of_octets_in_host_name;
while(unlikely!(self.bytes_read_so_far < SizeOfFixedHeader + dst_addr_length))
{
this.read_reply_bytes()?
}
let mut host_name = ArrayVec::new();
unsafe
{
copy_nonoverlapping(this.small_reply_packet_buffer.get_unchecked(SizeOfFixedHeader + SizeOfNumberOfOctetsOfHostName), host_name.as_mut_ptr(), number_of_octets_in_host_name);
host_name.set_len(number_of_octets_in_host_name)
}
let bind_address = HostName(host_name);
(bind_address, dst_addr_length)
}
_ => return error(ReplyContainedAnUnrecognisedAddressType(atyp)),
};
let offset_to_bndport = SizeOfFixedHeader + dst_addr_length;
while(unlikely!(self.bytes_read_so_far < offset_to_bndport + SizeOfBNDPORT))
{
this.read_reply_bytes()?
}
// Uses copy_nonoverlapping as might not be 16-bit aligned on 32-bit ARM platforms, which will cause a ?SIGBUS.
let mut bind_port_octets: [u8; SizeOfBNDPORT] = unsafe { uninitialized() };
unsafe { copy_nonoverlapping(this.small_reply_packet_buffer.get_unchecked(offset_to_bndport), (&mut bind_port_octets) as *mut [u8; SizeOfBNDPORT] as *mut u8, SizeOfBNDPORT) }
let bind_port = u16::from_be_bytes(bind_port_octets);
let bound_socket = BoundSocketAddress
{
address: bind_address,
port: bind_port,
};
Ok((this.unencrypted_stream, bound_socket))
}
#[inline(always)]
fn read_reply_bytes(&mut self) -> Result<(), CompleteError>
{
let mut buffer = &mut self.small_reply_packet_buffer[self.bytes_read_so_far..];
debug_assert_ne!(buffer.len(), 0, "should never try a read of zero bytes");
let bytes_read = unencrypted_stream.read_data(buffer).map_err(|io_error| CompleteError::SocketRead(io_error))?;
debug_assert_ne!(bytes_read, 0, "A read of zero should not be possible unless the buffer is zero");
self.bytes_read_so_far += bytes_read;
Ok(())
}
}
|
use std::collections::HashMap;
use {Capacity, Curviness, RoomNumber, Room, SquareFeet, View};
lazy_static! {
static ref BOSTON_SIDE_ROOMS: Vec<RoomNumber<'static>> = vec![
r!(244, "C"), r!(244, "B"), r!(252), r!(321),
r!(341), r!(344), r!(345), r!(371),
r!(372), r!(373), r!(374), r!(375),
r!(376), r!(377), r!(378), r!(379, "B"),
r!(379, "A"), r!(381), r!(380), r!(472),
r!(473), r!(474), r!(475), r!(476),
r!(477), r!(478), r!(479, "B"), r!(479, "A"),
r!(421, "B"), r!(421, "C"), r!(446), r!(447),
r!(448), r!(450), r!(451), r!(452),
r!(464), r!(465), r!(466), r!(467),
r!(543), r!(544), r!(545), r!(548),
r!(549, "B"), r!(549, "A"), r!(550), r!(551),
r!(552), r!(553), r!(564), r!(565),
r!(566), r!(569), r!(570), r!(571),
r!(572, "B"), r!(572, "A"), r!(573), r!(574),
r!(575), r!(577), r!(578, "B"), r!(578, "A"),
r!(643), r!(644), r!(645, "B"), r!(645, "A"),
r!(647), r!(648), r!(649), r!(650),
r!(652), r!(653), r!(664), r!(665),
r!(667), r!(670), r!(672), r!(673),
r!(674), r!(675), r!(678), r!(775),
r!(776), r!(778), r!(779), r!(780),
r!(741, "A"), r!(741, "B"), r!(743), r!(744),
r!(746), r!(747), r!(748, "C"), r!(748, "B"),
r!(873), r!(874), r!(875), r!(878),
r!(865), r!(866), r!(871), r!(872),
r!(846), r!(973), r!(974), r!(975),
r!(976), r!(977), r!(978), r!(979),
r!(972), r!(971), r!(966), r!(921, "B"),
r!(946), r!(945), r!(1073), r!(1074),
r!(1075), r!(1076), r!(1077), r!(1078, "B"),
r!(1078, "A"), r!(1072), r!(1066), r!(1065),
r!(1064), r!(1052, "A"), r!(1052, "B"), r!(1021, "C"),
r!(1021, "A"), r!(1043), r!(1044), r!(1045), r!(1046)
];
static ref MINOR_CURVES: Vec<RoomNumber<'static>> = vec![
r!(631, "D"), r!(252), r!(340, "A"), r!(438),
r!(545), r!(627), r!(875), r!(839),
r!(866), r!(871), r!(945), r!(966),
r!(971), r!(938), r!(1034), r!(1066)
];
static ref MAJOR_CURVES: Vec<RoomNumber<'static>> = vec![
r!(1021, "A"), r!(933), r!(833), r!(776),
r!(667), r!(337), r!(327), r!(228, "A")
];
static ref AWFUL_CURVES: Vec<RoomNumber<'static>> = vec![
r!(1043), r!(1036), r!(1039), r!(939),
r!(936), r!(733), r!(729), r!(628),
r!(575), r!(446), r!(548), r!(328)
];
static ref CAPACITIES_AND_SIZES: Vec<(RoomNumber<'static>, Capacity, SquareFeet)> = vec![
(r!(939), Capacity::Double, 194),
(r!(340, "B"), Capacity::Double, 204),
(r!(341), Capacity::Double, 204),
(r!(440), Capacity::Double, 207),
(r!(548), Capacity::Double, 207),
(r!(941), Capacity::Double, 215),
(r!(824), Capacity::Double, 219),
(r!(1024), Capacity::Double, 220),
(r!(322, "C"), Capacity::Double, 220),
(r!(924), Capacity::Double, 224),
(r!(446), Capacity::Double, 226),
(r!(422, "B"), Capacity::Double, 227),
(r!(921, "C"), Capacity::Double, 228),
(r!(1036), Capacity::Double, 231),
(r!(379, "A"), Capacity::Double, 232),
(r!(522, "B"), Capacity::Double, 233),
(r!(627), Capacity::Double, 238),
(r!(1021, "D"), Capacity::Double, 239),
(r!(1022, "B"), Capacity::Double, 240),
(r!(421, "C"), Capacity::Double, 240),
(r!(521, "C"), Capacity::Double, 240),
(r!(832), Capacity::Double, 241),
(r!(1078, "B"), Capacity::Double, 243),
(r!(645, "B"), Capacity::Double, 243),
(r!(451), Capacity::Double, 244),
(r!(572, "B"), Capacity::Double, 245),
(r!(978), Capacity::Double, 245),
(r!(340, "A"), Capacity::Double, 246),
(r!(675), Capacity::Double, 246),
(r!(922, "C"), Capacity::Double, 247),
(r!(1052, "A"), Capacity::Double, 248),
(r!(932), Capacity::Double, 248),
(r!(537), Capacity::Double, 250),
(r!(738, "B"), Capacity::Double, 250),
(r!(840), Capacity::Double, 252),
(r!(533), Capacity::Double, 253),
(r!(472), Capacity::Double, 255),
(r!(464), Capacity::Double, 256),
(r!(553), Capacity::Double, 256),
(r!(329), Capacity::Double, 257),
(r!(664), Capacity::Double, 257),
(r!(780), Capacity::Double, 257),
(r!(322, "B"), Capacity::Double, 258),
(r!(344), Capacity::Double, 259),
(r!(428), Capacity::Double, 259),
(r!(652), Capacity::Double, 259),
(r!(252), Capacity::Double, 260),
(r!(1040), Capacity::Double, 261),
(r!(721), Capacity::Double, 261),
(r!(940), Capacity::Double, 264),
(r!(971), Capacity::Double, 264),
(r!(224, "A"), Capacity::Double, 265),
(r!(228, "A"), Capacity::Double, 266),
(r!(424, "A"), Capacity::Double, 267),
(r!(524), Capacity::Double, 267),
(r!(225), Capacity::Double, 268),
(r!(324), Capacity::Double, 268),
(r!(326), Capacity::Double, 268),
(r!(433), Capacity::Double, 268),
(r!(724), Capacity::Double, 268),
(r!(438), Capacity::Double, 271),
(r!(650), Capacity::Double, 271),
(r!(624, "A"), Capacity::Double, 272),
(r!(821), Capacity::Double, 272),
(r!(371), Capacity::Double, 273),
(r!(866), Capacity::Double, 273),
(r!(321), Capacity::Double, 274),
(r!(575), Capacity::Double, 274),
(r!(833), Capacity::Double, 274),
(r!(778), Capacity::Double, 277),
(r!(878), Capacity::Double, 277),
(r!(729), Capacity::Double, 278),
(r!(1064), Capacity::Double, 282),
(r!(635), Capacity::Double, 283),
(r!(1032), Capacity::Double, 285),
(r!(467), Capacity::Double, 285),
(r!(732), Capacity::Double, 285),
(r!(337), Capacity::Double, 287),
(r!(328), Capacity::Double, 294),
(r!(846), Capacity::Double, 296),
(r!(776), Capacity::Double, 297),
(r!(1066), Capacity::Double, 298),
(r!(1072), Capacity::Double, 298),
(r!(1039), Capacity::Double, 299),
(r!(871), Capacity::Double, 303),
(r!(381), Capacity::Double, 304),
(r!(931), Capacity::Double, 304),
(r!(933), Capacity::Double, 304),
(r!(741, "A"), Capacity::Double, 312),
(r!(634), Capacity::Double, 313),
(r!(966), Capacity::Double, 313),
(r!(921, "B"), Capacity::Double, 320),
(r!(1021, "C"), Capacity::Double, 326),
(r!(945), Capacity::Double, 329),
(r!(733), Capacity::Double, 346),
(r!(452), Capacity::Single, 117),
(r!(653), Capacity::Single, 117),
(r!(779), Capacity::Single, 119),
(r!(427), Capacity::Single, 120),
(r!(527), Capacity::Single, 121),
(r!(540), Capacity::Single, 121),
(r!(626), Capacity::Single, 121),
(r!(372), Capacity::Single, 122),
(r!(665), Capacity::Single, 122),
(r!(379, "B"), Capacity::Single, 123),
(r!(447), Capacity::Single, 123),
(r!(473), Capacity::Single, 123),
(r!(549, "B"), Capacity::Single, 123),
(r!(631, "B"), Capacity::Single, 123),
(r!(728), Capacity::Single, 123),
(r!(731), Capacity::Single, 123),
(r!(973), Capacity::Single, 123),
(r!(322, "D"), Capacity::Single, 124),
(r!(325), Capacity::Single, 124),
(r!(373), Capacity::Single, 124),
(r!(378), Capacity::Single, 124),
(r!(465), Capacity::Single, 124),
(r!(479, "B"), Capacity::Single, 124),
(r!(525), Capacity::Single, 124),
(r!(624, "B"), Capacity::Single, 124),
(r!(740), Capacity::Single, 124),
(r!(1031, "C"), Capacity::Single, 125),
(r!(1045), Capacity::Single, 125),
(r!(1073), Capacity::Single, 125),
(r!(552), Capacity::Single, 125),
(r!(636), Capacity::Single, 125),
(r!(640), Capacity::Single, 125),
(r!(648), Capacity::Single, 125),
(r!(725), Capacity::Single, 125),
(r!(727), Capacity::Single, 125),
(r!(865), Capacity::Single, 125),
(r!(1022, "C"), Capacity::Single, 126),
(r!(1044), Capacity::Single, 126),
(r!(224, "B"), Capacity::Single, 126),
(r!(422, "C"), Capacity::Single, 126),
(r!(424, "B"), Capacity::Single, 126),
(r!(466), Capacity::Single, 126),
(r!(551), Capacity::Single, 126),
(r!(574), Capacity::Single, 126),
(r!(577), Capacity::Single, 126),
(r!(633), Capacity::Single, 126),
(r!(649), Capacity::Single, 126),
(r!(730), Capacity::Single, 126),
(r!(743), Capacity::Single, 126),
(r!(748, "C"), Capacity::Single, 126),
(r!(478), Capacity::Single, 127),
(r!(578, "B"), Capacity::Single, 127),
(r!(647), Capacity::Single, 127),
(r!(775), Capacity::Single, 127),
(r!(873), Capacity::Single, 127),
(r!(565), Capacity::Single, 128),
(r!(739), Capacity::Single, 128),
(r!(747), Capacity::Single, 128),
(r!(922, "D"), Capacity::Single, 128),
(r!(1031, "B"), Capacity::Single, 129),
(r!(421, "B"), Capacity::Single, 129),
(r!(522, "C"), Capacity::Single, 129),
(r!(872), Capacity::Single, 129),
(r!(1034), Capacity::Single, 130),
(r!(1052, "B"), Capacity::Single, 130),
(r!(228, "B"), Capacity::Single, 130),
(r!(539), Capacity::Single, 130),
(r!(1065), Capacity::Single, 131),
(r!(345), Capacity::Single, 131),
(r!(629), Capacity::Single, 131),
(r!(534), Capacity::Single, 132),
(r!(639), Capacity::Single, 132),
(r!(645, "A"), Capacity::Single, 132),
(r!(672), Capacity::Single, 132),
(r!(521, "B"), Capacity::Single, 133),
(r!(572, "A"), Capacity::Single, 133),
(r!(1074), Capacity::Single, 134),
(r!(549, "A"), Capacity::Single, 134),
(r!(974), Capacity::Single, 134),
(r!(550), Capacity::Single, 135),
(r!(631, "C"), Capacity::Single, 135),
(r!(874), Capacity::Single, 135),
(r!(1033), Capacity::Single, 136),
(r!(448), Capacity::Single, 136),
(r!(573), Capacity::Single, 136),
(r!(632), Capacity::Single, 136),
(r!(674), Capacity::Single, 136),
(r!(644), Capacity::Single, 137),
(r!(673), Capacity::Single, 137),
(r!(377), Capacity::Single, 138),
(r!(477), Capacity::Single, 138),
(r!(570), Capacity::Single, 138),
(r!(571), Capacity::Single, 138),
(r!(637), Capacity::Single, 138),
(r!(744), Capacity::Single, 138),
(r!(1076), Capacity::Single, 139),
(r!(475), Capacity::Single, 139),
(r!(566), Capacity::Single, 139),
(r!(746), Capacity::Single, 139),
(r!(569), Capacity::Single, 140),
(r!(1077), Capacity::Single, 141),
(r!(474), Capacity::Single, 141),
(r!(748, "B"), Capacity::Single, 141),
(r!(977), Capacity::Single, 142),
(r!(374), Capacity::Single, 143),
(r!(544), Capacity::Single, 145),
(r!(380), Capacity::Single, 147),
(r!(643), Capacity::Single, 147),
(r!(825), Capacity::Single, 147),
(r!(670), Capacity::Single, 148),
(r!(972), Capacity::Single, 148),
(r!(532), Capacity::Single, 150),
(r!(925), Capacity::Single, 150),
(r!(376), Capacity::Single, 152),
(r!(741, "B"), Capacity::Single, 153),
(r!(1025), Capacity::Single, 154),
(r!(578, "A"), Capacity::Single, 154),
(r!(375), Capacity::Single, 155),
(r!(625), Capacity::Single, 155),
(r!(564), Capacity::Single, 156),
(r!(678), Capacity::Single, 156),
(r!(1038), Capacity::Single, 157),
(r!(426), Capacity::Single, 157),
(r!(526), Capacity::Single, 157),
(r!(543), Capacity::Single, 160),
(r!(738, "C"), Capacity::Single, 160),
(r!(244, "B"), Capacity::Single, 161),
(r!(538), Capacity::Single, 161),
(r!(979), Capacity::Single, 162),
(r!(479, "A"), Capacity::Single, 163),
(r!(839), Capacity::Single, 163),
(r!(1078, "A"), Capacity::Single, 164),
(r!(976), Capacity::Single, 166),
(r!(545), Capacity::Single, 170),
(r!(936), Capacity::Single, 174),
(r!(938), Capacity::Single, 175),
(r!(450), Capacity::Single, 180),
(r!(638), Capacity::Single, 181),
(r!(667), Capacity::Single, 183),
(r!(429), Capacity::Single, 186),
(r!(1043), Capacity::Single, 187),
(r!(1046), Capacity::Single, 190),
(r!(1075), Capacity::Single, 190),
(r!(946), Capacity::Single, 191),
(r!(330), Capacity::Single, 192),
(r!(975), Capacity::Single, 193),
(r!(631, "D"), Capacity::Single, 197),
(r!(1021, "A"), Capacity::Single, 199),
(r!(476), Capacity::Single, 208),
(r!(628), Capacity::Single, 212),
(r!(327), Capacity::Single, 216),
(r!(244, "C"), Capacity::Single, 222),
(r!(535), Capacity::Single, 239),
(r!(875), Capacity::Single, 253),
];
/// A list of all rooms. Data provided by Cosmos Darwin and others.
pub static ref ROOMS: HashMap<RoomNumber<'static>, Room<'static>> = {
CAPACITIES_AND_SIZES.iter()
.map(|&(ref number, ref capacity, ref size)| (number.clone(),
Room {
grt_section: ::data::GRT_SECTIONS.values()
.filter(|section| section.numbers.contains(&number))
.next()
.expect(&format!(
"Inconsistent data: room {:?} doesn't have a GRT!",
number))
.clone(),
capacity: capacity.clone(),
size: *size, // SquareFeet is Copy
view: if BOSTON_SIDE_ROOMS.contains(number) {
View::Boston
} else {
View::Cambridge
},
curviness: if MINOR_CURVES.contains(number) {
Curviness::Minor
} else if MAJOR_CURVES.contains(number) {
Curviness::Major
} else if AWFUL_CURVES.contains(number) {
Curviness::Awful
} else {
Curviness::Square
},
bathroom: ::data::BATHROOMS.iter()
.filter(|bathroom| bathroom.rooms.contains(number))
.next()
.expect("Inconsistent data: room doesn't have a bathroom!")
.clone(),
})
).collect()
};
}
|
use std::env;
use serenity::{
async_trait,
model::{channel::Message, gateway::Ready},
prelude::*,
};
use tokio::signal::unix::{signal, SignalKind};
struct Handler;
#[async_trait]
impl EventHandler for Handler {
async fn message(&self, ctx: Context, msg: Message) {
if msg.content == "!ping" {
if let Err(why) = msg.channel_id.say(&ctx.http, "Pong!!").await {
println!("Error sending message: {:?}", why);
}
}
}
async fn ready(&self, _: Context, ready: Ready) {
println!("{} is connected!", ready.user.name);
}
}
#[tokio::main]
async fn main() {
{
use std::process;
println!("My pid is {}", process::id());
}
let token = env::var("BOT_TOKEN").expect("token");
let intents = GatewayIntents::MESSAGE_CONTENT
| GatewayIntents::GUILD_MESSAGES
| GatewayIntents::DIRECT_MESSAGES;
let mut client = Client::builder(&token, intents)
.event_handler(Handler)
.await
.expect("Err creating client");
let shard_man = client.shard_manager.clone();
let mut sigint = signal(SignalKind::interrupt()).expect("Could not register SIGINT handler");
let mut sigterm = signal(SignalKind::terminate()).expect("Could not register SIGTERM handler");
tokio::spawn(async move {
tokio::select! {
_ = sigint.recv() => println!("SIGINT"),
_ = sigterm.recv() => println!("SIGTERM"),
}
shard_man.lock().await.shutdown_all().await;
});
if let Err(why) = client.start().await {
println!("Client error: {:?}", why);
} else {
println!("Client shutdown.");
}
}
|
mod buildings;
mod bus_stops;
mod half_map;
mod initial;
mod parking_blackholes;
mod remove_disconnected;
mod sidewalk_finder;
mod turns;
pub use self::buildings::make_all_buildings;
pub use self::bus_stops::{make_bus_stops, verify_bus_routes};
pub use self::half_map::make_half_map;
pub use self::initial::lane_specs::{get_lane_types, RoadSpec};
pub use self::initial::{Hint, Hints, InitialMap};
pub use self::parking_blackholes::redirect_parking_blackholes;
pub use self::remove_disconnected::remove_disconnected_roads;
pub use self::turns::make_all_turns;
|
import driver.session;
import front.ast;
import std.map.hashmap;
import std.option;
import std.option.some;
import std.option.none;
import std._int;
import util.common;
type fn_id_of_local = std.map.hashmap[ast.def_id, ast.def_id];
type env = rec(option.t[ast.def_id] current_context, // fn or obj
fn_id_of_local idmap,
session.session sess);
fn update_env_for_item(&env e, @ast.item i) -> env {
alt (i.node) {
case (ast.item_fn(?name, _, _, ?id, _)) {
ret rec(current_context = some(id) with e);
}
case (ast.item_obj(_, _, _, ?ids, _)) {
ret rec(current_context = some(ids.ty) with e);
}
case (_) {
ret e;
}
}
}
fn update_env_for_expr(&env e, @ast.expr x) -> env {
alt (x.node) {
case (ast.expr_for(?d, _, _, _)) {
alt (d.node) {
case (ast.decl_local(?local)) {
auto curr_context =
option.get[ast.def_id](e.current_context);
e.idmap.insert(local.id, curr_context);
}
case (_) {
}
}
}
case (ast.expr_for_each(?d, _, _, _)) {
alt (d.node) {
case (ast.decl_local(?local)) {
auto curr_context =
option.get[ast.def_id](e.current_context);
e.idmap.insert(local.id, curr_context);
}
case (_) {
}
}
}
case (_) { }
}
ret e;
}
fn update_env_for_block(&env e, &ast.block b) -> env {
auto curr_context = option.get[ast.def_id](e.current_context);
for each (@tup(ast.ident, ast.block_index_entry) it in
b.node.index.items()) {
alt (it._1) {
case (ast.bie_local(?local)) {
e.idmap.insert(local.id, curr_context);
}
case (_) {
}
}
}
ret e;
}
fn fold_expr_path(&env e, &ast.span sp, &ast.path p, &option.t[ast.def] d,
ast.ann a) -> @ast.expr {
auto local_id;
alt (option.get[ast.def](d)) {
case (ast.def_local(?id)) {
local_id = id;
}
case (_) {
ret @fold.respan[ast.expr_](sp, ast.expr_path(p, d, a));
}
}
auto curr_context = option.get[ast.def_id](e.current_context);
auto x = ast.def_id_of_def(option.get[ast.def](d));
auto def_context = option.get[ast.def_id](e.idmap.find(x));
if (curr_context != def_context) {
e.sess.span_err(sp, "attempted dynamic environment-capture");
}
ret @fold.respan[ast.expr_](sp, ast.expr_path(p, d, a));
}
fn check_for_captures(session.session sess, @ast.crate crate) {
let fold.ast_fold[env] fld = fold.new_identity_fold[env]();
fld = @rec( update_env_for_item = bind update_env_for_item(_,_),
update_env_for_block = bind update_env_for_block(_,_),
update_env_for_expr = bind update_env_for_expr(_,_),
fold_expr_path = bind fold_expr_path(_,_,_,_,_)
with *fld);
auto idmap = common.new_def_hash[ast.def_id]();
auto e = rec(current_context = none[ast.def_id], idmap = idmap,
sess = sess);
fold.fold_crate[env](e, fld, crate);
}
// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
|
use crate::cli;
use crate::fs;
#[cfg(test)]
mod test;
static DECK_SIZE: i64 = 119315717514047;
#[allow(dead_code)]
static ITR_COUNT: i64 = 101741582076661;
pub fn run() {
let ops = parse();
let rev_ops = invert_ops(&ops, 10007);
let it = slam_shuffle(&ops, 10007, 2019);
println!("{}", it);
let it = slam_shuffle(&rev_ops, 10007, it);
println!("{}", it);
let rev_ops = invert_ops(&ops, DECK_SIZE);
let it = slam_shuffle(&rev_ops, DECK_SIZE, 2020);
println!("{}", it);
let it = slam_shuffle(&ops, DECK_SIZE, it);
println!("{}", it);
}
fn invert_ops(ops: &Vec<Op>, deck_size: i64) -> Vec<Op> {
let mut rev_ops = ops.to_vec();
rev_ops.reverse();
for i in 0..(rev_ops.len()) {
rev_ops[i] = rev_ops[i].invert(deck_size);
}
rev_ops
}
fn slam_shuffle(ops: &Vec<Op>, deck_size: i64, card: i64) -> i64 {
ops.iter().fold(card, |idx, op| op.perform(deck_size, idx))
}
fn multiply(mut a: i64, mut b: i64, modulus: i64) -> i64 {
let mut result = 0;
a %= modulus; // this'll be unneeded for us, but useful in general
while b > 0 {
if b % 2 == 1 {
result = (result + a) % modulus;
}
a = (a * 2) % modulus;
b /= 2;
}
result
}
#[allow(dead_code)]
fn gcd(mut a: i64, mut b: i64) -> i64 {
if a < b {
return gcd(b, a);
}
while b > 0 {
let temp = a;
a = b;
b = temp % b;
}
a
}
fn inverse(a: i64, n: i64) -> i64 {
let mut t = 0;
let mut newt = 1;
let mut r = n;
let mut newr = a;
while newr != 0 {
let quotient = r / newr;
let pt = t;
t = newt;
newt = pt - quotient * newt;
let pr = r;
r = newr;
newr = pr - quotient * newr;
}
if r > 1 {
panic!("{} is not invertible mod {}", a, n);
}
if t < 0 {
t = t + n;
}
t
}
#[derive(Debug, Clone)]
enum Op {
Reverse(),
Cut(i64),
Deal(i64),
}
impl Op {
fn perform(&self, deck_size: i64, idx: i64) -> i64 {
match self {
Op::Reverse() => (deck_size - idx - 1) % deck_size,
Op::Cut(n) => (deck_size + idx - n) % deck_size,
Op::Deal(n) => multiply(idx, *n, deck_size),
}
}
fn invert(&self, deck_size: i64) -> Op {
match self {
Op::Reverse() => Op::Reverse(),
Op::Cut(n) => Op::Cut(-1 * n),
Op::Deal(n) => Op::Deal(inverse(*n, deck_size)),
}
}
}
fn parse() -> Vec<Op> {
fs::read_lines(cli::aoc_filename("aoc_2019_22.txt"), |s| {
if s == "deal into new stack" {
Op::Reverse()
} else if s.starts_with("cut") {
Op::Cut(s.split(' ').last().unwrap().parse().unwrap())
} else if s.starts_with("deal") {
Op::Deal(s.split(' ').last().unwrap().parse().unwrap())
} else {
panic!("Unrecognized shuffle '{}'", s)
}
})
.unwrap()
}
|
use std::fmt::Display;
type NodeRef<T> = Option<Box<Node<T>>>;
#[derive(Debug, Default)]
struct Node<T> {
value: T,
left: NodeRef<T>,
right: NodeRef<T>,
}
fn generate_tree(level: usize, counter: &mut i32) -> NodeRef<i32> {
if level == 0 {
return None
} else {
let mut node = Node {
value: *counter,
left: None,
right: None,
};
*counter += 1;
node.left = generate_tree(level - 1, counter);
node.right = generate_tree(level - 1, counter);
Some(Box::new(node))
}
}
fn print_tree<T: Display>(root: &NodeRef<T>, level: usize) {
match root {
Some(node) => {
print_tree::<T>(&node.left, level + 1);
for _ in 0..level {
print!(" ");
}
println!("{}", node.value);
print_tree::<T>(&node.right, level + 1);
},
None => {},
}
}
fn invert_tree<T: Clone>(root: NodeRef<T>) -> NodeRef<T>{
match root {
Some(node) => {
Some(Box::new(Node {
value: node.value.clone(),
left: invert_tree::<T>(node.right),
right: invert_tree::<T>(node.left),
}))
},
None => None
}
}
fn main() {
let mut counter = 1;
let tree = generate_tree(3, &mut counter);
println!("\n\t* * * Initial binary tree * * *\n");
print_tree(&tree, 0);
println!("\n\t* * * Inverted binary tree * * *\n");
print_tree(&invert_tree(tree), 0)
} |
//! Tests on the command API
use std::collections::HashMap;
use commands::{self, ComMap};
// Commands for the commands tests
pub fn command_map() -> ComMap {
let mut map: ComMap = HashMap::new();
map.insert("command".to_string(), command);
map.insert("panic_command".to_string(), panic_command);
map
}
#[test]
pub fn command() {
println!("command being run!");
}
pub fn panic_command() {
panic!("panic_command panic")
}
#[test]
fn add_commands() {
// Command
assert!(commands::set("new_command".to_string(), command)
.is_none(), "New command was duplicate!");
assert!(commands::get("new_command").is_some(),
"Unable to add command")
}
#[test]
fn get_command() {
assert!(commands::get("command").is_some(), "Could not get command!");
}
#[test]
fn run_command() {
let command = commands::get("command")
.expect("Command not found");
command();
}
#[test]
#[should_panic(expected = "command panic")]
fn run_panic_command() {
let command = commands::get("panic_command")
.expect("Command not found");
command();
}
|
use std::net::{IpAddr, SocketAddr};
use std::ops::{Deref, DerefMut};
use ctrlc::set_handler;
pub use simple_socket::PostServing;
use n3_machine::HostMachine;
use n3_net_protocol::{Request, Response, PORT};
pub type SocketServer = simple_socket::SocketServer<Request, Response>;
pub(crate) trait Handle<H>
where
H: Deref<Target = HostMachine> + DerefMut,
{
fn handle(self, host: &mut H) -> Response;
}
impl<H> Handle<H> for Request
where
H: Deref<Target = HostMachine> + DerefMut,
{
fn handle(self, host: &mut H) -> Response {
match self {
Self::Load { work, query } => host
.load(work, query)
.map(|num_machines| Response::Load { num_machines }),
Self::Spawn {
id_primaries,
program,
} => Ok(Response::Status {
status: host.spawn(id_primaries, program),
}),
Self::Status { work } => host.status(work).map(|status| Response::Status { status }),
Self::Join { work } => host.join(work).map(|status| Response::Status { status }),
Self::Terminate { work } => host
.terminate(work)
.map(|status| Response::Status { status }),
}
// error handler
.map_or_else(
|e| Response::Error {
message: format!("{:?}", e),
},
|x| x,
)
}
}
pub fn run_server<H, P>(mut host: H, ip: IpAddr, post: P)
where
H: Deref<Target = HostMachine> + DerefMut,
P: Fn(&mut SocketServer) -> PostServing,
{
let socket = SocketAddr::new(ip, PORT);
let backlog = Default::default();
let server = SocketServer::try_new(socket, backlog).unwrap();
let handler = host.handler.clone();
set_handler(move || handler.set_running(false)).unwrap();
let handler = host.handler.clone();
server
.run(
|x| Handle::<H>::handle(x, &mut host),
|s| {
if handler.get_running() {
post(s)
} else {
PostServing::Stop
}
},
)
.unwrap()
}
|
pub mod columns;
pub mod input;
pub use columns::AddColumns;
pub use input::InputStream;
type Row = csv::StringRecord;
|
#[doc = "Reader of register OPTR"]
pub type R = crate::R<u32, super::OPTR>;
#[doc = "Writer for register OPTR"]
pub type W = crate::W<u32, super::OPTR>;
#[doc = "Register OPTR `reset()`'s with value 0xf000_0000"]
impl crate::ResetValue for super::OPTR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0xf000_0000
}
}
#[doc = "Reader of field `RDP`"]
pub type RDP_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `RDP`"]
pub struct RDP_W<'a> {
w: &'a mut W,
}
impl<'a> RDP_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0xff) | ((value as u32) & 0xff);
self.w
}
}
#[doc = "Reader of field `BOREN`"]
pub type BOREN_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `BOREN`"]
pub struct BOREN_W<'a> {
w: &'a mut W,
}
impl<'a> BOREN_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8);
self.w
}
}
#[doc = "Reader of field `BORF_LEV`"]
pub type BORF_LEV_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `BORF_LEV`"]
pub struct BORF_LEV_W<'a> {
w: &'a mut W,
}
impl<'a> BORF_LEV_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 << 9)) | (((value as u32) & 0x03) << 9);
self.w
}
}
#[doc = "Reader of field `BORR_LEV`"]
pub type BORR_LEV_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `BORR_LEV`"]
pub struct BORR_LEV_W<'a> {
w: &'a mut W,
}
impl<'a> BORR_LEV_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 << 11)) | (((value as u32) & 0x03) << 11);
self.w
}
}
#[doc = "Reader of field `nRST_STOP`"]
pub type NRST_STOP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `nRST_STOP`"]
pub struct NRST_STOP_W<'a> {
w: &'a mut W,
}
impl<'a> NRST_STOP_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 << 13)) | (((value as u32) & 0x01) << 13);
self.w
}
}
#[doc = "Reader of field `nRST_STDBY`"]
pub type NRST_STDBY_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `nRST_STDBY`"]
pub struct NRST_STDBY_W<'a> {
w: &'a mut W,
}
impl<'a> NRST_STDBY_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 << 14)) | (((value as u32) & 0x01) << 14);
self.w
}
}
#[doc = "Reader of field `nRSTS_HDW`"]
pub type NRSTS_HDW_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `nRSTS_HDW`"]
pub struct NRSTS_HDW_W<'a> {
w: &'a mut W,
}
impl<'a> NRSTS_HDW_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15);
self.w
}
}
#[doc = "Reader of field `IDWG_SW`"]
pub type IDWG_SW_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `IDWG_SW`"]
pub struct IDWG_SW_W<'a> {
w: &'a mut W,
}
impl<'a> IDWG_SW_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16);
self.w
}
}
#[doc = "Reader of field `IWDG_STOP`"]
pub type IWDG_STOP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `IWDG_STOP`"]
pub struct IWDG_STOP_W<'a> {
w: &'a mut W,
}
impl<'a> IWDG_STOP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17);
self.w
}
}
#[doc = "Reader of field `IWDG_STDBY`"]
pub type IWDG_STDBY_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `IWDG_STDBY`"]
pub struct IWDG_STDBY_W<'a> {
w: &'a mut W,
}
impl<'a> IWDG_STDBY_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18);
self.w
}
}
#[doc = "Reader of field `WWDG_SW`"]
pub type WWDG_SW_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `WWDG_SW`"]
pub struct WWDG_SW_W<'a> {
w: &'a mut W,
}
impl<'a> WWDG_SW_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 << 19)) | (((value as u32) & 0x01) << 19);
self.w
}
}
#[doc = "Reader of field `RAM_PARITY_CHECK`"]
pub type RAM_PARITY_CHECK_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `RAM_PARITY_CHECK`"]
pub struct RAM_PARITY_CHECK_W<'a> {
w: &'a mut W,
}
impl<'a> RAM_PARITY_CHECK_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 22)) | (((value as u32) & 0x01) << 22);
self.w
}
}
#[doc = "Reader of field `nBOOT_SEL`"]
pub type NBOOT_SEL_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `nBOOT_SEL`"]
pub struct NBOOT_SEL_W<'a> {
w: &'a mut W,
}
impl<'a> NBOOT_SEL_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 << 24)) | (((value as u32) & 0x01) << 24);
self.w
}
}
#[doc = "Reader of field `nBOOT1`"]
pub type NBOOT1_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `nBOOT1`"]
pub struct NBOOT1_W<'a> {
w: &'a mut W,
}
impl<'a> NBOOT1_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 << 25)) | (((value as u32) & 0x01) << 25);
self.w
}
}
#[doc = "Reader of field `nBOOT0`"]
pub type NBOOT0_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `nBOOT0`"]
pub struct NBOOT0_W<'a> {
w: &'a mut W,
}
impl<'a> NBOOT0_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 << 26)) | (((value as u32) & 0x01) << 26);
self.w
}
}
#[doc = "Reader of field `NRST_MODE`"]
pub type NRST_MODE_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `NRST_MODE`"]
pub struct NRST_MODE_W<'a> {
w: &'a mut W,
}
impl<'a> NRST_MODE_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 << 27)) | (((value as u32) & 0x03) << 27);
self.w
}
}
#[doc = "Reader of field `IRHEN`"]
pub type IRHEN_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `IRHEN`"]
pub struct IRHEN_W<'a> {
w: &'a mut W,
}
impl<'a> IRHEN_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 << 29)) | (((value as u32) & 0x01) << 29);
self.w
}
}
impl R {
#[doc = "Bits 0:7 - Read protection level"]
#[inline(always)]
pub fn rdp(&self) -> RDP_R {
RDP_R::new((self.bits & 0xff) as u8)
}
#[doc = "Bit 8 - BOR reset Level"]
#[inline(always)]
pub fn boren(&self) -> BOREN_R {
BOREN_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bits 9:10 - These bits contain the VDD supply level threshold that activates the reset"]
#[inline(always)]
pub fn borf_lev(&self) -> BORF_LEV_R {
BORF_LEV_R::new(((self.bits >> 9) & 0x03) as u8)
}
#[doc = "Bits 11:12 - These bits contain the VDD supply level threshold that releases the reset."]
#[inline(always)]
pub fn borr_lev(&self) -> BORR_LEV_R {
BORR_LEV_R::new(((self.bits >> 11) & 0x03) as u8)
}
#[doc = "Bit 13 - nRST_STOP"]
#[inline(always)]
pub fn n_rst_stop(&self) -> NRST_STOP_R {
NRST_STOP_R::new(((self.bits >> 13) & 0x01) != 0)
}
#[doc = "Bit 14 - nRST_STDBY"]
#[inline(always)]
pub fn n_rst_stdby(&self) -> NRST_STDBY_R {
NRST_STDBY_R::new(((self.bits >> 14) & 0x01) != 0)
}
#[doc = "Bit 15 - nRSTS_HDW"]
#[inline(always)]
pub fn n_rsts_hdw(&self) -> NRSTS_HDW_R {
NRSTS_HDW_R::new(((self.bits >> 15) & 0x01) != 0)
}
#[doc = "Bit 16 - Independent watchdog selection"]
#[inline(always)]
pub fn idwg_sw(&self) -> IDWG_SW_R {
IDWG_SW_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bit 17 - Independent watchdog counter freeze in Stop mode"]
#[inline(always)]
pub fn iwdg_stop(&self) -> IWDG_STOP_R {
IWDG_STOP_R::new(((self.bits >> 17) & 0x01) != 0)
}
#[doc = "Bit 18 - Independent watchdog counter freeze in Standby mode"]
#[inline(always)]
pub fn iwdg_stdby(&self) -> IWDG_STDBY_R {
IWDG_STDBY_R::new(((self.bits >> 18) & 0x01) != 0)
}
#[doc = "Bit 19 - Window watchdog selection"]
#[inline(always)]
pub fn wwdg_sw(&self) -> WWDG_SW_R {
WWDG_SW_R::new(((self.bits >> 19) & 0x01) != 0)
}
#[doc = "Bit 22 - SRAM parity check control"]
#[inline(always)]
pub fn ram_parity_check(&self) -> RAM_PARITY_CHECK_R {
RAM_PARITY_CHECK_R::new(((self.bits >> 22) & 0x01) != 0)
}
#[doc = "Bit 24 - nBOOT_SEL"]
#[inline(always)]
pub fn n_boot_sel(&self) -> NBOOT_SEL_R {
NBOOT_SEL_R::new(((self.bits >> 24) & 0x01) != 0)
}
#[doc = "Bit 25 - Boot configuration"]
#[inline(always)]
pub fn n_boot1(&self) -> NBOOT1_R {
NBOOT1_R::new(((self.bits >> 25) & 0x01) != 0)
}
#[doc = "Bit 26 - nBOOT0 option bit"]
#[inline(always)]
pub fn n_boot0(&self) -> NBOOT0_R {
NBOOT0_R::new(((self.bits >> 26) & 0x01) != 0)
}
#[doc = "Bits 27:28 - NRST_MODE"]
#[inline(always)]
pub fn nrst_mode(&self) -> NRST_MODE_R {
NRST_MODE_R::new(((self.bits >> 27) & 0x03) as u8)
}
#[doc = "Bit 29 - Internal reset holder enable bit"]
#[inline(always)]
pub fn irhen(&self) -> IRHEN_R {
IRHEN_R::new(((self.bits >> 29) & 0x01) != 0)
}
}
impl W {
#[doc = "Bits 0:7 - Read protection level"]
#[inline(always)]
pub fn rdp(&mut self) -> RDP_W {
RDP_W { w: self }
}
#[doc = "Bit 8 - BOR reset Level"]
#[inline(always)]
pub fn boren(&mut self) -> BOREN_W {
BOREN_W { w: self }
}
#[doc = "Bits 9:10 - These bits contain the VDD supply level threshold that activates the reset"]
#[inline(always)]
pub fn borf_lev(&mut self) -> BORF_LEV_W {
BORF_LEV_W { w: self }
}
#[doc = "Bits 11:12 - These bits contain the VDD supply level threshold that releases the reset."]
#[inline(always)]
pub fn borr_lev(&mut self) -> BORR_LEV_W {
BORR_LEV_W { w: self }
}
#[doc = "Bit 13 - nRST_STOP"]
#[inline(always)]
pub fn n_rst_stop(&mut self) -> NRST_STOP_W {
NRST_STOP_W { w: self }
}
#[doc = "Bit 14 - nRST_STDBY"]
#[inline(always)]
pub fn n_rst_stdby(&mut self) -> NRST_STDBY_W {
NRST_STDBY_W { w: self }
}
#[doc = "Bit 15 - nRSTS_HDW"]
#[inline(always)]
pub fn n_rsts_hdw(&mut self) -> NRSTS_HDW_W {
NRSTS_HDW_W { w: self }
}
#[doc = "Bit 16 - Independent watchdog selection"]
#[inline(always)]
pub fn idwg_sw(&mut self) -> IDWG_SW_W {
IDWG_SW_W { w: self }
}
#[doc = "Bit 17 - Independent watchdog counter freeze in Stop mode"]
#[inline(always)]
pub fn iwdg_stop(&mut self) -> IWDG_STOP_W {
IWDG_STOP_W { w: self }
}
#[doc = "Bit 18 - Independent watchdog counter freeze in Standby mode"]
#[inline(always)]
pub fn iwdg_stdby(&mut self) -> IWDG_STDBY_W {
IWDG_STDBY_W { w: self }
}
#[doc = "Bit 19 - Window watchdog selection"]
#[inline(always)]
pub fn wwdg_sw(&mut self) -> WWDG_SW_W {
WWDG_SW_W { w: self }
}
#[doc = "Bit 22 - SRAM parity check control"]
#[inline(always)]
pub fn ram_parity_check(&mut self) -> RAM_PARITY_CHECK_W {
RAM_PARITY_CHECK_W { w: self }
}
#[doc = "Bit 24 - nBOOT_SEL"]
#[inline(always)]
pub fn n_boot_sel(&mut self) -> NBOOT_SEL_W {
NBOOT_SEL_W { w: self }
}
#[doc = "Bit 25 - Boot configuration"]
#[inline(always)]
pub fn n_boot1(&mut self) -> NBOOT1_W {
NBOOT1_W { w: self }
}
#[doc = "Bit 26 - nBOOT0 option bit"]
#[inline(always)]
pub fn n_boot0(&mut self) -> NBOOT0_W {
NBOOT0_W { w: self }
}
#[doc = "Bits 27:28 - NRST_MODE"]
#[inline(always)]
pub fn nrst_mode(&mut self) -> NRST_MODE_W {
NRST_MODE_W { w: self }
}
#[doc = "Bit 29 - Internal reset holder enable bit"]
#[inline(always)]
pub fn irhen(&mut self) -> IRHEN_W {
IRHEN_W { w: self }
}
}
|
mod day1;
mod day2;
mod day3;
mod day4;
mod day5;
mod day6;
mod day7;
mod day8;
mod day12;
mod day16;
mod day22;
mod day24;
mod utils;
mod cartesian;
mod math;
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
|
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use super::super::kernel::waiter::*;
use super::super::kernel::timer::*;
use super::super::kernel::time::*;
use super::super::fs::file::*;
use super::super::task::*;
use super::super::qlib::common::*;
use super::super::qlib::mem::block::*;
use super::super::qlib::linux_def::*;
use super::super::syscalls::syscalls::*;
use super::super::perflog::*;
pub fn SysRead(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let fd = args.arg0 as i32;
let addr = args.arg1 as u64;
let size = args.arg2 as i64;
let n = Read(task, fd, addr, size)?;
task.ioUsage.AccountReadSyscall(n);
return Ok(n)
}
pub fn Read(task: &Task, fd: i32, addr: u64, size: i64) -> Result<i64> {
task.PerfGoto(PerfType::Read);
defer!(task.PerfGofrom(PerfType::Read));
let file = task.GetFile(fd)?;
if !file.Flags().Read {
return Err(Error::SysError(SysErr::EBADF))
}
if size < 0 {
return Err(Error::SysError(SysErr::EINVAL))
}
if size == 0 {
return Ok(0)
}
let iov = IoVec::NewFromAddr(addr, size as usize);
let mut iovs: [IoVec; 1] = [iov];
let n = readv(task, &file, &mut iovs)?;
/*if fd == 0 {
use alloc::string::ToString;
use super::super::qlib::util::*;
let str = CString::ToStringWithLen(addr, n as usize).to_string();
info!("(Data)Read({}): {}", n, str);
}*/
return Ok(n)
}
pub fn SysPread64(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let fd = args.arg0 as i32;
let addr = args.arg1 as u64;
let size = args.arg2 as i64;
let offset = args.arg3 as i64;
let n = Pread64(task, fd, addr, size, offset)?;
task.ioUsage.AccountReadSyscall(n);
return Ok(n)
}
pub fn Pread64(task: &Task, fd: i32, addr: u64, size: i64, offset: i64) -> Result<i64> {
task.PerfGoto(PerfType::Read);
defer!(task.PerfGofrom(PerfType::Read));
let file = task.GetFile(fd)?;
if offset < 0 {
return Err(Error::SysError(SysErr::EINVAL))
}
if !file.Flags().Pread {
return Err(Error::SysError(SysErr::ESPIPE))
}
if !file.Flags().Read {
return Err(Error::SysError(SysErr::EBADF))
}
if size < 0 {
return Err(Error::SysError(SysErr::EINVAL))
}
if size == 0 {
return Ok(0)
}
let iov = IoVec::NewFromAddr(addr, size as usize);
let mut iovs: [IoVec; 1] = [iov];
return preadv(task, &file, &mut iovs, offset)
}
pub fn SysReadv(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let fd = args.arg0 as i32;
let addr = args.arg1 as u64;
let iovcnt = args.arg2 as i32;
let n = Readv(task, fd, addr, iovcnt)?;
task.ioUsage.AccountReadSyscall(n);
return Ok(n)
}
pub fn Readv(task: &Task, fd: i32, addr: u64, iovcnt: i32) -> Result<i64> {
let file = task.GetFile(fd)?;
if !file.Flags().Read {
return Err(Error::SysError(SysErr::EBADF))
}
if iovcnt < 0 {
return Err(Error::SysError(SysErr::EINVAL))
}
let mut dsts = task.IovsFromAddr(addr, iovcnt as usize)?;
return readv(task, &file, &mut dsts);
}
pub fn SysPreadv(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let fd = args.arg0 as i32;
let addr = args.arg1 as u64;
let iovcnt = args.arg2 as i32;
let offset = args.arg3 as i64;
let n = Preadv(task, fd, addr, iovcnt, offset)?;
task.ioUsage.AccountReadSyscall(n);
return Ok(n)
}
pub fn SysPreadv2(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
// While the syscall is
// preadv2(int fd, struct iovec* iov, int iov_cnt, off_t offset, int flags)
// the linux internal call
// (https://elixir.bootlin.com/linux/v4.18/source/fs/read_write.c#L1248)
// splits the offset argument into a high/low value for compatibility with
// 32-bit architectures. The flags argument is the 5th argument.
let fd = args.arg0 as i32;
let addr = args.arg1 as u64;
let iovcnt = args.arg2 as i32;
let offset = args.arg3 as i64;
let flags = args.arg5 as i32;
if offset < -1 {
return Err(Error::SysError(SysErr::EINVAL))
}
// Check flags field.
// Note: qkernel does not implement the RWF_HIPRI feature, but the flag is
// accepted as a valid flag argument for preadv2.
if flags & !(Flags::RWF_VALID) != 0 {
return Err(Error::SysError(SysErr::EOPNOTSUPP))
}
if offset == -1 {
let n = Readv(task, fd, addr, iovcnt)?;
task.ioUsage.AccountWriteSyscall(n);
return Ok(n);
}
let n = Preadv(task, fd, addr, iovcnt, offset)?;
task.ioUsage.AccountReadSyscall(n);
return Ok(n)
}
pub fn Preadv(task: &Task, fd: i32, addr: u64, iovcnt: i32, offset: i64) -> Result<i64> {
let file = task.GetFile(fd)?;
if offset < 0 {
return Err(Error::SysError(SysErr::EINVAL))
}
if !file.Flags().Pread {
return Err(Error::SysError(SysErr::ESPIPE))
}
if !file.Flags().Read {
return Err(Error::SysError(SysErr::EBADF))
}
if iovcnt < 0 {
return Err(Error::SysError(SysErr::EINVAL))
}
if iovcnt == 0 {
return Ok(0)
}
let mut dsts = task.IovsFromAddr(addr, iovcnt as usize)?;
return preadv(task, &file, &mut dsts, offset);
}
fn RepReadv(task: &Task, f: &File, dsts: &mut [IoVec]) -> Result<i64> {
let len = Iovs(dsts).Count();
let mut count = 0;
let mut dsts = dsts;
let mut tmp;
loop {
match f.Readv(task, dsts) {
Err(e) => {
if count > 0 {
return Ok(count)
}
return Err(e)
}
Ok(n) => {
if n == 0 {
return Ok(count);
}
count += n;
if count == len as i64 {
return Ok(count)
}
tmp = Iovs(dsts).DropFirst(n as usize);
if tmp.len() == 0 {
return Ok(count)
}
dsts = &mut tmp;
}
}
}
}
fn readv(task: &Task, f: &File, dsts: &mut [IoVec]) -> Result<i64> {
task.CheckIOVecPermission(dsts, true)?;
let wouldBlock = f.WouldBlock();
if !wouldBlock {
return RepReadv(task, f, dsts)
}
match f.Readv(task, dsts) {
Err(e) => {
if e != Error::SysError(SysErr::EWOULDBLOCK) || f.Flags().NonBlocking {
return Err(e);
}
}
Ok(n) => {
return Ok(n)
}
};
let mut deadline = None;
let dl = f.FileOp.RecvTimeout();
if dl < 0 {
return Err(Error::SysError(SysErr::EWOULDBLOCK));
}
if dl > 0 {
let now = MonotonicNow();
deadline = Some(Time(now + dl));
}
let general = task.blocker.generalEntry.clone();
f.EventRegister(task, &general, EVENT_READ);
defer!(f.EventUnregister(task, &general));
let len = Iovs(dsts).Count();
let mut count = 0;
let mut dsts = dsts;
let mut tmp;
loop {
loop {
match f.Readv(task, dsts) {
Err(Error::SysError(SysErr::EWOULDBLOCK)) => {
if count > 0 {
return Ok(count)
}
break;
},
Err(e) => {
if count > 0 {
return Ok(count)
}
return Err(e);
}
Ok(n) => {
if n == 0 {
return Ok(count);
}
count += n;
if count == len as i64 {
return Ok(count)
}
tmp = Iovs(dsts).DropFirst(n as usize);
dsts = &mut tmp;
}
}
}
match task.blocker.BlockWithMonoTimer(true, deadline) {
Err(Error::ErrInterrupted) => {
return Err(Error::SysError(SysErr::ERESTARTSYS));
}
Err(Error::SysError(SysErr::ETIMEDOUT)) => {
return Err(Error::SysError(SysErr::EAGAIN));
}
Err(e) => {
return Err(e);
}
_ => ()
}
}
}
fn preadv(task: &Task, f: &File, dsts: &mut [IoVec], offset: i64) -> Result<i64> {
task.CheckIOVecPermission(dsts, true)?;
match f.Preadv(task, dsts, offset) {
Err(e) => {
if e != Error::SysError(SysErr::EWOULDBLOCK) || f.Flags().NonBlocking {
return Err(e);
}
}
Ok(n) => {
return Ok(n)
}
};
let general = task.blocker.generalEntry.clone();
f.EventRegister(task, &general, EVENT_READ);
defer!(f.EventUnregister(task, &general));
loop {
match f.Preadv(task, dsts, offset) {
Err(Error::SysError(SysErr::EWOULDBLOCK)) => (),
Err(e) => {
return Err(e);
}
Ok(n) => {
return Ok(n);
}
}
match task.blocker.BlockWithMonoTimer(true, None) {
Err(e) => {
return Err(e);
}
_ => ()
}
}
} |
use std::convert::AsRef;
use std::ffi::CString;
use std::fs;
use std::io;
use std::os;
use std::path::{Path, PathBuf};
use cfg_if::cfg_if;
cfg_if! {
if #[cfg(windows)] {
use std::os::windows::io::AsRawHandle;
} else {
use std::os::unix::io::AsRawFd;
}
}
pub use glob::{GlobError, Pattern, PatternError};
/// Compiles a glob pattern, to a `Pattern`
///
/// The compiled pattern can be used to then match paths or strings.
///
/// Returns `Err(PatternError)` if the input is not a valid glob
pub fn glob<S: AsRef<str>>(pattern: S) -> Result<Pattern, PatternError> {
Pattern::new(pattern.as_ref())
}
/// Get the underlying raw file descriptor for a File
#[cfg(windows)]
pub fn get_file_descriptor<F: AsRawHandle>(f: &F) -> os::windows::io::RawHandle {
f.as_raw_handle()
}
/// Get the underlying raw file descriptor for a File
#[cfg(not(windows))]
pub fn get_file_descriptor<F: AsRawFd>(f: &F) -> os::unix::io::RawFd {
f.as_raw_fd()
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum NativeLibraryKind {
/// Static library (e.g. `libfoo.a` on Linux or `foo.lib` on Windows/MSVC)
Static {
/// Whether to bundle objects from static library into produced lib
bundle: Option<bool>,
/// Whether to link static library without throwing any object files away
whole_archive: Option<bool>,
},
/// Dynamic library (e.g. `libfoo.so` on Linux)
Dylib {
/// Whether the dynamic library will be linked only if it satisfies some undefined symbol
as_needed: Option<bool>,
},
/// Dynamic library without a corresponding import library.
RawDylib,
/// A macOS-specific kind of dynamic library
Framework {
/// Whether the framework will be linked only if it satisfies some undefined symbol
as_needed: Option<bool>,
},
/// The library kind wasn't specified, dylibs are assumed by default
Unspecified,
}
impl NativeLibraryKind {
pub fn has_modifiers(&self) -> bool {
match self {
Self::Static {
bundle,
whole_archive,
} => bundle.is_some() || whole_archive.is_some(),
Self::Dylib { as_needed } | Self::Framework { as_needed } => as_needed.is_some(),
Self::RawDylib | Self::Unspecified => false,
}
}
}
// Unfortunately, on windows, it looks like msvcrt.dll is silently translating
// verbatim paths under the hood to non-verbatim paths! This manifests itself as
// gcc looking like it cannot accept paths of the form `\\?\C:\...`, but the
// real bug seems to lie in msvcrt.dll.
//
// Verbatim paths are generally pretty rare, but the implementation of
// `fs::canonicalize` currently generates paths of this form, meaning that we're
// going to be passing quite a few of these down to gcc, so we need to deal with
// this case.
//
// For now we just strip the "verbatim prefix" of `\\?\` from the path. This
// will probably lose information in some cases, but there's not a whole lot
// more we can do with a buggy msvcrt...
//
// For some more information, see this comment:
// https://github.com/rust-lang/rust/issues/25505#issuecomment-102876737
#[cfg(windows)]
pub fn fix_windows_verbatim_for_gcc(p: &Path) -> PathBuf {
use std::ffi::OsString;
use std::path;
let mut components = p.components();
let prefix = match components.next() {
Some(path::Component::Prefix(p)) => p,
_ => return p.to_path_buf(),
};
match prefix.kind() {
path::Prefix::VerbatimDisk(disk) => {
let mut base = OsString::from(format!("{}:", disk as char));
base.push(components.as_path());
PathBuf::from(base)
}
path::Prefix::VerbatimUNC(server, share) => {
let mut base = OsString::from(r"\\");
base.push(server);
base.push(r"\");
base.push(share);
base.push(components.as_path());
PathBuf::from(base)
}
_ => p.to_path_buf(),
}
}
#[cfg(not(windows))]
pub fn fix_windows_verbatim_for_gcc(p: &Path) -> PathBuf {
p.to_path_buf()
}
pub enum LinkOrCopy {
Link,
Copy,
}
/// Copies `p` into `q`, preferring to use hard-linking if possible. If
/// `q` already exists, it is removed first.
/// The result indicates which of the two operations has been performed.
pub fn link_or_copy<P: AsRef<Path>, Q: AsRef<Path>>(p: P, q: Q) -> io::Result<LinkOrCopy> {
let p = p.as_ref();
let q = q.as_ref();
if q.exists() {
fs::remove_file(&q)?;
}
match fs::hard_link(p, q) {
Ok(()) => Ok(LinkOrCopy::Link),
Err(_) => match fs::copy(p, q) {
Ok(_) => Ok(LinkOrCopy::Copy),
Err(e) => Err(e),
},
}
}
#[derive(Debug)]
pub enum RenameOrCopyRemove {
Rename,
CopyRemove,
}
/// Rename `p` into `q`, preferring to use `rename` if possible.
/// If `rename` fails (rename may fail for reasons such as crossing
/// filesystem), fallback to copy & remove
pub fn rename_or_copy_remove<P: AsRef<Path>, Q: AsRef<Path>>(
p: P,
q: Q,
) -> io::Result<RenameOrCopyRemove> {
let p = p.as_ref();
let q = q.as_ref();
match fs::rename(p, q) {
Ok(()) => Ok(RenameOrCopyRemove::Rename),
Err(_) => match fs::copy(p, q) {
Ok(_) => {
fs::remove_file(p)?;
Ok(RenameOrCopyRemove::CopyRemove)
}
Err(e) => Err(e),
},
}
}
#[cfg(all(unix, target_env = "wasi"))]
pub fn path_to_c_string(p: &Path) -> CString {
use std::ffi::OsStr;
use std::os::wasi::ffi::OsStrExt;
let p: &OsStr = p.as_ref();
CString::new(p.as_bytes()).unwrap()
}
#[cfg(all(unix, not(target_env = "wasi")))]
pub fn path_to_c_string(p: &Path) -> CString {
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
let p: &OsStr = p.as_ref();
CString::new(p.as_bytes()).unwrap()
}
#[cfg(windows)]
pub fn path_to_c_string(p: &Path) -> CString {
CString::new(p.to_str().unwrap()).unwrap()
}
|
/* I guess this problem was removed?
*/
pub fn bloom(data: &Vec<&str>, hashes: [fn(&[u8]) -> u64; 3], value: &str)
-> bool {
let mut bloom = [false; 20];
let mut val;
for item in data.iter() {
for hash in hashes.iter() {
val = hash(item.as_bytes()) % 20;
if val <= 20 {
bloom[val as usize] = true;
}
}
}
println!("{:?}", bloom);
if hashes.iter().all(|f| {
let _v = f(value.as_bytes()) % 20;
if _v <= 20 {
bloom[_v as usize]
} else {
false
}}) {
true
} else {
false
}
}
pub fn djb2(bytes: &[u8]) -> u64 {
let mut hash: u64 = 5381;
for b in bytes {
// hash * 33 + c
hash = (hash.wrapping_shr(5) + hash) + (*b as u64);
}
return hash;
}
pub fn fnv(bytes: &[u8]) -> u64 {
let mut hash = 0xcbf29ce484222325;
for b in bytes {
hash = hash ^ (*b as u64);
hash = hash.wrapping_mul(0x100000001b3);
}
return hash;
}
pub fn jenkins(bytes: &[u8]) -> u64 {
let mut hash = 0;
for b in bytes {
hash += *b as u64;
hash += hash.wrapping_shr(10);
hash ^= hash.wrapping_shl(6);
}
hash += hash.wrapping_shr(3);
hash ^= hash.wrapping_shl(11);
hash += hash.wrapping_shr(15);
return hash;
}
|
extern crate mio;
pub mod impl_thread;
pub mod impl_mio;
|
#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)]
pub fn rint(x: f64) -> f64 {
let one_over_e = 1.0 / f64::EPSILON;
let as_u64: u64 = x.to_bits();
let exponent: u64 = as_u64 >> 52 & 0x7ff;
let is_positive = (as_u64 >> 63) == 0;
if exponent >= 0x3ff + 52 {
x
} else {
let ans = if is_positive {
x + one_over_e - one_over_e
} else {
x - one_over_e + one_over_e
};
if ans == 0.0 {
if is_positive {
0.0
} else {
-0.0
}
} else {
ans
}
}
}
// PowerPC tests are failing on LLVM 13: https://github.com/rust-lang/rust/issues/88520
#[cfg(not(target_arch = "powerpc64"))]
#[cfg(test)]
mod tests {
use super::rint;
#[test]
fn negative_zero() {
assert_eq!(rint(-0.0_f64).to_bits(), (-0.0_f64).to_bits());
}
#[test]
fn sanity_check() {
assert_eq!(rint(-1.0), -1.0);
assert_eq!(rint(2.8), 3.0);
assert_eq!(rint(-0.5), -0.0);
assert_eq!(rint(0.5), 0.0);
assert_eq!(rint(-1.5), -2.0);
assert_eq!(rint(1.5), 2.0);
}
}
|
use proconio::input;
fn solve(n: usize, takahashi: bool, a: &[usize], memo: &mut Vec<Vec<Option<usize>>>) -> usize {
if n == 0 {
return 0;
}
if let Some(ans) = memo[n][takahashi as usize] {
return ans;
}
let mut result = 0;
for &x in a {
if x <= n {
let s = solve(n - x, !takahashi, a, memo);
result = result.max(n - s);
}
}
memo[n][takahashi as usize] = Some(result);
result
}
fn main() {
input! {
n: usize,
k: usize,
a: [usize; k],
};
let mut memo = vec![vec![None; 2]; n + 1];
let ans = solve(n, true, &a, &mut memo);
println!("{}", ans);
}
|
//! A simple gossip & broadcast primitive for best-effort metadata distribution
//! between IOx nodes.
//!
//! # Peers
//!
//! Peers are uniquely identified by their self-reported "identity" UUID. A
//! unique UUID is generated for each gossip instance, ensuring the identity
//! changes across restarts of the underlying node.
//!
//! An identity is associated with an immutable socket address used for peer
//! communication.
//!
//! # Transport
//!
//! Prefer small payloads where possible, and expect loss of some messages -
//! this primitive provides *best effort* delivery.
//!
//! This implementation sends unicast UDP frames between peers, with support for
//! both control frames & user payloads. The maximum UDP message size is 65,507
//! bytes ([`MAX_USER_PAYLOAD_BYTES`] for application-level payloads), but a
//! packet this large is fragmented into smaller (at most MTU-sized) packets and
//! is at greater risk of being dropped due to a lost fragment.
//!
//! # Security
//!
//! Messages exchanged between peers are unauthenticated and connectionless -
//! it's trivial to forge a message appearing to come from a different peer, or
//! include malicious payloads.
//!
//! The security model of this implementation expects the peers to be running in
//! a trusted environment, secure from malicious users.
//!
//! # Peer Exchange
//!
//! When a gossip instance is initialised, it advertises itself to the set of
//! user-provided "seed" peers - other gossip instances with fixed, known
//! addresses. The peer then bootstraps the peer list from these seed peers.
//!
//! Peers are discovered through PONG messages from peers, which contain the
//! list of peers the sender has successfully communicated with.
//!
//! On receipt of a PONG frame, a node will send PING frames to all newly
//! discovered peers without adding the peer to its local peer list. Once the
//! discovered peer responds with a PONG, the peer is added to the peer list.
//! This acts as a liveness check, ensuring a node only adds peers it can
//! communicate with to its peer list.
//!
//! ```text
//! ┌──────────┐
//! │ Seed │
//! └──────────┘
//! ▲ │
//! │ │
//! (1) │ │ (2)
//! PING │ │ PONG
//! │ │ (contains Peer A)
//! │ ▼
//! ┌──────────┐
//! │ Local │
//! └──────────┘
//! ▲ │
//! │ │
//! (4) │ │ (3)
//! PONG │ │ PING
//! │ │
//! │ ▼
//! ┌──────────┐
//! │ Peer A │
//! └──────────┘
//! ```
//!
//! The above illustrates this process when the "local" node joins:
//!
//! 1. Send PING messages to all configured seeds
//! 2. Receive a PONG response containing the list of all known peers
//! 3. Send PING frames to all discovered peers - do not add to peer list
//! 4. Receive PONG frames from discovered peers - add to peer list
//!
//! The peer addresses sent during PEX rounds contain the advertised peer
//! identity and the socket address the PONG sender discovered.
//!
//! # Dead Peer Removal
//!
//! All peers are periodically sent a PING frame, and a per-peer counter is
//! incremented. If a message of any sort is received (including the PONG
//! response to the soliciting PING), the peer's counter is reset to 0.
//!
//! Once a peer's counter reaches [`MAX_PING_UNACKED`], indicating a number of
//! PINGs have been sent without receiving any response, the peer is removed
//! from the node's peer list.
//!
//! Dead peers age out of the cluster once all nodes perform the above routine.
//! If a peer dies, it is still sent in PONG messages as part of PEX until it is
//! removed from the sender's peer list, but the receiver of the PONG will not
//! add it to the node's peer list unless it successfully commutates, ensuring
//! dead peers are not propagated.
//!
//! Ageing out dead peers is strictly an optimisation (and not for correctness).
//! A dead peer consumes a tiny amount of RAM, but also will have frames
//! dispatched to it - over time, as the number of dead peers accumulates, this
//! would cause the number of UDP frames sent per broadcast to increase,
//! needlessly increasing gossip traffic.
//!
//! This process is heavily biased towards reliability/deliverability and is too
//! slow for use as a general peer health check.
#![deny(rustdoc::broken_intra_doc_links, rust_2018_idioms)]
#![warn(
clippy::clone_on_ref_ptr,
clippy::dbg_macro,
clippy::explicit_iter_loop,
clippy::future_not_send,
clippy::todo,
clippy::use_self,
missing_copy_implementations,
missing_debug_implementations,
unused_crate_dependencies,
missing_docs
)]
#![allow(clippy::default_constructed_unit_structs)]
mod builder;
mod dispatcher;
mod handle;
mod metric;
mod peers;
mod proto;
mod reactor;
pub(crate) mod seed;
use std::time::Duration;
/// Work around the unused_crate_dependencies false positives for test deps.
#[cfg(test)]
use test_helpers as _;
use workspace_hack as _;
pub use builder::*;
pub use dispatcher::*;
pub use handle::*;
/// The maximum duration of time allotted to performing a DNS resolution against
/// a seed/peer address.
const RESOLVE_TIMEOUT: Duration = Duration::from_secs(5);
/// Defines the interval between PING frames sent to all configured seed peers.
const SEED_PING_INTERVAL: Duration = Duration::from_secs(60);
/// How often a PING frame should be sent to a known peer.
///
/// This value and [`MAX_PING_UNACKED`] defines the approximate duration of time
/// until a dead peer is removed from the peer list.
const PEER_PING_INTERVAL: Duration = Duration::from_secs(30);
/// The maximum payload size allowed.
///
/// Attempting to send a serialised packet (inclusive of control frames/fields)
/// in excess of this amount will result in an error.
const MAX_FRAME_BYTES: usize = 1024 * 10;
/// The frame header overhead for user payloads.
const USER_PAYLOAD_OVERHEAD: usize = 22;
/// The maximum allowed byte size of user payloads.
///
/// Sending payloads of this size is discouraged as it leads to fragmentation of
/// the message and increases the chance of the message being undelivered /
/// dropped. Smaller is always better for UDP transports!
pub const MAX_USER_PAYLOAD_BYTES: usize = MAX_FRAME_BYTES - USER_PAYLOAD_OVERHEAD;
/// The number of PING messages sent to a peer without a response (of any kind)
/// before the peer is considered dead and removed from the peer list.
///
/// Increasing this value does not affect correctness - messages will be sent to
/// this peer for longer before being marked as dead, and the (small amount of)
/// RAM used by this peer will be held for longer.
///
/// This value should be large so that the occasional dropped frame does not
/// cause a peer to be spuriously marked as "dead" - doing so would cause it to
/// miss broadcast frames until it is re-discovered.
const MAX_PING_UNACKED: usize = 10;
#[cfg(test)]
#[allow(clippy::assertions_on_constants)]
mod tests {
use super::*;
#[test]
fn test_max_msg_size() {
assert!(MAX_FRAME_BYTES < 65_536, "cannot exceed UDP maximum");
}
#[test]
fn test_max_user_payload_size() {
assert_eq!(
MAX_USER_PAYLOAD_BYTES, 10_218,
"applications may depend on this value not changing"
);
}
}
|
use crate::actor::telegram_sender::{PushEventMsg, TbSenderActor};
use crate::model::PushEvent;
use actix::Addr;
use actix_web::{web, Error, HttpResponse};
use futures::Future;
pub fn register_push_event(
push_event: web::Json<PushEvent>,
tb: web::Data<Addr<TbSenderActor>>,
) -> impl Future<Item = HttpResponse, Error = Error> {
println!("Push Event: {:?}", push_event);
let msg = PushEventMsg {
reference: push_event.reference.clone(),
};
tb.send(msg)
.then(|_| Ok(HttpResponse::Ok().json("Message Sent")))
}
|
use super::*;
#[test]
fn without_found_errors_badarg() {
with_process_arc(|arc_process| {
let element = Atom::str_to_term("not_found");
let not_element = Atom::str_to_term("not_element");
let slice = &[not_element];
let tail = Atom::str_to_term("tail");
let list = arc_process.improper_list_from_slice(slice, tail);
assert_badarg!(
result(element, list),
format!("list ({}) is improper", list)
);
});
}
#[test]
fn with_found_returns_true() {
with_process_arc(|arc_process| {
let element = Atom::str_to_term("found");
let slice = &[element];
let tail = Atom::str_to_term("tail");
let list = arc_process.improper_list_from_slice(slice, tail);
assert_eq!(result(element, list), Ok(true.into()));
});
}
|
use crate::action::{Action, ActionHandled};
use crate::game_event::{GameEvent, GameEventType};
use crate::room::{closed_message, enter_room, RoomType};
use crate::sound::{AudioEvent, Effect};
use crate::timer::TimerType;
use crate::App;
use crate::room;
// Handle game actions here (Timers).
pub fn handle_action(mut app: &mut App, next_action: Action) {
if app.try_handle_room_action(&next_action).is_some() {
return
}
// Handle system and global actions here.
match next_action {
Action::Message(mut message, game_event_type) => {
message.push('\n');
app.log.push_front(GameEvent {
content: message,
game_event_type: game_event_type,
})
}
Action::Rebooted => {
app.event_queue.schedule_action(Action::Message(
String::from("\"Initiating reboot.\" The room goes black. You notice a coldness quickly creeping into the air and start to shiver. As the air gets thinner and thinner, you slowly slip into unconsciousness."),
GameEventType::Failure,
));
}
Action::Enter(room_type) => {
if app.rooms.get(&room_type).unwrap().is_opened() || cfg!(debug_assertions) {
if room_type != RoomType::Corridor {
app.event_queue
.schedule_action(Action::Audio(AudioEvent::Effect(Effect::Door)));
}
enter_room(&mut app, room_type);
} else {
app.event_queue.schedule_action(Action::Message(
closed_message(room_type),
GameEventType::Failure,
));
}
}
Action::Leave(_) => {}
Action::ShowEnterText => {
app.event_queue.schedule_action(Action::Message(
room::room_intro_text(app.state.current_room).0.into(),
GameEventType::Normal,
));
}
Action::Command(tokens) => app.try_handle_command(tokens),
Action::EnemyAttack => {
if let Some(ref enemy) = app.state.get_current_enemy(app.state.current_room) {
let timers = enemy.get_attack_timers(0);
for timer in timers {
app.event_queue.schedule_timer(timer);
}
app.log.push_front(GameEvent {
content: format!(
"{} You lose {} HP.\n",
enemy.get_enemy_attack_message(),
enemy.get_attack_strength(),
),
game_event_type: GameEventType::Combat,
});
app.state.player.health -= enemy.get_attack_strength();
if app.state.player.health <= 0 {
app.event_queue.schedule_action(Action::PlayerDied);
}
}
}
Action::Attack => {
let damage = app.state.player.attack_strength;
if let Some(ref mut enemy) = app.state.get_current_enemy_mut(app.state.current_room) {
enemy.reduce_health(damage);
let attack_message = enemy.get_attack_message();
let enemy_type = enemy.get_enemy_type();
if enemy.get_health() <= 0 {
app.event_queue
.schedule_action(Action::Audio(AudioEvent::Effect(
Effect::PlayerAttack,
)));
app.log.push_front(GameEvent {
content: enemy.get_death_message(),
game_event_type: GameEventType::Failure,
});
app.event_queue
.emplace_timers(TimerType::EnemyAttack, vec![]);
app.state.enemies.remove(&app.state.current_room);
}
app.log.push_front(GameEvent {
content: format!("{}\n", attack_message),
game_event_type: GameEventType::Combat,
});
} else {
app.event_queue.schedule_action(Action::Message(
String::from("There is nothing you can attack."),
GameEventType::Failure,
));
}
}
Action::PlayerDied => {
app.event_queue.schedule_action(Action::Message(
String::from("You died."),
GameEventType::Failure,
));
}
Action::Dodge => {
let mut attack_timers = app.event_queue.get_timers(TimerType::EnemyAttack);
if attack_timers.is_empty() {
if app.state.enemies.get(&app.state.current_room).is_some() {
app.event_queue.schedule_action(Action::Message(
String::from(
"You dodge the attack. The enemy calmly analyses your movements.",
),
GameEventType::Failure,
));
return;
}
app.event_queue.schedule_action(Action::Message(
String::from("You dodge the attack of your own paranoia..."),
GameEventType::Failure,
));
return;
}
for elem in attack_timers.iter_mut() {
elem.elapsed = 0;
}
if let Some(enemy) = app.state.get_current_enemy(app.state.current_room) {
app.event_queue
.emplace_timers(TimerType::EnemyAttack, enemy.get_attack_timers(0));
}
let enemy_type = app
.state
.enemies
.get(&app.state.current_room)
.unwrap()
.get_enemy_type();
app.event_queue.schedule_action(Action::Message(
String::from(format!("You dodge the {:?}'s attack.", enemy_type)),
GameEventType::Success,
));
}
Action::Tick(dt) => {
app.event_queue.tick(dt);
}
Action::PlayerFinishedReading => {
let room_type = app.state.current_room;
let enemy_option = app.state.get_current_enemy(room_type);
let timers = app.event_queue.get_timers(TimerType::EnemyAttack);
if !timers.is_empty() {
return;
}
match enemy_option {
Some(enemy) => {
let timers = enemy.get_initial_attack_timers();
app.event_queue.schedule_timers(timers);
app.log.push_front(GameEvent {
content: format!("The {:?}'s attack is imminent.\n", enemy.get_enemy_type()),
game_event_type: GameEventType::Combat,
});
}
None => (),
}
}
action => app.log.push_front(GameEvent {
content: format!("Unhandled action: {}\n", action),
game_event_type: GameEventType::Debug,
}),
}
}
|
#![allow(unused_imports)]
#![allow(dead_code)]
use gtk;
use gtk::{BuilderExt, EventBoxExt, ImageExt};
use model::Model;
/*
* Room row widget for the room sidebar.
* Shows the avatar, title and the number of unread messages.
* +-----+----------------------+-----+
* |Image| Room Title | 3 |
* +-----+----------------------+-----+
*/
pub struct Room {
pub builder: gtk::Builder,
pub icon: gtk::Image,
pub title: gtk::Label,
pub notifications: gtk::Label,
pub progress: gtk::ProgressBar,
pub widget: gtk::EventBox,
}
impl Room {
pub fn new() -> Room {
let icon = builder.get_object("user_menu_button").unwrap();
let title = builder.get_object("").unwrap();
let notifications = builder.get_object("").unwrap();
let progress = builder.get_object("").unwrap();
let widget = builder.get_object("").unwrap();
Room {
builder,
icon,
title,
notifications,
progress,
widget,
}
}
}
|
use crate::{error, types};
use faccess::{AccessMode, PathExt};
use snafu::ResultExt;
use std::path::{Path, PathBuf};
pub fn check_working_dir(config: &types::Config) -> error::Result<()> {
let path = Path::new(&config.working_dir);
check_writeable(&path)?;
Ok(())
}
pub fn check_pid_file(config: &types::Config) -> error::Result<()> {
let path = Path::new(&config.pid_file);
check_writeable_file(&path)?;
Ok(())
}
pub fn delete_file(file_path: &str) {
let path = Path::new(&file_path);
let _ = std::fs::remove_file(&path);
}
fn check_writeable_file(path: &Path) -> error::Result<()> {
if path.exists() {
check_is_file(path)?;
check_writeable(path)?;
} else {
check_parent_dir_writeable(path)?;
}
Ok(())
}
fn check_parent_dir_writeable(path: &Path) -> error::Result<()> {
let mut path_buf = PathBuf::new();
path_buf.push(path);
path_buf.pop();
check_writeable(path_buf.as_path())?;
Ok(())
}
fn check_is_file(path: &Path) -> error::Result<()> {
let metadata = std::fs::metadata(path).context(error::PathMetadataError {
path: path.to_string_lossy().to_string(),
})?;
if !metadata.is_file() {
return Err(error::Error::PathNoFile {
path: path.to_string_lossy().to_string(),
});
}
Ok(())
}
fn check_writeable(path: &Path) -> error::Result<()> {
if path.access(AccessMode::READ | AccessMode::WRITE).is_err() {
return Err(error::Error::CouldNotWriteToFileOrDirectory {
path: path.to_string_lossy().to_string(),
});
}
Ok(())
}
|
use crate::error::ApiError;
use actix_web::{get, web, HttpResponse};
mod auth;
mod middleware;
#[macro_export]
macro_rules! dump {
($e:expr) => {
if cfg!(debug_assertions) {
dbg!($e)
} else {
$e
}
};
}
#[get("/ping")]
async fn hello() -> Result<HttpResponse, ApiError> {
Ok(HttpResponse::Ok().body("pong"))
}
pub fn config(cfg: &mut web::ServiceConfig) {
cfg.service(hello);
cfg.service(auth::reg);
cfg.service(auth::login);
}
|
// Copyright 2021 Datafuse Labs.
//
// 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.
#![allow(clippy::too_many_arguments)]
mod statistics;
mod compression;
/// Re-exports meta data structures of current version, i.e. v1
mod current;
mod v0;
mod v1;
mod v2;
mod versions;
pub use compression::Compression;
pub use current::*;
pub use statistics::ClusterKey;
pub use statistics::ClusterStatistics;
pub use statistics::ColumnStatistics;
pub use statistics::Location;
pub use statistics::SnapshotId;
pub use statistics::Statistics;
pub use statistics::StatisticsOfColumns;
pub use versions::testify_version;
pub use versions::SegmentInfoVersion;
pub use versions::SnapshotVersion;
pub use versions::TableSnapshotStatisticsVersion;
pub use versions::Versioned;
|
// Copyright 2016 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.
// aux-build:call-site.rs
// ignore-stage1
#![feature(proc_macro_non_items)]
extern crate call_site;
use call_site::*;
fn main() {
let x1 = 10;
call_site::check!(let x2 = x1;);
let x6 = x5;
}
|
use serde::{Deserialize, Serialize};
use std::fmt::Debug;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Position {
pub x: f32,
pub y: f32,
pub z: f32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DroneDefinedEvent {
pub id: String,
pub ssid: String,
pub ip: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DroneReadyEvent {
pub id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DroneActivatedEvent {
pub id: String,
pub launchpad_id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DroneConnectedEvent {
pub id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DroneStatsUpdatedEvent {
pub id: String,
pub battery: u8,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DroneLaunchedEvent {
pub id: String,
pub mission_id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DroneStartedToNextWaypointEvent {
pub id: String,
pub mission_id: String,
pub waypoint_id: i32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DroneArrivedAtWaypointEvent {
pub id: String,
pub mission_id: String,
pub waypoint_id: i32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DroneMissionCompletedEvent {
pub id: String,
pub mission_id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DroneLandedEvent {
pub id: String,
pub at: Position,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DroneDisconnectedEvent {
pub id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "eventType")]
#[serde(rename_all = "camelCase")]
pub enum DroneEvent {
DroneDefined(DroneDefinedEvent),
DroneReady(DroneReadyEvent),
DroneActivated(DroneActivatedEvent),
DroneConnected(DroneConnectedEvent),
DroneStatsUpdated(DroneStatsUpdatedEvent),
DroneLaunched(DroneLaunchedEvent),
DroneStartedToNextWaypoint(DroneStartedToNextWaypointEvent),
DroneArrivedAtWaypoint(DroneArrivedAtWaypointEvent),
DroneMissionCompleted(DroneMissionCompletedEvent),
DroneLanded(DroneLandedEvent),
DroneDisconnected(DroneDisconnectedEvent),
}
|
#![allow(clippy::all)]
fn parse_command(command: &str) -> (&str, i64) {
let mut c = command.split_whitespace();
let c_name = c
.next()
.unwrap_or_else(|| panic!("Command missing first part: {}", command));
let c_value = c
.next()
.unwrap_or_else(|| panic!("Command missing second part: {}", command))
.parse::<i64>()
.expect("Failed to parse command value.");
if c.next().is_some() {
panic!("Command has unexpected third part: {}", command)
}
(c_name, c_value)
}
pub fn part1(input: String) {
let (final_horizontal, final_depth) =
input
.trim()
.split('\n')
.fold((0, 0), |(horizontal, depth), command| {
let (c_name, c_value) = parse_command(command);
// Increment the horizontal and depth values according
// to the command.
match c_name {
"forward" => (horizontal + c_value, depth),
"up" => (horizontal, depth - c_value),
"down" => (horizontal, depth + c_value),
_ => panic!("Unexpected command type: {}", c_name),
}
});
println!("Final Horizontal: {final_horizontal}");
println!("Final Depth: {final_depth}");
println!("Puzzle Answer: {}", final_horizontal * final_depth);
}
pub fn part2(input: String) {
let (final_horizontal, final_depth, final_aim) =
input
.trim()
.split('\n')
.fold((0, 0, 0), |(horizontal, depth, aim), command| {
let (c_name, c_value) = parse_command(command);
// Increment the horizontal and depth values according
// to the command.
match c_name {
"forward" => (horizontal + c_value, depth + c_value * aim, aim),
"up" => (horizontal, depth, aim - c_value),
"down" => (horizontal, depth, aim + c_value),
_ => panic!("Unexpected command type: {}", c_name),
}
});
println!("Final Horizontal: {}", final_horizontal);
println!("Final Depth: {}", final_depth);
println!("Final Aim: {}", final_aim);
println!("Puzzle Answer: {}", final_horizontal * final_depth);
}
|
#[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::LDODPCTL {
#[doc = r"Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
self.register.set(f(&R { bits }, &mut W { bits }).bits);
}
#[doc = r"Reads the contents of the register"]
#[inline(always)]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r"Writes to the register"]
#[inline(always)]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
self.register.set(
f(&mut W {
bits: Self::reset_value(),
})
.bits,
);
}
#[doc = r"Reset value of the register"]
#[inline(always)]
pub const fn reset_value() -> u32 {
0
}
#[doc = r"Writes the reset value to the register"]
#[inline(always)]
pub fn reset(&self) {
self.register.set(Self::reset_value())
}
}
#[doc = "Possible values of the field `SYSCTL_LDODPCTL_VLDO`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SYSCTL_LDODPCTL_VLDOR {
#[doc = "0.90 V"]
SYSCTL_LDODPCTL_VLDO_0_90V,
#[doc = "0.95 V"]
SYSCTL_LDODPCTL_VLDO_0_95V,
#[doc = "1.00 V"]
SYSCTL_LDODPCTL_VLDO_1_00V,
#[doc = "1.05 V"]
SYSCTL_LDODPCTL_VLDO_1_05V,
#[doc = "1.10 V"]
SYSCTL_LDODPCTL_VLDO_1_10V,
#[doc = "1.15 V"]
SYSCTL_LDODPCTL_VLDO_1_15V,
#[doc = "1.20 V"]
SYSCTL_LDODPCTL_VLDO_1_20V,
#[doc = "1.25 V"]
SYSCTL_LDODPCTL_VLDO_1_25V,
#[doc = "1.30 V"]
SYSCTL_LDODPCTL_VLDO_1_30V,
#[doc = "1.35 V"]
SYSCTL_LDODPCTL_VLDO_1_35V,
#[doc = r"Reserved"]
_Reserved(u8),
}
impl SYSCTL_LDODPCTL_VLDOR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
match *self {
SYSCTL_LDODPCTL_VLDOR::SYSCTL_LDODPCTL_VLDO_0_90V => 18,
SYSCTL_LDODPCTL_VLDOR::SYSCTL_LDODPCTL_VLDO_0_95V => 19,
SYSCTL_LDODPCTL_VLDOR::SYSCTL_LDODPCTL_VLDO_1_00V => 20,
SYSCTL_LDODPCTL_VLDOR::SYSCTL_LDODPCTL_VLDO_1_05V => 21,
SYSCTL_LDODPCTL_VLDOR::SYSCTL_LDODPCTL_VLDO_1_10V => 22,
SYSCTL_LDODPCTL_VLDOR::SYSCTL_LDODPCTL_VLDO_1_15V => 23,
SYSCTL_LDODPCTL_VLDOR::SYSCTL_LDODPCTL_VLDO_1_20V => 24,
SYSCTL_LDODPCTL_VLDOR::SYSCTL_LDODPCTL_VLDO_1_25V => 25,
SYSCTL_LDODPCTL_VLDOR::SYSCTL_LDODPCTL_VLDO_1_30V => 26,
SYSCTL_LDODPCTL_VLDOR::SYSCTL_LDODPCTL_VLDO_1_35V => 27,
SYSCTL_LDODPCTL_VLDOR::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _from(value: u8) -> SYSCTL_LDODPCTL_VLDOR {
match value {
18 => SYSCTL_LDODPCTL_VLDOR::SYSCTL_LDODPCTL_VLDO_0_90V,
19 => SYSCTL_LDODPCTL_VLDOR::SYSCTL_LDODPCTL_VLDO_0_95V,
20 => SYSCTL_LDODPCTL_VLDOR::SYSCTL_LDODPCTL_VLDO_1_00V,
21 => SYSCTL_LDODPCTL_VLDOR::SYSCTL_LDODPCTL_VLDO_1_05V,
22 => SYSCTL_LDODPCTL_VLDOR::SYSCTL_LDODPCTL_VLDO_1_10V,
23 => SYSCTL_LDODPCTL_VLDOR::SYSCTL_LDODPCTL_VLDO_1_15V,
24 => SYSCTL_LDODPCTL_VLDOR::SYSCTL_LDODPCTL_VLDO_1_20V,
25 => SYSCTL_LDODPCTL_VLDOR::SYSCTL_LDODPCTL_VLDO_1_25V,
26 => SYSCTL_LDODPCTL_VLDOR::SYSCTL_LDODPCTL_VLDO_1_30V,
27 => SYSCTL_LDODPCTL_VLDOR::SYSCTL_LDODPCTL_VLDO_1_35V,
i => SYSCTL_LDODPCTL_VLDOR::_Reserved(i),
}
}
#[doc = "Checks if the value of the field is `SYSCTL_LDODPCTL_VLDO_0_90V`"]
#[inline(always)]
pub fn is_sysctl_ldodpctl_vldo_0_90v(&self) -> bool {
*self == SYSCTL_LDODPCTL_VLDOR::SYSCTL_LDODPCTL_VLDO_0_90V
}
#[doc = "Checks if the value of the field is `SYSCTL_LDODPCTL_VLDO_0_95V`"]
#[inline(always)]
pub fn is_sysctl_ldodpctl_vldo_0_95v(&self) -> bool {
*self == SYSCTL_LDODPCTL_VLDOR::SYSCTL_LDODPCTL_VLDO_0_95V
}
#[doc = "Checks if the value of the field is `SYSCTL_LDODPCTL_VLDO_1_00V`"]
#[inline(always)]
pub fn is_sysctl_ldodpctl_vldo_1_00v(&self) -> bool {
*self == SYSCTL_LDODPCTL_VLDOR::SYSCTL_LDODPCTL_VLDO_1_00V
}
#[doc = "Checks if the value of the field is `SYSCTL_LDODPCTL_VLDO_1_05V`"]
#[inline(always)]
pub fn is_sysctl_ldodpctl_vldo_1_05v(&self) -> bool {
*self == SYSCTL_LDODPCTL_VLDOR::SYSCTL_LDODPCTL_VLDO_1_05V
}
#[doc = "Checks if the value of the field is `SYSCTL_LDODPCTL_VLDO_1_10V`"]
#[inline(always)]
pub fn is_sysctl_ldodpctl_vldo_1_10v(&self) -> bool {
*self == SYSCTL_LDODPCTL_VLDOR::SYSCTL_LDODPCTL_VLDO_1_10V
}
#[doc = "Checks if the value of the field is `SYSCTL_LDODPCTL_VLDO_1_15V`"]
#[inline(always)]
pub fn is_sysctl_ldodpctl_vldo_1_15v(&self) -> bool {
*self == SYSCTL_LDODPCTL_VLDOR::SYSCTL_LDODPCTL_VLDO_1_15V
}
#[doc = "Checks if the value of the field is `SYSCTL_LDODPCTL_VLDO_1_20V`"]
#[inline(always)]
pub fn is_sysctl_ldodpctl_vldo_1_20v(&self) -> bool {
*self == SYSCTL_LDODPCTL_VLDOR::SYSCTL_LDODPCTL_VLDO_1_20V
}
#[doc = "Checks if the value of the field is `SYSCTL_LDODPCTL_VLDO_1_25V`"]
#[inline(always)]
pub fn is_sysctl_ldodpctl_vldo_1_25v(&self) -> bool {
*self == SYSCTL_LDODPCTL_VLDOR::SYSCTL_LDODPCTL_VLDO_1_25V
}
#[doc = "Checks if the value of the field is `SYSCTL_LDODPCTL_VLDO_1_30V`"]
#[inline(always)]
pub fn is_sysctl_ldodpctl_vldo_1_30v(&self) -> bool {
*self == SYSCTL_LDODPCTL_VLDOR::SYSCTL_LDODPCTL_VLDO_1_30V
}
#[doc = "Checks if the value of the field is `SYSCTL_LDODPCTL_VLDO_1_35V`"]
#[inline(always)]
pub fn is_sysctl_ldodpctl_vldo_1_35v(&self) -> bool {
*self == SYSCTL_LDODPCTL_VLDOR::SYSCTL_LDODPCTL_VLDO_1_35V
}
}
#[doc = "Values that can be written to the field `SYSCTL_LDODPCTL_VLDO`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SYSCTL_LDODPCTL_VLDOW {
#[doc = "0.90 V"]
SYSCTL_LDODPCTL_VLDO_0_90V,
#[doc = "0.95 V"]
SYSCTL_LDODPCTL_VLDO_0_95V,
#[doc = "1.00 V"]
SYSCTL_LDODPCTL_VLDO_1_00V,
#[doc = "1.05 V"]
SYSCTL_LDODPCTL_VLDO_1_05V,
#[doc = "1.10 V"]
SYSCTL_LDODPCTL_VLDO_1_10V,
#[doc = "1.15 V"]
SYSCTL_LDODPCTL_VLDO_1_15V,
#[doc = "1.20 V"]
SYSCTL_LDODPCTL_VLDO_1_20V,
#[doc = "1.25 V"]
SYSCTL_LDODPCTL_VLDO_1_25V,
#[doc = "1.30 V"]
SYSCTL_LDODPCTL_VLDO_1_30V,
#[doc = "1.35 V"]
SYSCTL_LDODPCTL_VLDO_1_35V,
}
impl SYSCTL_LDODPCTL_VLDOW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _bits(&self) -> u8 {
match *self {
SYSCTL_LDODPCTL_VLDOW::SYSCTL_LDODPCTL_VLDO_0_90V => 18,
SYSCTL_LDODPCTL_VLDOW::SYSCTL_LDODPCTL_VLDO_0_95V => 19,
SYSCTL_LDODPCTL_VLDOW::SYSCTL_LDODPCTL_VLDO_1_00V => 20,
SYSCTL_LDODPCTL_VLDOW::SYSCTL_LDODPCTL_VLDO_1_05V => 21,
SYSCTL_LDODPCTL_VLDOW::SYSCTL_LDODPCTL_VLDO_1_10V => 22,
SYSCTL_LDODPCTL_VLDOW::SYSCTL_LDODPCTL_VLDO_1_15V => 23,
SYSCTL_LDODPCTL_VLDOW::SYSCTL_LDODPCTL_VLDO_1_20V => 24,
SYSCTL_LDODPCTL_VLDOW::SYSCTL_LDODPCTL_VLDO_1_25V => 25,
SYSCTL_LDODPCTL_VLDOW::SYSCTL_LDODPCTL_VLDO_1_30V => 26,
SYSCTL_LDODPCTL_VLDOW::SYSCTL_LDODPCTL_VLDO_1_35V => 27,
}
}
}
#[doc = r"Proxy"]
pub struct _SYSCTL_LDODPCTL_VLDOW<'a> {
w: &'a mut W,
}
impl<'a> _SYSCTL_LDODPCTL_VLDOW<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SYSCTL_LDODPCTL_VLDOW) -> &'a mut W {
unsafe { self.bits(variant._bits()) }
}
#[doc = "0.90 V"]
#[inline(always)]
pub fn sysctl_ldodpctl_vldo_0_90v(self) -> &'a mut W {
self.variant(SYSCTL_LDODPCTL_VLDOW::SYSCTL_LDODPCTL_VLDO_0_90V)
}
#[doc = "0.95 V"]
#[inline(always)]
pub fn sysctl_ldodpctl_vldo_0_95v(self) -> &'a mut W {
self.variant(SYSCTL_LDODPCTL_VLDOW::SYSCTL_LDODPCTL_VLDO_0_95V)
}
#[doc = "1.00 V"]
#[inline(always)]
pub fn sysctl_ldodpctl_vldo_1_00v(self) -> &'a mut W {
self.variant(SYSCTL_LDODPCTL_VLDOW::SYSCTL_LDODPCTL_VLDO_1_00V)
}
#[doc = "1.05 V"]
#[inline(always)]
pub fn sysctl_ldodpctl_vldo_1_05v(self) -> &'a mut W {
self.variant(SYSCTL_LDODPCTL_VLDOW::SYSCTL_LDODPCTL_VLDO_1_05V)
}
#[doc = "1.10 V"]
#[inline(always)]
pub fn sysctl_ldodpctl_vldo_1_10v(self) -> &'a mut W {
self.variant(SYSCTL_LDODPCTL_VLDOW::SYSCTL_LDODPCTL_VLDO_1_10V)
}
#[doc = "1.15 V"]
#[inline(always)]
pub fn sysctl_ldodpctl_vldo_1_15v(self) -> &'a mut W {
self.variant(SYSCTL_LDODPCTL_VLDOW::SYSCTL_LDODPCTL_VLDO_1_15V)
}
#[doc = "1.20 V"]
#[inline(always)]
pub fn sysctl_ldodpctl_vldo_1_20v(self) -> &'a mut W {
self.variant(SYSCTL_LDODPCTL_VLDOW::SYSCTL_LDODPCTL_VLDO_1_20V)
}
#[doc = "1.25 V"]
#[inline(always)]
pub fn sysctl_ldodpctl_vldo_1_25v(self) -> &'a mut W {
self.variant(SYSCTL_LDODPCTL_VLDOW::SYSCTL_LDODPCTL_VLDO_1_25V)
}
#[doc = "1.30 V"]
#[inline(always)]
pub fn sysctl_ldodpctl_vldo_1_30v(self) -> &'a mut W {
self.variant(SYSCTL_LDODPCTL_VLDOW::SYSCTL_LDODPCTL_VLDO_1_30V)
}
#[doc = "1.35 V"]
#[inline(always)]
pub fn sysctl_ldodpctl_vldo_1_35v(self) -> &'a mut W {
self.variant(SYSCTL_LDODPCTL_VLDOW::SYSCTL_LDODPCTL_VLDO_1_35V)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(255 << 0);
self.w.bits |= ((value as u32) & 255) << 0;
self.w
}
}
#[doc = r"Value of the field"]
pub struct SYSCTL_LDODPCTL_VADJENR {
bits: bool,
}
impl SYSCTL_LDODPCTL_VADJENR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _SYSCTL_LDODPCTL_VADJENW<'a> {
w: &'a mut W,
}
impl<'a> _SYSCTL_LDODPCTL_VADJENW<'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 &= !(1 << 31);
self.w.bits |= ((value as u32) & 1) << 31;
self.w
}
}
impl R {
#[doc = r"Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bits 0:7 - LDO Output Voltage"]
#[inline(always)]
pub fn sysctl_ldodpctl_vldo(&self) -> SYSCTL_LDODPCTL_VLDOR {
SYSCTL_LDODPCTL_VLDOR::_from(((self.bits >> 0) & 255) as u8)
}
#[doc = "Bit 31 - Voltage Adjust Enable"]
#[inline(always)]
pub fn sysctl_ldodpctl_vadjen(&self) -> SYSCTL_LDODPCTL_VADJENR {
let bits = ((self.bits >> 31) & 1) != 0;
SYSCTL_LDODPCTL_VADJENR { bits }
}
}
impl W {
#[doc = r"Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bits 0:7 - LDO Output Voltage"]
#[inline(always)]
pub fn sysctl_ldodpctl_vldo(&mut self) -> _SYSCTL_LDODPCTL_VLDOW {
_SYSCTL_LDODPCTL_VLDOW { w: self }
}
#[doc = "Bit 31 - Voltage Adjust Enable"]
#[inline(always)]
pub fn sysctl_ldodpctl_vadjen(&mut self) -> _SYSCTL_LDODPCTL_VADJENW {
_SYSCTL_LDODPCTL_VADJENW { w: self }
}
}
|
//
// line_shape2.rs
// Copyright (C) 2019 Malcolm Ramsay <malramsay64@gmail.com>
// Distributed under terms of the MIT license.
//
use std::f64::consts::PI;
use std::fmt;
use std::slice;
use std::vec;
use anyhow::{bail, Error};
use itertools::{iproduct, Itertools};
use nalgebra::{distance, Point2};
use serde::{Deserialize, Serialize};
use super::Line2;
use crate::traits::{Intersect, Shape};
use crate::Transform2;
/// A Shape constructed from a collection of Lines
///
/// This defines a collection of lines, from one point to another which define the area enclosed by
/// a shape. It is assumed that the lines completely enclose an area, and that the enclosed area is
/// close to the origin.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LineShape {
pub name: String,
pub items: Vec<Line2>,
}
impl<'a> IntoIterator for &'a LineShape {
type Item = &'a Line2;
type IntoIter = slice::Iter<'a, Line2>;
fn into_iter(self) -> Self::IntoIter {
self.items.iter()
}
}
impl fmt::Display for LineShape {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "LineShape {{ {} }}", self.items.iter().format(", "))
}
}
impl Intersect for LineShape {
/// Check whether this shape intersects with another shape
///
/// A ShapeInstance is considered to intersect with another when one of it's components
/// intersects with a component of the other shape. For a square, there is an intersection
/// when a line from one square crosses the other. Each component item of `self` is
/// checked against `other`.
///
fn intersects(&self, other: &Self) -> bool {
// We want to compare every item of the current shape with every item of the other shape.
iproduct!(self.iter(), other.iter()).any(|(s, o)| s.intersects(o))
}
fn area(&self) -> f64 {
// This is the sine of the angle between each point, this is used for every calculation
// so pre-calculate here.
let angle_term: f64 = f64::sin(2. * PI / self.items.len() as f64);
self.iter()
// Calculate the area of the of triangle made by the line and the origin
.map(|p| {
0.5 * angle_term
* distance(&Point2::origin(), &p.start)
* distance(&Point2::origin(), &p.end)
})
.sum()
}
}
impl Shape for LineShape {
type Component = Line2;
fn score(&self, other: &Self) -> Option<f64> {
if self.intersects(other) {
None
} else {
Some(self.area())
}
}
fn enclosing_radius(&self) -> f64 {
self.iter()
.map(|p| distance(&Point2::origin(), &p.start))
// The f64 type doesn't have complete ordering because of Nan and Inf, so the
// standard min/max comparators don't work. Instead we use the f64::max which ignores
// the NAN and max values.
.fold(std::f64::MIN, f64::max)
}
fn get_items(&self) -> Vec<Self::Component> {
self.items.clone()
}
fn iter(&self) -> slice::Iter<'_, Self::Component> {
self.into_iter()
}
fn transform(&self, transform: &Transform2) -> Self {
Self {
name: self.name.clone(),
items: self.into_iter().map(|i| i * transform).collect(),
}
}
}
impl LineShape {
/// Instantiate a LineShape from a collection of radial points
///
/// The input is a Vector of points which are a radial distance from the origin, with the
/// points separated by and equal angle. For example to create a Triangle, which is the shape
/// with the fewest number of sides, we can run
/// ```
/// use crystal_packing::LineShape;
/// let tri = LineShape::from_radial("Triangle", vec![1., 1., 1.]);
/// ```
/// More generally to create a regular polygon with an arbitrary number of sides
/// ```
/// use crystal_packing::LineShape;
/// let sides = 10;
/// let polygon = LineShape::from_radial("Polygon", vec![1.; sides]);
/// ```
///
pub fn from_radial(name: &str, points: Vec<f64>) -> Result<LineShape, Error> {
if points.len() < 3 {
bail!("The number of points provided is too few to create a 2D shape.")
}
let dtheta = 2. * PI / points.len() as f64;
let mut items: Vec<Line2> = vec![];
for (index, (r1, r2)) in points.iter().zip(points.iter().cycle().skip(1)).enumerate() {
let angle = index as f64 * dtheta;
items.push(Line2::new(
(r1 * f64::sin(angle), r1 * f64::cos(angle)),
(r2 * f64::sin(angle + dtheta), r2 * f64::cos(angle + dtheta)),
))
}
Ok(LineShape {
name: String::from(name),
items,
})
}
pub fn polygon(sides: usize) -> Result<LineShape, Error> {
LineShape::from_radial("Polygon", vec![1.; sides])
}
}
#[cfg(test)]
mod test {
use approx::assert_abs_diff_eq;
use super::*;
fn create_square() -> LineShape {
LineShape::from_radial("Square", vec![1., 1., 1., 1.]).unwrap()
}
#[test]
fn init() {
let square = create_square();
assert_eq!(square.name, "Square");
}
#[test]
fn area() {
let square = create_square();
assert_abs_diff_eq!(square.area(), 2.);
}
#[test]
fn max_radius() {
let shape = LineShape::from_radial("iter_test", vec![1., 2., 3., 4.]).unwrap();
assert_abs_diff_eq!(shape.enclosing_radius(), 4.);
assert_abs_diff_eq!(shape.enclosing_radius(), 4.);
}
#[test]
fn intersection() {
let square = create_square();
let transform = Transform2::new(0., (1., 1.));
assert!(square.intersects(&square.transform(&transform)));
}
#[test]
fn corner_no_intersection() {
let square = create_square();
let transform = Transform2::new(0., (2., 2.));
assert!(!square.intersects(&square.transform(&transform)));
}
#[test]
fn self_intersection() {
let square = create_square();
let transform = Transform2::new(0., (0., 0.));
assert!(square.intersects(&square.transform(&transform)));
}
#[test]
fn no_intersection() {
let square = create_square();
let transform = Transform2::new(0., (2.01, 2.01));
assert!(!square.intersects(&square.transform(&transform)));
}
}
|
pub mod app;
pub mod camera;
pub mod ecs;
pub mod input;
pub mod pass;
pub mod pipeline;
pub mod tech;
|
use crate::bssrdf::BSSRDF;
use crate::geometry::vector::cross;
use crate::geometry::vector::dot;
use crate::geometry::vector::face_forward;
use crate::geometry::vector::Cross;
use crate::medium::Medium;
use crate::medium::MediumInterface;
use crate::primitive::Primitive;
use crate::ray::offset_ray_origin;
use crate::ray::Ray;
use crate::reflection::BSDF;
use crate::shape::Shape;
use crate::types::Float;
use crate::Normal3f;
use crate::Point2f;
use crate::Point3f;
use crate::Vector3f;
use crate::SHADOW_EPSILON;
use crate::math;
use crate::math::consts;
use num::Zero;
use std::rc::Rc;
pub trait Interaction<'prim> {
fn get_point(&self) -> Point3f;
fn get_point_error(&self) -> Vector3f;
fn get_time(&self) -> Float;
fn get_normal(&self) -> Normal3f;
fn get_medium(&self, w: Vector3f) -> Option<&'prim Rc<Medium>> {
match self.get_medium_interface() {
Some(interface) => {
let medium = if dot(&w, &self.get_normal()) > 0.0 {
&interface.outside
} else {
&interface.inside
};
match medium {
Some(m) => Some(&m),
None => None,
}
}
None => None,
}
}
fn get_medium_interface(&self) -> Option<&'prim MediumInterface>;
fn set_medium_interface(&mut self, interface: Option<&'prim MediumInterface>);
fn spawn_ray(&self, direction: Vector3f) -> Ray {
let origin = offset_ray_origin(
&self.get_point(),
&self.get_point_error(),
&self.get_normal(),
&direction,
);
Ray::new(
origin,
direction,
consts::INFINITY,
self.get_time(),
// self.get_medium(direction),
)
}
fn spawn_ray_to(&self, to: &Interaction<'prim>) -> Ray {
let origin = offset_ray_origin(
&self.get_point(),
&self.get_point_error(),
&self.get_normal(),
&(to.get_point() - self.get_point()),
);
let target = offset_ray_origin(
&to.get_point(),
&to.get_point_error(),
&to.get_normal(),
&(origin - self.get_point()),
);
let direction = target - origin;
Ray::new(
origin,
direction,
1.0 - SHADOW_EPSILON,
self.get_time(),
// self.get_medium(direction),
)
}
}
#[derive(Clone)]
pub struct Shading {
pub dpdu: Vector3f,
pub dpdv: Vector3f,
pub dndu: Normal3f,
pub dndv: Normal3f,
pub normal: Normal3f,
}
#[derive(Clone)]
pub struct SurfaceInteraction<'prim> {
pub point: Point3f,
pub point_error: Vector3f,
pub time: Float,
pub wo: Vector3f,
pub normal: Normal3f,
pub medium_interface: Option<&'prim MediumInterface>,
pub bsdf: Option<BSDF>,
pub bssrdf: Option<&'prim BSSRDF>,
pub dndu: Vector3f,
pub dndv: Vector3f,
pub dpdu: Vector3f,
pub dpdv: Vector3f,
pub dpdx: Vector3f,
pub dpdy: Vector3f,
pub dudx: Float,
pub dudy: Float,
pub dvdx: Float,
pub dvdy: Float,
pub primitive: Option<&'prim Primitive>,
pub shading: Shading,
pub shape: Option<&'prim Shape>,
pub uv: Point2f,
pub face_index: Option<usize>,
}
impl<'prim> SurfaceInteraction<'prim> {
pub fn new(
point: Point3f,
point_error: Vector3f,
uv: Point2f,
wo: Vector3f,
dpdu: Vector3f,
dpdv: Vector3f,
dndu: Normal3f,
dndv: Normal3f,
time: Float,
shape: &'prim Shape,
face_index: Option<usize>,
) -> Self {
Self {
point,
point_error,
uv,
wo,
dpdu,
dpdv,
dndu,
dndv,
time,
shape: Some(shape),
face_index,
.. Self::default()
}
}
pub fn set_shading_geometry(
&mut self,
dpdu: Vector3f,
dpdv: Vector3f,
dndu: Normal3f,
dndv: Normal3f,
orientation_is_authoritative: bool,
) {
self.shading.normal = dpdu.cross(&dpdv).normalized();
if let Some(shape) = self.shape {
if shape.reverse_orientation() ^ shape.transform_swaps_handedness() {
self.shading.normal = -self.shading.normal;
}
}
if orientation_is_authoritative {
self.normal = face_forward(self.normal, self.shading.normal);
} else {
self.shading.normal = face_forward(self.shading.normal, self.normal)
}
self.shading.dpdu = dpdu;
self.shading.dpdv = dpdv;
self.shading.dndu = dndu;
self.shading.dndv = dndv;
}
}
impl<'prim> Default for SurfaceInteraction<'prim> {
fn default() -> Self {
Self {
..Default::default()
}
// Self {
// point: Point3f::default(),
// point_error: Vector3f::zero(),
// time: 0.0,
// wo: Vector3f::zero(),
// normal: Normal3f::zero(),
// medium_interface: None,
//
// bsdf: None,
// bssrdf: None,
// dndu: Vector3f::zero(),
// dndv: Vector3f::zero(),
// dpdu: Vector3f::zero(),
// dpdv: Vector3f::zero(),
// dpdx: Vector3f::zero(),
// dpdy: Vector3f::zero(),
// dudx: 0.0,
// dudy: 0.0,
// dvdx: 0.0,
// dvdy: 0.0,
// primitive: None,
// shading: Shading {
// dpdu: Vector3f::zero(),
// dpdv: Vector3f::zero(),
// dndu: Normal3f::zero(),
// dndv: Normal3f::zero(),
// normal: Normal3f::zero(),
// },
// shape: None,
// uv: Point2f::zero(),
// face_index: None,
// }
}
}
impl<'prim> Interaction<'prim> for SurfaceInteraction<'prim> {
fn get_point(&self) -> Point3f {
self.point
}
fn get_point_error(&self) -> Vector3f {
self.point_error
}
fn get_time(&self) -> Float {
self.time
}
fn get_normal(&self) -> Normal3f {
self.normal
}
fn get_medium_interface(&self) -> Option<&'prim MediumInterface> {
self.medium_interface
}
fn set_medium_interface(&mut self, interface: Option<&'prim MediumInterface>) {
self.medium_interface = interface;
}
}
pub struct MediumInteraction<'prim> {
pub point: Point3f,
pub point_error: Vector3f,
pub time: Float,
pub wo: Vector3f,
pub normal: Normal3f,
pub medium_interface: Option<&'prim MediumInterface>,
}
impl<'prim> Interaction<'prim> for MediumInteraction<'prim> {
fn get_point(&self) -> Point3f {
self.point
}
fn get_point_error(&self) -> Vector3f {
self.point_error
}
fn get_time(&self) -> Float {
self.time
}
fn get_normal(&self) -> Normal3f {
self.normal
}
fn get_medium_interface(&self) -> Option<&'prim MediumInterface> {
self.medium_interface
}
fn set_medium_interface(&mut self, interface: Option<&'prim MediumInterface>) {
self.medium_interface = interface;
}
}
//pub enum Interaction<'prim: 'ray> {
// Surface(SurfaceInteraction<'prim>),
// Medium(MediumInteraction<'prim>),
//}
fn accept_medium(mi: MediumInteraction) -> bool {
true
}
|
use std::prelude::v1::*;
use std::fmt;
use std::path::{Path, PathBuf};
use {trace, resolve, SymbolName};
use types::c_void;
/// Representation of an owned and self-contained backtrace.
///
/// This structure can be used to capture a backtrace at various points in a
/// program and later used to inspect what the backtrace was at that time.
///
/// `Backtrace` supports pretty-printing of backtraces through its `Debug`
/// implementation.
#[derive(Clone)]
#[cfg_attr(feature = "serialize-rustc", derive(RustcDecodable, RustcEncodable))]
#[cfg_attr(feature = "serialize-serde", derive(Deserialize, Serialize))]
pub struct Backtrace {
// Frames here are listed from top-to-bottom of the stack
frames: Vec<BacktraceFrame>,
// The index we believe is the actual start of the backtrace, omitting
// frames like `Backtrace::new` and `backtrace::trace`.
actual_start_index: usize,
}
/// Captured version of a frame in a backtrace.
///
/// This type is returned as a list from `Backtrace::frames` and represents one
/// stack frame in a captured backtrace.
#[derive(Clone)]
#[cfg_attr(feature = "serialize-rustc", derive(RustcDecodable, RustcEncodable))]
#[cfg_attr(feature = "serialize-serde", derive(Deserialize, Serialize))]
pub struct BacktraceFrame {
ip: usize,
symbol_address: usize,
symbols: Option<Vec<BacktraceSymbol>>,
}
/// Captured version of a symbol in a backtrace.
///
/// This type is returned as a list from `BacktraceFrame::symbols` and
/// represents the metadata for a symbol in a backtrace.
#[derive(Clone)]
#[cfg_attr(feature = "serialize-rustc", derive(RustcDecodable, RustcEncodable))]
#[cfg_attr(feature = "serialize-serde", derive(Deserialize, Serialize))]
pub struct BacktraceSymbol {
name: Option<Vec<u8>>,
addr: Option<usize>,
filename: Option<PathBuf>,
lineno: Option<u32>,
}
impl Backtrace {
/// Captures a backtrace at the callsite of this function, returning an
/// owned representation.
///
/// This function is useful for representing a backtrace as an object in
/// Rust. This returned value can be sent across threads and printed
/// elsewhere, and the purpose of this value is to be entirely self
/// contained.
///
/// # Examples
///
/// ```
/// use backtrace::Backtrace;
///
/// let current_backtrace = Backtrace::new();
/// ```
#[inline(never)] // want to make sure there's a frame here to remove
pub fn new() -> Backtrace {
let mut bt = Self::create(Self::new as usize);
bt.resolve();
bt
}
/// Similar to `new` except that this does not resolve any symbols, this
/// simply captures the backtrace as a list of addresses.
///
/// At a later time the `resolve` function can be called to resolve this
/// backtrace's symbols into readable names. This function exists because
/// the resolution process can sometimes take a significant amount of time
/// whereas any one backtrace may only be rarely printed.
///
/// # Examples
///
/// ```
/// use backtrace::Backtrace;
///
/// let mut current_backtrace = Backtrace::new_unresolved();
/// println!("{:?}", current_backtrace); // no symbol names
/// current_backtrace.resolve();
/// println!("{:?}", current_backtrace); // symbol names now present
/// ```
#[inline(never)] // want to make sure there's a frame here to remove
pub fn new_unresolved() -> Backtrace {
Self::create(Self::new_unresolved as usize)
}
fn create(ip: usize) -> Backtrace {
let ip_lo = ip;
let ip_hi = ip + 128;
let mut frames = Vec::new();
let mut actual_start_index = None;
trace(|frame| {
let ip = frame.ip() as usize;
frames.push(BacktraceFrame {
ip,
symbol_address: frame.symbol_address() as usize,
symbols: None,
});
if cfg!(not(all(target_os = "windows", target_arch = "x86"))) &&
ip >= ip_lo &&
ip <= ip_hi &&
actual_start_index.is_none()
{
actual_start_index = Some(frames.len());
}
true
});
Backtrace {
frames,
actual_start_index: actual_start_index.unwrap_or(0),
}
}
/// Returns the frames from when this backtrace was captured.
///
/// The first entry of this slice is likely the function `Backtrace::new`,
/// and the last frame is likely something about how this thread or the main
/// function started.
pub fn frames(&self) -> &[BacktraceFrame] {
&self.frames[self.actual_start_index..]
}
/// If this backtrace was created from `new_unresolved` then this function
/// will resolve all addresses in the backtrace to their symbolic names.
///
/// If this backtrace has been previously resolved or was created through
/// `new`, this function does nothing.
pub fn resolve(&mut self) {
for frame in self.frames.iter_mut().filter(|f| f.symbols.is_none()) {
let mut symbols = Vec::new();
resolve(frame.ip as *mut _, |symbol| {
symbols.push(BacktraceSymbol {
name: symbol.name().map(|m| m.as_bytes().to_vec()),
addr: symbol.addr().map(|a| a as usize),
filename: symbol.filename().map(|m| m.to_owned()),
lineno: symbol.lineno(),
});
});
frame.symbols = Some(symbols);
}
}
}
impl From<Vec<BacktraceFrame>> for Backtrace {
fn from(frames: Vec<BacktraceFrame>) -> Self {
Backtrace {
frames,
actual_start_index: 0,
}
}
}
impl Into<Vec<BacktraceFrame>> for Backtrace {
fn into(self) -> Vec<BacktraceFrame> {
self.frames
}
}
impl BacktraceFrame {
/// Same as `Frame::ip`
pub fn ip(&self) -> *mut c_void {
self.ip as *mut c_void
}
/// Same as `Frame::symbol_address`
pub fn symbol_address(&self) -> *mut c_void {
self.symbol_address as *mut c_void
}
/// Returns the list of symbols that this frame corresponds to.
///
/// Normally there is only one symbol per frame, but sometimes if a number
/// of functions are inlined into one frame then multiple symbols will be
/// returned. The first symbol listed is the "innermost function", whereas
/// the last symbol is the outermost (last caller).
///
/// Note that if this frame came from an unresolved backtrace then this will
/// return an empty list.
pub fn symbols(&self) -> &[BacktraceSymbol] {
self.symbols.as_ref().map(|s| &s[..]).unwrap_or(&[])
}
}
impl BacktraceSymbol {
/// Same as `Symbol::name`
pub fn name(&self) -> Option<SymbolName> {
self.name.as_ref().map(|s| SymbolName::new(s))
}
/// Same as `Symbol::addr`
pub fn addr(&self) -> Option<*mut c_void> {
self.addr.map(|s| s as *mut c_void)
}
/// Same as `Symbol::filename`
pub fn filename(&self) -> Option<&Path> {
self.filename.as_ref().map(|p| &**p)
}
/// Same as `Symbol::lineno`
pub fn lineno(&self) -> Option<u32> {
self.lineno
}
}
impl fmt::Debug for Backtrace {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "stack backtrace:")?;
let iter = if fmt.alternate() {
self.frames.iter()
} else {
self.frames[self.actual_start_index..].iter()
};
for (idx, frame) in iter.enumerate() {
let ip = frame.ip();
write!(fmt, "\n{:4}: ", idx)?;
let symbols = match frame.symbols {
Some(ref s) => s,
None => {
write!(fmt, "<unresolved> ({:?})", ip)?;
continue
}
};
if symbols.len() == 0 {
write!(fmt, "<no info> ({:?})", ip)?;
continue;
}
for (idx, symbol) in symbols.iter().enumerate() {
if idx != 0 {
write!(fmt, "\n ")?;
}
if let Some(name) = symbol.name() {
write!(fmt, "{}", name)?;
} else {
write!(fmt, "<unknown>")?;
}
if idx == 0 {
write!(fmt, " ({:?})", ip)?;
}
if let (Some(file), Some(line)) = (symbol.filename(), symbol.lineno()) {
write!(fmt, "\n at {}:{}", file.display(), line)?;
}
}
}
Ok(())
}
}
impl Default for Backtrace {
fn default() -> Backtrace {
Backtrace::new()
}
}
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fmt::Display;
use std::fmt::Write;
use common_exception::Result;
use super::FormatTreeNode;
static INDENT_SIZE: usize = 4;
impl<T> FormatTreeNode<T>
where T: Display + Clone
{
pub fn format_indent(&self) -> Result<String> {
let mut buf = String::new();
self.format_indent_impl(0, &mut buf)?;
Ok(buf)
}
fn format_indent_impl(&self, indent: usize, f: &mut String) -> Result<()> {
writeln!(f, "{}{}", " ".repeat(indent), &self.payload).unwrap();
for child in self.children.iter() {
child.format_indent_impl(indent + INDENT_SIZE, f)?;
}
Ok(())
}
}
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use common_exception::Result;
use crate::plans::ComparisonExpr;
use crate::plans::ComparisonOp;
use crate::plans::Join;
use crate::plans::ScalarExpr;
pub fn get_join_predicates(join: &Join) -> Result<Vec<ScalarExpr>> {
Ok(join
.left_conditions
.iter()
.zip(join.right_conditions.iter())
.map(|(left_cond, right_cond)| {
Ok(ScalarExpr::ComparisonExpr(ComparisonExpr {
left: Box::new(left_cond.clone()),
right: Box::new(right_cond.clone()),
op: ComparisonOp::Equal,
}))
})
.collect::<Result<Vec<_>>>()?
.into_iter()
.chain(join.non_equi_conditions.clone().into_iter())
.collect())
}
|
// Copyright 2017 Dasein Phaos aka. Luxko
//
// 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.
//! render target view description
use format::DxgiFormat;
/// describes a render target view
#[derive(Copy, Clone, Debug)]
pub struct RtvDesc {
pub format: DxgiFormat,
pub dimension: RtvDimension,
}
impl RtvDesc {
#[inline]
pub(crate) fn into_cstruct(self) -> RtvDescBindHelper {
self.into()
}
}
#[derive(Copy, Clone, Debug)]
pub enum RtvDimension {
Buffer(RtvBufferDesc),
Tex1D(RtvTex1DDesc),
Tex1DArray(RtvTex1DArrayDesc),
Tex2D(RtvTex2DDesc),
Tex2DArray(RtvTex2DArrayDesc),
Tex2DMs,
Tex2DMsArray(RtvTex2DMsArrayDesc),
Tex3D(RtvTex3DDesc),
}
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub struct RtvBufferDesc {
/// first element to be accessed by the view
pub offset: u64,
/// number of elements
pub num_elements: u32,
}
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub struct RtvTex1DDesc {
/// index of the mipmap slice to use
pub mip_slice: u32,
}
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub struct RtvTex1DArrayDesc{
/// index of the mipmap slice to use
pub mip_slice: u32,
/// first array slice to use
pub first_slice: u32,
/// number of slices in the array
pub array_size: u32,
}
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub struct RtvTex2DDesc{
/// index of the mipmap slice to use
pub mip_slice: u32,
/// index of the plane slice to use
pub plane_slice: u32,
}
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub struct RtvTex2DArrayDesc{
/// index of the mipmap slice to use
pub mip_slice: u32,
/// first array slice to use
pub first_slice: u32,
/// number of slices in the array
pub array_size: u32,
/// index of the plane slice to use
pub plane_slice: u32,
}
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub struct RtvTex2DMsArrayDesc{
/// first array slice to use
pub first_slice: u32,
/// number of slices in the array
pub array_size: u32,
}
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub struct RtvTex3DDesc{
/// index of the mipmap slice to use
pub mip_slice: u32,
/// first depth level to use
pub first_slice: u32,
/// number of depth levels in the array
pub num_slices: u32,
}
/// helper struct for ffi, not intended for application user
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub(crate) struct RtvDescBindHelper {
format: DxgiFormat,
view_dimension: ::winapi::D3D12_RTV_DIMENSION,
a: [u32; 4],
}
impl From<RtvDesc> for RtvDescBindHelper{
#[inline]
fn from(desc: RtvDesc) -> RtvDescBindHelper {
unsafe {
let mut ret: RtvDescBindHelper = ::std::mem::zeroed();
ret.format = desc.format;
match desc.dimension {
RtvDimension::Buffer(content) => {
ret.view_dimension = ::winapi::D3D12_RTV_DIMENSION_BUFFER;
ret.a = ::std::mem::transmute_copy(&content);
},
RtvDimension::Tex1D(content) => {
ret.view_dimension = ::winapi::D3D12_RTV_DIMENSION_TEXTURE1D;
ret.a = ::std::mem::transmute_copy(&content);
},
RtvDimension::Tex1DArray(content) => {
ret.view_dimension = ::winapi::D3D12_RTV_DIMENSION_TEXTURE1DARRAY;
ret.a = ::std::mem::transmute_copy(&content);
},
RtvDimension::Tex2D(content) => {
ret.view_dimension = ::winapi::D3D12_RTV_DIMENSION_TEXTURE2D;
ret.a = ::std::mem::transmute_copy(&content);
},
RtvDimension::Tex2DArray(content) => {
ret.view_dimension = ::winapi::D3D12_RTV_DIMENSION_TEXTURE2DARRAY;
ret.a = ::std::mem::transmute_copy(&content);
},
RtvDimension::Tex2DMs =>
ret.view_dimension = ::winapi::D3D12_RTV_DIMENSION_TEXTURE2DMS,
RtvDimension::Tex2DMsArray(content) => {
ret.view_dimension = ::winapi::D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY;
ret.a = ::std::mem::transmute_copy(&content);
},
RtvDimension::Tex3D(content) => {
ret.view_dimension = ::winapi::D3D12_RTV_DIMENSION_TEXTURE3D;
ret.a = ::std::mem::transmute_copy(&content);
},
}
ret
}
}
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - EXTI rising trigger selection register"]
pub rtsr1: RTSR1,
#[doc = "0x04 - EXTI falling trigger selection register"]
pub ftsr1: FTSR1,
#[doc = "0x08 - EXTI software interrupt event register"]
pub swier1: SWIER1,
#[doc = "0x0c - EXTI D3 pending mask register"]
pub d3pmr1: D3PMR1,
#[doc = "0x10 - EXTI D3 pending clear selection register low"]
pub d3pcr1l: D3PCR1L,
#[doc = "0x14 - EXTI D3 pending clear selection register high"]
pub d3pcr1h: D3PCR1H,
_reserved6: [u8; 8usize],
#[doc = "0x20 - EXTI rising trigger selection register"]
pub rtsr2: RTSR2,
#[doc = "0x24 - EXTI falling trigger selection register"]
pub ftsr2: FTSR2,
#[doc = "0x28 - EXTI software interrupt event register"]
pub swier2: SWIER2,
#[doc = "0x2c - EXTI D3 pending mask register"]
pub d3pmr2: D3PMR2,
#[doc = "0x30 - EXTI D3 pending clear selection register low"]
pub d3pcr2l: D3PCR2L,
#[doc = "0x34 - EXTI D3 pending clear selection register high"]
pub d3pcr2h: D3PCR2H,
_reserved12: [u8; 8usize],
#[doc = "0x40 - EXTI rising trigger selection register"]
pub rtsr3: RTSR3,
#[doc = "0x44 - EXTI falling trigger selection register"]
pub ftsr3: FTSR3,
#[doc = "0x48 - EXTI software interrupt event register"]
pub swier3: SWIER3,
#[doc = "0x4c - EXTI D3 pending mask register"]
pub d3pmr3: D3PMR3,
_reserved16: [u8; 4usize],
#[doc = "0x54 - EXTI D3 pending clear selection register high"]
pub d3pcr3h: D3PCR3H,
_reserved17: [u8; 40usize],
#[doc = "0x80 - EXTI interrupt mask register"]
pub c1imr1: C1IMR1,
#[doc = "0x84 - EXTI event mask register"]
pub c1emr1: C1EMR1,
#[doc = "0x88 - EXTI pending register"]
pub c1pr1: C1PR1,
_reserved20: [u8; 4usize],
#[doc = "0x90 - EXTI interrupt mask register"]
pub c1imr2: C1IMR2,
#[doc = "0x94 - EXTI event mask register"]
pub c1emr2: C1EMR2,
#[doc = "0x98 - EXTI pending register"]
pub c1pr2: C1PR2,
_reserved23: [u8; 4usize],
#[doc = "0xa0 - EXTI interrupt mask register"]
pub c1imr3: C1IMR3,
#[doc = "0xa4 - EXTI event mask register"]
pub c1emr3: C1EMR3,
#[doc = "0xa8 - EXTI pending register"]
pub c1pr3: C1PR3,
_reserved26: [u8; 20usize],
#[doc = "0xc0 - CPU2 EXTI interrupt mask register"]
pub c2imr1: C2IMR1,
#[doc = "0xc4 - CPU2 EXTI event mask register"]
pub c2emr1: C2EMR1,
#[doc = "0xc8 - CPU2 EXTI pending register"]
pub c2pr1: C2PR1,
_reserved29: [u8; 4usize],
#[doc = "0xd0 - CPU2 EXTI interrupt mask register"]
pub c2imr2: C2IMR2,
#[doc = "0xd4 - CPU2 EXTI event mask register"]
pub c2emr2: C2EMR2,
#[doc = "0xd8 - CPU2 EXTI pending register"]
pub c2pr2: C2PR2,
_reserved32: [u8; 4usize],
#[doc = "0xe0 - CPU2 EXTI interrupt mask register"]
pub c2imr3: C2IMR3,
#[doc = "0xe4 - CPU2 EXTI event mask register"]
pub c2emr3: C2EMR3,
#[doc = "0xe8 - CPU2 EXTI pending register"]
pub c2pr3: C2PR3,
}
#[doc = "EXTI rising trigger selection register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rtsr1](rtsr1) module"]
pub type RTSR1 = crate::Reg<u32, _RTSR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _RTSR1;
#[doc = "`read()` method returns [rtsr1::R](rtsr1::R) reader structure"]
impl crate::Readable for RTSR1 {}
#[doc = "`write(|w| ..)` method takes [rtsr1::W](rtsr1::W) writer structure"]
impl crate::Writable for RTSR1 {}
#[doc = "EXTI rising trigger selection register"]
pub mod rtsr1;
#[doc = "EXTI falling trigger selection register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ftsr1](ftsr1) module"]
pub type FTSR1 = crate::Reg<u32, _FTSR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FTSR1;
#[doc = "`read()` method returns [ftsr1::R](ftsr1::R) reader structure"]
impl crate::Readable for FTSR1 {}
#[doc = "`write(|w| ..)` method takes [ftsr1::W](ftsr1::W) writer structure"]
impl crate::Writable for FTSR1 {}
#[doc = "EXTI falling trigger selection register"]
pub mod ftsr1;
#[doc = "EXTI software interrupt event register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [swier1](swier1) module"]
pub type SWIER1 = crate::Reg<u32, _SWIER1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SWIER1;
#[doc = "`read()` method returns [swier1::R](swier1::R) reader structure"]
impl crate::Readable for SWIER1 {}
#[doc = "`write(|w| ..)` method takes [swier1::W](swier1::W) writer structure"]
impl crate::Writable for SWIER1 {}
#[doc = "EXTI software interrupt event register"]
pub mod swier1;
#[doc = "EXTI D3 pending mask register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [d3pmr1](d3pmr1) module"]
pub type D3PMR1 = crate::Reg<u32, _D3PMR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _D3PMR1;
#[doc = "`read()` method returns [d3pmr1::R](d3pmr1::R) reader structure"]
impl crate::Readable for D3PMR1 {}
#[doc = "`write(|w| ..)` method takes [d3pmr1::W](d3pmr1::W) writer structure"]
impl crate::Writable for D3PMR1 {}
#[doc = "EXTI D3 pending mask register"]
pub mod d3pmr1;
#[doc = "EXTI D3 pending clear selection register low\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [d3pcr1l](d3pcr1l) module"]
pub type D3PCR1L = crate::Reg<u32, _D3PCR1L>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _D3PCR1L;
#[doc = "`read()` method returns [d3pcr1l::R](d3pcr1l::R) reader structure"]
impl crate::Readable for D3PCR1L {}
#[doc = "`write(|w| ..)` method takes [d3pcr1l::W](d3pcr1l::W) writer structure"]
impl crate::Writable for D3PCR1L {}
#[doc = "EXTI D3 pending clear selection register low"]
pub mod d3pcr1l;
#[doc = "EXTI D3 pending clear selection register high\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [d3pcr1h](d3pcr1h) module"]
pub type D3PCR1H = crate::Reg<u32, _D3PCR1H>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _D3PCR1H;
#[doc = "`read()` method returns [d3pcr1h::R](d3pcr1h::R) reader structure"]
impl crate::Readable for D3PCR1H {}
#[doc = "`write(|w| ..)` method takes [d3pcr1h::W](d3pcr1h::W) writer structure"]
impl crate::Writable for D3PCR1H {}
#[doc = "EXTI D3 pending clear selection register high"]
pub mod d3pcr1h;
#[doc = "EXTI rising trigger selection register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rtsr2](rtsr2) module"]
pub type RTSR2 = crate::Reg<u32, _RTSR2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _RTSR2;
#[doc = "`read()` method returns [rtsr2::R](rtsr2::R) reader structure"]
impl crate::Readable for RTSR2 {}
#[doc = "`write(|w| ..)` method takes [rtsr2::W](rtsr2::W) writer structure"]
impl crate::Writable for RTSR2 {}
#[doc = "EXTI rising trigger selection register"]
pub mod rtsr2;
#[doc = "EXTI falling trigger selection register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ftsr2](ftsr2) module"]
pub type FTSR2 = crate::Reg<u32, _FTSR2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FTSR2;
#[doc = "`read()` method returns [ftsr2::R](ftsr2::R) reader structure"]
impl crate::Readable for FTSR2 {}
#[doc = "`write(|w| ..)` method takes [ftsr2::W](ftsr2::W) writer structure"]
impl crate::Writable for FTSR2 {}
#[doc = "EXTI falling trigger selection register"]
pub mod ftsr2;
#[doc = "EXTI software interrupt event register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [swier2](swier2) module"]
pub type SWIER2 = crate::Reg<u32, _SWIER2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SWIER2;
#[doc = "`read()` method returns [swier2::R](swier2::R) reader structure"]
impl crate::Readable for SWIER2 {}
#[doc = "`write(|w| ..)` method takes [swier2::W](swier2::W) writer structure"]
impl crate::Writable for SWIER2 {}
#[doc = "EXTI software interrupt event register"]
pub mod swier2;
#[doc = "EXTI D3 pending mask register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [d3pmr2](d3pmr2) module"]
pub type D3PMR2 = crate::Reg<u32, _D3PMR2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _D3PMR2;
#[doc = "`read()` method returns [d3pmr2::R](d3pmr2::R) reader structure"]
impl crate::Readable for D3PMR2 {}
#[doc = "`write(|w| ..)` method takes [d3pmr2::W](d3pmr2::W) writer structure"]
impl crate::Writable for D3PMR2 {}
#[doc = "EXTI D3 pending mask register"]
pub mod d3pmr2;
#[doc = "EXTI D3 pending clear selection register low\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [d3pcr2l](d3pcr2l) module"]
pub type D3PCR2L = crate::Reg<u32, _D3PCR2L>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _D3PCR2L;
#[doc = "`read()` method returns [d3pcr2l::R](d3pcr2l::R) reader structure"]
impl crate::Readable for D3PCR2L {}
#[doc = "`write(|w| ..)` method takes [d3pcr2l::W](d3pcr2l::W) writer structure"]
impl crate::Writable for D3PCR2L {}
#[doc = "EXTI D3 pending clear selection register low"]
pub mod d3pcr2l;
#[doc = "EXTI D3 pending clear selection register high\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [d3pcr2h](d3pcr2h) module"]
pub type D3PCR2H = crate::Reg<u32, _D3PCR2H>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _D3PCR2H;
#[doc = "`read()` method returns [d3pcr2h::R](d3pcr2h::R) reader structure"]
impl crate::Readable for D3PCR2H {}
#[doc = "`write(|w| ..)` method takes [d3pcr2h::W](d3pcr2h::W) writer structure"]
impl crate::Writable for D3PCR2H {}
#[doc = "EXTI D3 pending clear selection register high"]
pub mod d3pcr2h;
#[doc = "EXTI rising trigger selection register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rtsr3](rtsr3) module"]
pub type RTSR3 = crate::Reg<u32, _RTSR3>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _RTSR3;
#[doc = "`read()` method returns [rtsr3::R](rtsr3::R) reader structure"]
impl crate::Readable for RTSR3 {}
#[doc = "`write(|w| ..)` method takes [rtsr3::W](rtsr3::W) writer structure"]
impl crate::Writable for RTSR3 {}
#[doc = "EXTI rising trigger selection register"]
pub mod rtsr3;
#[doc = "EXTI falling trigger selection register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ftsr3](ftsr3) module"]
pub type FTSR3 = crate::Reg<u32, _FTSR3>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FTSR3;
#[doc = "`read()` method returns [ftsr3::R](ftsr3::R) reader structure"]
impl crate::Readable for FTSR3 {}
#[doc = "`write(|w| ..)` method takes [ftsr3::W](ftsr3::W) writer structure"]
impl crate::Writable for FTSR3 {}
#[doc = "EXTI falling trigger selection register"]
pub mod ftsr3;
#[doc = "EXTI software interrupt event register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [swier3](swier3) module"]
pub type SWIER3 = crate::Reg<u32, _SWIER3>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SWIER3;
#[doc = "`read()` method returns [swier3::R](swier3::R) reader structure"]
impl crate::Readable for SWIER3 {}
#[doc = "`write(|w| ..)` method takes [swier3::W](swier3::W) writer structure"]
impl crate::Writable for SWIER3 {}
#[doc = "EXTI software interrupt event register"]
pub mod swier3;
#[doc = "EXTI D3 pending mask register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [d3pmr3](d3pmr3) module"]
pub type D3PMR3 = crate::Reg<u32, _D3PMR3>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _D3PMR3;
#[doc = "`read()` method returns [d3pmr3::R](d3pmr3::R) reader structure"]
impl crate::Readable for D3PMR3 {}
#[doc = "`write(|w| ..)` method takes [d3pmr3::W](d3pmr3::W) writer structure"]
impl crate::Writable for D3PMR3 {}
#[doc = "EXTI D3 pending mask register"]
pub mod d3pmr3;
#[doc = "EXTI D3 pending clear selection register high\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [d3pcr3h](d3pcr3h) module"]
pub type D3PCR3H = crate::Reg<u32, _D3PCR3H>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _D3PCR3H;
#[doc = "`read()` method returns [d3pcr3h::R](d3pcr3h::R) reader structure"]
impl crate::Readable for D3PCR3H {}
#[doc = "`write(|w| ..)` method takes [d3pcr3h::W](d3pcr3h::W) writer structure"]
impl crate::Writable for D3PCR3H {}
#[doc = "EXTI D3 pending clear selection register high"]
pub mod d3pcr3h;
#[doc = "EXTI interrupt mask register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [c1imr1](c1imr1) module"]
pub type C1IMR1 = crate::Reg<u32, _C1IMR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _C1IMR1;
#[doc = "`read()` method returns [c1imr1::R](c1imr1::R) reader structure"]
impl crate::Readable for C1IMR1 {}
#[doc = "`write(|w| ..)` method takes [c1imr1::W](c1imr1::W) writer structure"]
impl crate::Writable for C1IMR1 {}
#[doc = "EXTI interrupt mask register"]
pub mod c1imr1;
#[doc = "EXTI event mask register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [c1emr1](c1emr1) module"]
pub type C1EMR1 = crate::Reg<u32, _C1EMR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _C1EMR1;
#[doc = "`read()` method returns [c1emr1::R](c1emr1::R) reader structure"]
impl crate::Readable for C1EMR1 {}
#[doc = "`write(|w| ..)` method takes [c1emr1::W](c1emr1::W) writer structure"]
impl crate::Writable for C1EMR1 {}
#[doc = "EXTI event mask register"]
pub mod c1emr1;
#[doc = "EXTI pending register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [c1pr1](c1pr1) module"]
pub type C1PR1 = crate::Reg<u32, _C1PR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _C1PR1;
#[doc = "`read()` method returns [c1pr1::R](c1pr1::R) reader structure"]
impl crate::Readable for C1PR1 {}
#[doc = "`write(|w| ..)` method takes [c1pr1::W](c1pr1::W) writer structure"]
impl crate::Writable for C1PR1 {}
#[doc = "EXTI pending register"]
pub mod c1pr1;
#[doc = "EXTI interrupt mask register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [c1imr2](c1imr2) module"]
pub type C1IMR2 = crate::Reg<u32, _C1IMR2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _C1IMR2;
#[doc = "`read()` method returns [c1imr2::R](c1imr2::R) reader structure"]
impl crate::Readable for C1IMR2 {}
#[doc = "`write(|w| ..)` method takes [c1imr2::W](c1imr2::W) writer structure"]
impl crate::Writable for C1IMR2 {}
#[doc = "EXTI interrupt mask register"]
pub mod c1imr2;
#[doc = "EXTI event mask register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [c1emr2](c1emr2) module"]
pub type C1EMR2 = crate::Reg<u32, _C1EMR2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _C1EMR2;
#[doc = "`read()` method returns [c1emr2::R](c1emr2::R) reader structure"]
impl crate::Readable for C1EMR2 {}
#[doc = "`write(|w| ..)` method takes [c1emr2::W](c1emr2::W) writer structure"]
impl crate::Writable for C1EMR2 {}
#[doc = "EXTI event mask register"]
pub mod c1emr2;
#[doc = "EXTI pending register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [c1pr2](c1pr2) module"]
pub type C1PR2 = crate::Reg<u32, _C1PR2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _C1PR2;
#[doc = "`read()` method returns [c1pr2::R](c1pr2::R) reader structure"]
impl crate::Readable for C1PR2 {}
#[doc = "`write(|w| ..)` method takes [c1pr2::W](c1pr2::W) writer structure"]
impl crate::Writable for C1PR2 {}
#[doc = "EXTI pending register"]
pub mod c1pr2;
#[doc = "EXTI interrupt mask register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [c1imr3](c1imr3) module"]
pub type C1IMR3 = crate::Reg<u32, _C1IMR3>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _C1IMR3;
#[doc = "`read()` method returns [c1imr3::R](c1imr3::R) reader structure"]
impl crate::Readable for C1IMR3 {}
#[doc = "`write(|w| ..)` method takes [c1imr3::W](c1imr3::W) writer structure"]
impl crate::Writable for C1IMR3 {}
#[doc = "EXTI interrupt mask register"]
pub mod c1imr3;
#[doc = "EXTI event mask register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [c1emr3](c1emr3) module"]
pub type C1EMR3 = crate::Reg<u32, _C1EMR3>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _C1EMR3;
#[doc = "`read()` method returns [c1emr3::R](c1emr3::R) reader structure"]
impl crate::Readable for C1EMR3 {}
#[doc = "`write(|w| ..)` method takes [c1emr3::W](c1emr3::W) writer structure"]
impl crate::Writable for C1EMR3 {}
#[doc = "EXTI event mask register"]
pub mod c1emr3;
#[doc = "EXTI pending register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [c1pr3](c1pr3) module"]
pub type C1PR3 = crate::Reg<u32, _C1PR3>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _C1PR3;
#[doc = "`read()` method returns [c1pr3::R](c1pr3::R) reader structure"]
impl crate::Readable for C1PR3 {}
#[doc = "`write(|w| ..)` method takes [c1pr3::W](c1pr3::W) writer structure"]
impl crate::Writable for C1PR3 {}
#[doc = "EXTI pending register"]
pub mod c1pr3;
#[doc = "CPU2 EXTI interrupt mask register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [c2imr1](c2imr1) module"]
pub type C2IMR1 = crate::Reg<u32, _C2IMR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _C2IMR1;
#[doc = "`read()` method returns [c2imr1::R](c2imr1::R) reader structure"]
impl crate::Readable for C2IMR1 {}
#[doc = "`write(|w| ..)` method takes [c2imr1::W](c2imr1::W) writer structure"]
impl crate::Writable for C2IMR1 {}
#[doc = "CPU2 EXTI interrupt mask register"]
pub mod c2imr1;
#[doc = "CPU2 EXTI event mask register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [c2emr1](c2emr1) module"]
pub type C2EMR1 = crate::Reg<u32, _C2EMR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _C2EMR1;
#[doc = "`read()` method returns [c2emr1::R](c2emr1::R) reader structure"]
impl crate::Readable for C2EMR1 {}
#[doc = "`write(|w| ..)` method takes [c2emr1::W](c2emr1::W) writer structure"]
impl crate::Writable for C2EMR1 {}
#[doc = "CPU2 EXTI event mask register"]
pub mod c2emr1;
#[doc = "CPU2 EXTI pending register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [c2pr1](c2pr1) module"]
pub type C2PR1 = crate::Reg<u32, _C2PR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _C2PR1;
#[doc = "`read()` method returns [c2pr1::R](c2pr1::R) reader structure"]
impl crate::Readable for C2PR1 {}
#[doc = "`write(|w| ..)` method takes [c2pr1::W](c2pr1::W) writer structure"]
impl crate::Writable for C2PR1 {}
#[doc = "CPU2 EXTI pending register"]
pub mod c2pr1;
#[doc = "CPU2 EXTI interrupt mask register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [c2imr2](c2imr2) module"]
pub type C2IMR2 = crate::Reg<u32, _C2IMR2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _C2IMR2;
#[doc = "`read()` method returns [c2imr2::R](c2imr2::R) reader structure"]
impl crate::Readable for C2IMR2 {}
#[doc = "`write(|w| ..)` method takes [c2imr2::W](c2imr2::W) writer structure"]
impl crate::Writable for C2IMR2 {}
#[doc = "CPU2 EXTI interrupt mask register"]
pub mod c2imr2;
#[doc = "CPU2 EXTI event mask register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [c2emr2](c2emr2) module"]
pub type C2EMR2 = crate::Reg<u32, _C2EMR2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _C2EMR2;
#[doc = "`read()` method returns [c2emr2::R](c2emr2::R) reader structure"]
impl crate::Readable for C2EMR2 {}
#[doc = "`write(|w| ..)` method takes [c2emr2::W](c2emr2::W) writer structure"]
impl crate::Writable for C2EMR2 {}
#[doc = "CPU2 EXTI event mask register"]
pub mod c2emr2;
#[doc = "CPU2 EXTI pending register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [c2pr2](c2pr2) module"]
pub type C2PR2 = crate::Reg<u32, _C2PR2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _C2PR2;
#[doc = "`read()` method returns [c2pr2::R](c2pr2::R) reader structure"]
impl crate::Readable for C2PR2 {}
#[doc = "`write(|w| ..)` method takes [c2pr2::W](c2pr2::W) writer structure"]
impl crate::Writable for C2PR2 {}
#[doc = "CPU2 EXTI pending register"]
pub mod c2pr2;
#[doc = "CPU2 EXTI interrupt mask register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [c2imr3](c2imr3) module"]
pub type C2IMR3 = crate::Reg<u32, _C2IMR3>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _C2IMR3;
#[doc = "`read()` method returns [c2imr3::R](c2imr3::R) reader structure"]
impl crate::Readable for C2IMR3 {}
#[doc = "`write(|w| ..)` method takes [c2imr3::W](c2imr3::W) writer structure"]
impl crate::Writable for C2IMR3 {}
#[doc = "CPU2 EXTI interrupt mask register"]
pub mod c2imr3;
#[doc = "CPU2 EXTI event mask register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [c2emr3](c2emr3) module"]
pub type C2EMR3 = crate::Reg<u32, _C2EMR3>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _C2EMR3;
#[doc = "`read()` method returns [c2emr3::R](c2emr3::R) reader structure"]
impl crate::Readable for C2EMR3 {}
#[doc = "`write(|w| ..)` method takes [c2emr3::W](c2emr3::W) writer structure"]
impl crate::Writable for C2EMR3 {}
#[doc = "CPU2 EXTI event mask register"]
pub mod c2emr3;
#[doc = "CPU2 EXTI pending register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [c2pr3](c2pr3) module"]
pub type C2PR3 = crate::Reg<u32, _C2PR3>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _C2PR3;
#[doc = "`read()` method returns [c2pr3::R](c2pr3::R) reader structure"]
impl crate::Readable for C2PR3 {}
#[doc = "`write(|w| ..)` method takes [c2pr3::W](c2pr3::W) writer structure"]
impl crate::Writable for C2PR3 {}
#[doc = "CPU2 EXTI pending register"]
pub mod c2pr3;
|
use std::env;
use std::error::Error;
use std::fs;
use std::str;
pub fn pattern_matches(text: &[u8], pattern: &str) -> Vec<usize> {
text.windows(pattern.len())
.enumerate()
.filter_map(|(i, x)| {
if str::from_utf8(x).unwrap() == pattern {
Some(i)
} else {
None
}
})
.collect()
}
fn main() -> Result<(), Box<dyn Error>> {
let input: String = env::args()
.nth(1)
.unwrap_or("data/rosalind_ba1d.txt".into());
let data = fs::read_to_string(input)?;
let mut lines = data.lines();
let pattern = lines.next().unwrap();
let text = lines.next().unwrap();
for word in pattern_matches(text.as_bytes(), pattern) {
print!("{} ", word);
}
println!();
Ok(())
}
|
use crate::utils;
use std::io::{Read, Result, Write};
pub trait Stream: Read + Write {}
impl<T> Stream for T where T: Read + Write {}
struct StreamParser<'a, T: Read> {
stream: &'a mut T,
buffer: Vec<u8>,
}
struct StreamWriter<'a, T: Write> {
stream: &'a mut T,
}
const CRLF: &[u8] = b"\r\n";
impl<'a, T: Read> StreamParser<'a, T> {
fn new(stream: &'a mut T) -> Self {
StreamParser {
stream,
buffer: Vec::with_capacity(512),
}
}
fn read_line(&mut self) -> Option<Vec<u8>> {
let mut line_end = utils::find_subsequence(&self.buffer[..], CRLF);
let mut read_count = 0;
let mut buf_end = self.buffer.len();
self.buffer.resize(512, 0);
while let None = line_end {
read_count = buf_end;
match self.stream.read(&mut self.buffer[read_count..]) {
Ok(0) if self.buffer.len() == 0 => return Some(Vec::new()),
Ok(size) => {
buf_end += size;
line_end = utils::find_subsequence(&self.buffer[read_count..buf_end], CRLF);
}
_ => return None,
}
}
let line_end = line_end.unwrap();
self.buffer.truncate(buf_end); // buffer was resized to 512, truncate it till data
let mut split = self.buffer.split_off(read_count + line_end + CRLF.len()); // split after the CRLF
std::mem::swap(&mut split, &mut self.buffer); // swap to get the leftover on buffer
Some(split)
}
}
impl<'a, T: Write> StreamWriter<'a, T> {
fn new(stream: &'a mut T) -> Self {
StreamWriter { stream }
}
fn write_line(&mut self, data: &Vec<u8>) -> bool {
self.stream.write_all(&data[..]).is_ok() && self.stream.write_all(CRLF).is_ok()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::default::Default;
#[derive(Default)]
struct ChunkedTestStream {
read_buf: Vec<u8>,
bytes_read: usize,
chunk_size: usize,
write_buf: Vec<u8>,
}
impl Read for ChunkedTestStream {
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
let size = self
.read_buf
.len()
.checked_sub(self.bytes_read)
.unwrap_or(std::cmp::min(buf.len(), self.chunk_size));
buf[..size].clone_from_slice(&self.read_buf[self.bytes_read..self.bytes_read + size]);
self.bytes_read += size;
Ok(size)
}
}
impl Write for ChunkedTestStream {
fn write(&mut self, buf: &[u8]) -> Result<usize> {
let size = std::cmp::min(buf.len(), self.chunk_size);
self.write_buf.extend(&buf[..size]);
Ok(size)
}
fn flush(&mut self) -> std::result::Result<(), std::io::Error> {
Ok(())
}
}
#[test]
fn read_line_test() {
let mut stream = ChunkedTestStream {
read_buf: b"line-one\r\nline-two\r\nline-three\r\n".to_vec(),
chunk_size: 5,
..Default::default()
};
let mut parser = StreamParser::new(&mut stream);
assert_eq!(parser.read_line().unwrap(), b"line-one\r\n".to_vec());
assert_eq!(parser.read_line().unwrap(), b"line-two\r\n".to_vec());
assert_eq!(parser.read_line().unwrap(), b"line-three\r\n".to_vec());
}
#[test]
fn write_line_test() {
let mut stream = ChunkedTestStream {
chunk_size: 5,
..Default::default()
};
let mut writer = StreamWriter::new(&mut stream);
assert!(writer.write_line(&b"line-one".to_vec()));
assert!(writer.write_line(&b"line-two".to_vec()));
assert!(writer.write_line(&b"line-three".to_vec()));
assert_eq!(&stream.write_buf, b"line-one\r\nline-two\r\nline-three\r\n");
}
}
|
use std::{sync::RwLock, collections::HashMap};
use crossbeam_channel::Sender;
use smallvec::SmallVec;
pub struct Command {
cmd: String,
args: SmallVec::<[String; 4]>
}
pub struct Console {
msgs: RwLock<HashMap<String, Sender<Command>>>
}
impl Console {
pub fn new() -> Self {
Self { msgs: RwLock::new(HashMap::new()) }
}
pub fn install_listener(&self, prefix: &str, sender: Sender<Command>) {
let mut lock = self.msgs.write().unwrap();
lock.insert(prefix.to_string().to_lowercase(), sender);
}
pub fn write_cmd(&self, cmd: &str) {
let mut words = cmd.split(" ");
let base_cmd = words.next();
if base_cmd.is_none() {
return;
}
let base_cmd = base_cmd.unwrap();
let dot_index = base_cmd.find('.');
if dot_index.is_none() {
return;
}
let dot_index = dot_index.unwrap();
let prefix = &base_cmd[..dot_index].to_lowercase();
let mut args = SmallVec::<[String; 4]>::new();
for arg in words {
args.push(arg.to_string());
}
let command = Command {
cmd: (&base_cmd[(dot_index + 1)..]).to_string(),
args
};
let lock = self.msgs.read().unwrap();
let listener = lock.get(prefix);
if listener.is_none() {
return;
}
let listener = listener.unwrap();
listener.send(command).unwrap();
}
} |
use std::borrow::Cow;
use indexmap::IndexMap;
use serde::de::DeserializeOwned;
use crate::{Error, Name, Result, Value};
/// A value accessor
pub struct ValueAccessor<'a>(&'a Value);
impl<'a> ValueAccessor<'a> {
/// Returns `true` if the value is null, otherwise returns `false`
#[inline]
pub fn is_null(&self) -> bool {
matches!(self.0, Value::Null)
}
/// Returns the boolean
pub fn boolean(&self) -> Result<bool> {
match self.0 {
Value::Boolean(b) => Ok(*b),
_ => Err(Error::new("internal: not a boolean")),
}
}
/// Returns the enum name
pub fn enum_name(&self) -> Result<&str> {
match self.0 {
Value::Enum(s) => Ok(s),
Value::String(s) => Ok(s.as_str()),
_ => Err(Error::new("internal: not an enum name")),
}
}
/// Returns the number as `i64`
pub fn i64(&self) -> Result<i64> {
if let Value::Number(number) = self.0 {
if let Some(value) = number.as_i64() {
return Ok(value);
}
}
Err(Error::new("internal: not an signed integer"))
}
/// Returns the number as `u64`
pub fn u64(&self) -> Result<u64> {
if let Value::Number(number) = self.0 {
if let Some(value) = number.as_u64() {
return Ok(value);
}
}
Err(Error::new("internal: not an unsigned integer"))
}
/// Returns the number as `f32`
pub fn f32(&self) -> Result<f32> {
if let Value::Number(number) = self.0 {
if let Some(value) = number.as_f64() {
return Ok(value as f32);
}
}
Err(Error::new("internal: not a float"))
}
/// Returns the number as `f64`
pub fn f64(&self) -> Result<f64> {
if let Value::Number(number) = self.0 {
if let Some(value) = number.as_f64() {
return Ok(value);
}
}
Err(Error::new("internal: not a float"))
}
/// Returns the string value
pub fn string(&self) -> Result<&str> {
if let Value::String(value) = self.0 {
Ok(value)
} else {
Err(Error::new("internal: not a string"))
}
}
/// Returns the object accessor
pub fn object(&self) -> Result<ObjectAccessor<'_>> {
if let Value::Object(obj) = self.0 {
Ok(ObjectAccessor(Cow::Borrowed(obj)))
} else {
Err(Error::new("internal: not a string"))
}
}
/// Returns the list accessor
pub fn list(&self) -> Result<ListAccessor<'_>> {
if let Value::List(list) = self.0 {
Ok(ListAccessor(list))
} else {
Err(Error::new("internal: not a list"))
}
}
/// Deserialize the value to `T`
pub fn deserialize<T: DeserializeOwned>(&self) -> Result<T> {
T::deserialize(self.0.clone()).map_err(|err| format!("internal: {}", err).into())
}
}
/// A object accessor
pub struct ObjectAccessor<'a>(pub(crate) Cow<'a, IndexMap<Name, Value>>);
impl<'a> ObjectAccessor<'a> {
/// Return a reference to the value stored for `key`, if it is present,
/// else `None`.
#[inline]
pub fn get(&'a self, name: &str) -> Option<ValueAccessor<'a>> {
self.0.get(name).map(ValueAccessor)
}
/// Like [`ObjectAccessor::get`], returns `Err` if the index does not exist
#[inline]
pub fn try_get(&'a self, name: &str) -> Result<ValueAccessor<'a>> {
self.0
.get(name)
.map(ValueAccessor)
.ok_or_else(|| Error::new(format!("internal: key \"{}\" not found", name)))
}
/// Return an iterator over the key-value pairs of the object, in their
/// order
#[inline]
pub fn iter(&'a self) -> impl Iterator<Item = (&Name, ValueAccessor<'_>)> + 'a {
self.0
.iter()
.map(|(name, value)| (name, ValueAccessor(value)))
}
}
/// A list accessor
pub struct ListAccessor<'a>(pub(crate) &'a [Value]);
impl<'a> ListAccessor<'a> {
/// Returns the number of elements in the list
#[inline]
pub fn len(&self) -> usize {
self.0.len()
}
/// Returns `true` if the list has a length of 0
#[inline]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Returns an iterator over the list
#[inline]
pub fn iter(&'a self) -> impl Iterator<Item = ValueAccessor<'_>> + 'a {
self.0.iter().map(ValueAccessor)
}
/// Returns a reference to an element depending on the index
#[inline]
pub fn get(&self, idx: usize) -> Option<ValueAccessor<'a>> {
self.0.get(idx).map(ValueAccessor)
}
/// Like [`ListAccessor::get`], returns `Err` if the index does not exist
#[inline]
pub fn try_get(&self, idx: usize) -> Result<ValueAccessor<'a>> {
self.get(idx)
.ok_or_else(|| Error::new(format!("internal: index \"{}\" not found", idx)))
}
}
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::mem::MaybeUninit;
use std::num::Wrapping;
use std::sync::Arc;
use std::sync::Once;
use common_expression::types::map::KvPair;
use common_expression::types::number::Float64Type;
use common_expression::types::number::NumberColumnBuilder;
use common_expression::types::number::NumberScalar;
use common_expression::types::number::F32;
use common_expression::types::number::F64;
use common_expression::types::AnyType;
use common_expression::types::DataType;
use common_expression::types::NumberDataType;
use common_expression::types::NumberType;
use common_expression::types::StringType;
use common_expression::types::UInt8Type;
use common_expression::types::ValueType;
use common_expression::vectorize_with_builder_1_arg;
use common_expression::vectorize_with_builder_2_arg;
use common_expression::vectorize_with_builder_3_arg;
use common_expression::Column;
use common_expression::EvalContext;
use common_expression::Function;
use common_expression::FunctionDomain;
use common_expression::FunctionEval;
use common_expression::FunctionRegistry;
use common_expression::FunctionSignature;
use common_expression::Scalar;
use common_expression::ScalarRef;
use common_expression::Value;
use common_expression::ValueRef;
use geo::coord;
use geo::Contains;
use geo::Coord;
use geo::LineString;
use geo::Polygon;
use h3o::LatLng;
use h3o::Resolution;
use once_cell::sync::OnceCell;
const PI: f64 = std::f64::consts::PI;
const PI_F: f32 = std::f32::consts::PI;
const RAD_IN_DEG: f32 = (PI / 180.0) as f32;
const RAD_IN_DEG_HALF: f32 = (PI / 360.0) as f32;
const COS_LUT_SIZE: usize = 1024; // maxerr 0.00063%
const COS_LUT_SIZE_F: f32 = 1024.0f32; // maxerr 0.00063%
const ASIN_SQRT_LUT_SIZE: usize = 512;
const METRIC_LUT_SIZE: usize = 1024;
/// Earth radius in meters using WGS84 authalic radius.
/// We use this value to be consistent with Uber H3 library.
const EARTH_RADIUS: f32 = 6371007.180918475f32;
const EARTH_DIAMETER: f32 = 2f32 * EARTH_RADIUS;
static COS_LUT: OnceCell<[f32; COS_LUT_SIZE + 1]> = OnceCell::new();
static ASIN_SQRT_LUT: OnceCell<[f32; ASIN_SQRT_LUT_SIZE + 1]> = OnceCell::new();
static SPHERE_METRIC_LUT: OnceCell<[f32; METRIC_LUT_SIZE + 1]> = OnceCell::new();
static SPHERE_METRIC_METERS_LUT: OnceCell<[f32; METRIC_LUT_SIZE + 1]> = OnceCell::new();
static WGS84_METRIC_METERS_LUT: OnceCell<[f32; 2 * (METRIC_LUT_SIZE + 1)]> = OnceCell::new();
#[derive(PartialEq)]
enum GeoMethod {
SphereDegrees,
SphereMeters,
Wgs84Meters,
}
struct Ellipse {
x: f64,
y: f64,
a: f64,
b: f64,
}
pub fn register(registry: &mut FunctionRegistry) {
// init globals.
geo_dist_init();
registry.register_passthrough_nullable_3_arg::<NumberType<F64>, NumberType<F64>, NumberType<u8>, NumberType<u64>,_, _>(
"geo_to_h3",
|_,_,_|FunctionDomain::Full,
vectorize_with_builder_3_arg::<NumberType<F64>, NumberType<F64>, NumberType<u8>, NumberType<u64>>(
|lon, lat, r, builder, ctx| {
match LatLng::new(lat.into(), lon.into()) {
Ok(coord) => {
let h3_cell = coord.to_cell(Resolution::try_from(r).unwrap());
builder.push(h3_cell.into())
},
Err(e) => {
ctx.set_error(builder.len(), e.to_string());
builder.push(0);
}
}
}
),
);
// geo distance
registry.register_4_arg::<NumberType<F64>, NumberType<F64>, NumberType<F64>, NumberType<F64>,NumberType<F32>,_, _>(
"geo_distance",
|_,_,_,_|FunctionDomain::Full,
|lon1:F64,lat1:F64,lon2:F64,lat2:F64,_| {
F32::from(distance(lon1.0 as f32, lat1.0 as f32, lon2.0 as f32, lat2.0 as f32, GeoMethod::Wgs84Meters))
},
);
// great circle angle
registry.register_4_arg::<NumberType<F64>, NumberType<F64>, NumberType<F64>, NumberType<F64>,NumberType<F32>,_, _>(
"great_circle_angle",
|_,_,_,_|FunctionDomain::Full,
|lon1:F64,lat1:F64,lon2:F64,lat2:F64,_| {
F32::from(distance(lon1.0 as f32, lat1.0 as f32, lon2.0 as f32, lat2.0 as f32, GeoMethod::SphereDegrees))
},
);
// great circle distance
registry.register_4_arg::<NumberType<F64>, NumberType<F64>, NumberType<F64>, NumberType<F64>,NumberType<F32>,_, _>(
"great_circle_distance",
|_,_,_,_|FunctionDomain::Full,
|lon1:F64,lat1:F64,lon2:F64,lat2:F64,_| {
F32::from(distance(lon1.0 as f32, lat1.0 as f32, lon2.0 as f32, lat2.0 as f32, GeoMethod::SphereMeters))
},
);
registry.register_passthrough_nullable_2_arg::<Float64Type, Float64Type, StringType, _, _>(
"geohash_encode",
|_, _| FunctionDomain::Full,
vectorize_with_builder_2_arg::<Float64Type, Float64Type, StringType>(
|lon, lat, builder, ctx| {
let c = Coord { x: lon.0, y: lat.0 };
match geohash::encode(c, 12) {
Ok(r) => builder.put_str(&r),
Err(e) => {
ctx.set_error(builder.len(), e.to_string());
builder.put_str("");
}
}
builder.commit_row();
},
),
);
registry.register_passthrough_nullable_3_arg::<Float64Type, Float64Type, UInt8Type,StringType, _, _>(
"geohash_encode",
|_, _, _| FunctionDomain::Full,
vectorize_with_builder_3_arg::<Float64Type, Float64Type, UInt8Type,StringType>(
|lon, lat, precision, builder, ctx| {
let c = Coord { x: lon.0, y: lat.0 };
let precision = if !(1..=12).contains(&precision) {12} else {precision};
match geohash::encode(c, precision as usize) {
Ok(r) => builder.put_str(&r),
Err(e) => {
ctx.set_error(builder.len(), e.to_string());
builder.put_str("");
}
}
builder.commit_row();
},
),
);
registry
.register_passthrough_nullable_1_arg::<StringType, KvPair<Float64Type, Float64Type>, _, _>(
"geohash_decode",
|_| FunctionDomain::Full,
vectorize_with_builder_1_arg::<StringType, KvPair<Float64Type, Float64Type>>(
|encoded, builder, ctx| match std::str::from_utf8(encoded)
.map_err(|e| e.to_string())
.and_then(|s| geohash::decode(s).map_err(|e| e.to_string()))
{
Ok((c, _, _)) => builder.push((c.x.into(), c.y.into())),
Err(e) => {
ctx.set_error(builder.len(), e);
builder.push((F64::from(0.0), F64::from(0.0)))
}
},
),
);
// point in ellipses
registry.register_function_factory("point_in_ellipses", |_, args_type| {
if args_type.len() < 6 {
return None;
}
Some(Arc::new(Function {
signature: FunctionSignature {
name: "point_in_ellipses".to_string(),
args_type: vec![DataType::Number(NumberDataType::Float64); args_type.len()],
return_type: DataType::Number(NumberDataType::UInt8),
},
eval: FunctionEval::Scalar {
calc_domain: Box::new(|_| FunctionDomain::Full),
eval: Box::new(point_in_ellipses_fn),
},
}))
});
// simple polygon
// point_in_polygon((x, y), [(x1, y1), (x2, y2), ...])
registry.register_function_factory("point_in_polygon", |_, args_type| {
if args_type.len() != 2 {
return None;
}
let (arg1, arg2) = if args_type.len() == 2 {
let arg1 = match args_type.get(0)? {
DataType::Tuple(tys) => vec![DataType::Number(NumberDataType::Float64); tys.len()],
_ => return None,
};
let arg2 = match args_type.get(1)? {
DataType::Array(box DataType::Tuple(tys)) => {
vec![DataType::Number(NumberDataType::Float64); tys.len()]
}
_ => return None,
};
(arg1, arg2)
} else {
(vec![], vec![])
};
Some(Arc::new(Function {
signature: FunctionSignature {
name: "point_in_polygon".to_string(),
args_type: vec![
DataType::Tuple(arg1),
DataType::Array(Box::new(DataType::Tuple(arg2))),
],
return_type: DataType::Number(NumberDataType::UInt8),
},
eval: FunctionEval::Scalar {
calc_domain: Box::new(|_| FunctionDomain::Full),
eval: Box::new(point_in_polygon_fn),
},
}))
});
// polygon with a number of holes, all as multidimensional array.
// point_in_polygon((x, y), [[(x1, y1), (x2, y2), ...], [(x21, y21), (x22, y22), ...], ...])
registry.register_function_factory("point_in_polygon", |_, args_type| {
if args_type.len() != 2 {
return None;
}
let (arg1, arg2) = if args_type.len() == 2 {
let arg1 = match args_type.get(0)? {
DataType::Tuple(tys) => vec![DataType::Number(NumberDataType::Float64); tys.len()],
_ => return None,
};
let arg2 = match args_type.get(1)? {
DataType::Array(box DataType::Array(box DataType::Tuple(tys))) => {
vec![DataType::Number(NumberDataType::Float64); tys.len()]
}
_ => return None,
};
(arg1, arg2)
} else {
(vec![], vec![])
};
Some(Arc::new(Function {
signature: FunctionSignature {
name: "point_in_polygon".to_string(),
args_type: vec![
DataType::Tuple(arg1),
DataType::Array(Box::new(DataType::Array(Box::new(DataType::Tuple(arg2))))),
],
return_type: DataType::Number(NumberDataType::UInt8),
},
eval: FunctionEval::Scalar {
calc_domain: Box::new(|_| FunctionDomain::Full),
eval: Box::new(point_in_polygon_fn),
},
}))
});
// polygon with a number of holes, each hole as a subsequent argument.
// point_in_polygon((x, y), [(x1, y1), (x2, y2), ...], [(x21, y21), (x22, y22), ...], ...)
registry.register_function_factory("point_in_polygon", |_, args_type| {
if args_type.len() < 3 {
return None;
}
let mut args = vec![];
let arg1 = match args_type.get(0)? {
DataType::Tuple(tys) => vec![DataType::Number(NumberDataType::Float64); tys.len()],
_ => return None,
};
args.push(DataType::Tuple(arg1));
let arg2: Vec<DataType> = match args_type.get(1)? {
DataType::Array(box DataType::Tuple(tys)) => {
vec![DataType::Number(NumberDataType::Float64); tys.len()]
}
_ => return None,
};
(0..args_type.len() - 1)
.for_each(|_| args.push(DataType::Array(Box::new(DataType::Tuple(arg2.clone())))));
Some(Arc::new(Function {
signature: FunctionSignature {
name: "point_in_polygon".to_string(),
args_type: args,
return_type: DataType::Number(NumberDataType::UInt8),
},
eval: FunctionEval::Scalar {
calc_domain: Box::new(|_| FunctionDomain::Full),
eval: Box::new(point_in_polygon_fn),
},
}))
});
}
fn get_coord(fields: &[ScalarRef]) -> Coord {
let v = fields
.iter()
.map(|s| ValueRef::Scalar(Float64Type::try_downcast_scalar(s).unwrap()))
.map(|x: ValueRef<Float64Type>| match x {
ValueRef::Scalar(v) => *v,
_ => 0_f64,
})
.collect::<Vec<_>>();
Coord { x: v[0], y: v[1] }
}
fn point_in_polygon_fn(args: &[ValueRef<AnyType>], _: &mut EvalContext) -> Value<AnyType> {
let len = args.iter().find_map(|arg| match arg {
ValueRef::Column(col) => Some(col.len()),
_ => None,
});
let input_rows = len.unwrap_or(1);
let mut builder = NumberColumnBuilder::with_capacity(&NumberDataType::UInt8, input_rows);
for idx in 0..input_rows {
let arg0: Vec<f64> = match &args[0] {
ValueRef::Scalar(ScalarRef::Tuple(fields)) => fields
.iter()
.cloned()
.map(|s| ValueRef::Scalar(Float64Type::try_downcast_scalar(&s).unwrap()))
.map(|x: ValueRef<Float64Type>| match x {
ValueRef::Scalar(v) => *v,
_ => unreachable!(),
})
.collect(),
ValueRef::Column(Column::Tuple(fields)) => fields
.iter()
.cloned()
.map(|c| ValueRef::Column(Float64Type::try_downcast_column(&c).unwrap()))
.map(|x: ValueRef<Float64Type>| match x {
ValueRef::Column(c) => unsafe {
Float64Type::index_column_unchecked(&c, idx).0
},
_ => unreachable!(),
})
.collect(),
_ => unreachable!(),
};
let point = coord! {x:arg0[0], y:arg0[1]};
let polys = if args.len() == 2 {
let polys: Vec<Vec<Coord>> = match &args[1] {
ValueRef::Scalar(ScalarRef::Array(c)) => c
.iter()
.map(|s| match s {
// form type 1: ((x, y), [(x1, y1), (x2, y2), ...])
// match arm return value type should be equal, so we wrap to a vec here.
ScalarRef::Tuple(fields) => vec![get_coord(&fields)],
// form type 2: ((x, y), [[(x1, y1), (x2, y2), ...], [(x21, y21), (x22, y22), ...], ...])
ScalarRef::Array(inner_c) => inner_c
.iter()
.map(|s| match s {
ScalarRef::Tuple(fields) => get_coord(&fields),
_ => unreachable!(),
})
.collect(),
_ => unreachable!(),
})
.collect(),
ValueRef::Column(Column::Array(c)) => unsafe {
c.index_unchecked(idx)
.iter()
.map(|s| match s {
ScalarRef::Tuple(fields) => vec![get_coord(&fields)],
ScalarRef::Array(inner_c) => inner_c
.iter()
.map(|s| match s {
ScalarRef::Tuple(fields) => get_coord(&fields),
_ => unreachable!(),
})
.collect(),
_ => unreachable!(),
})
.collect::<Vec<_>>()
},
_ => unreachable!(),
};
polys
} else {
// form type 3: ((x, y), [(x1, y1), (x2, y2), ...], [(x21, y21), (x22, y22), ...], ...)
let mut polys: Vec<Vec<Coord>> = Vec::new();
for arg in &args[1..] {
let hole: Vec<Coord> = match arg {
ValueRef::Scalar(ScalarRef::Array(c)) => c
.iter()
.map(|s| match s {
ScalarRef::Tuple(fields) => get_coord(&fields),
_ => unreachable!(),
})
.collect(),
ValueRef::Column(Column::Array(c)) => unsafe {
c.index_unchecked(idx)
.iter()
.map(|s| match s {
ScalarRef::Tuple(fields) => get_coord(&fields),
_ => unreachable!(),
})
.collect()
},
_ => unreachable!(),
};
polys.push(hole);
}
polys
};
// since we wrapped form type 1 to a vec before, we should flatten here.
// form type 1 [[coord1], [coord2], ...] -> [coord1, coord2, ...]
let polys = if polys[0].len() == 1 {
vec![polys.into_iter().flatten().collect()]
} else {
polys
};
let outer = LineString::from(polys[0].clone());
let inners: Vec<LineString> = if polys.len() > 1 {
polys[1..]
.iter()
.map(|p| LineString::from(p.clone()))
.collect()
} else {
vec![]
};
let poly = Polygon::new(outer, inners);
let is_in = poly.contains(&point);
builder.push(NumberScalar::UInt8(u8::from(is_in)));
}
match len {
Some(_) => Value::Column(Column::Number(builder.build())),
_ => Value::Scalar(Scalar::Number(builder.build_scalar())),
}
}
fn point_in_ellipses_fn(args: &[ValueRef<AnyType>], _: &mut EvalContext) -> Value<AnyType> {
let len = args.iter().find_map(|arg| match arg {
ValueRef::Column(col) => Some(col.len()),
_ => None,
});
let args = args
.iter()
.map(|arg| arg.try_downcast::<Float64Type>().unwrap())
.collect::<Vec<_>>();
let input_rows = len.unwrap_or(1);
let ellipses_cnt = (args.len() - 2) / 4;
let mut ellipses: Vec<Ellipse> = Vec::with_capacity(ellipses_cnt);
for ellipse_idx in 0..ellipses_cnt {
let mut ellipse_data = [0.0; 4];
for (idx, e_data) in ellipse_data.iter_mut().enumerate() {
let arg_idx = 2 + 4 * ellipse_idx + idx;
*e_data = match args[arg_idx] {
ValueRef::Scalar(v) => *v,
_ => 0f64,
};
}
ellipses.push(Ellipse {
x: ellipse_data[0],
y: ellipse_data[1],
a: ellipse_data[2],
b: ellipse_data[3],
});
}
let mut start_index = 0;
let mut builder = NumberColumnBuilder::with_capacity(&NumberDataType::UInt8, input_rows);
for idx in 0..input_rows {
let col_x = match &args[0] {
ValueRef::Scalar(v) => *v,
ValueRef::Column(c) => unsafe { Float64Type::index_column_unchecked(c, idx) },
};
let col_y = match &args[1] {
ValueRef::Scalar(v) => *v,
ValueRef::Column(c) => unsafe { Float64Type::index_column_unchecked(c, idx) },
};
let r = u8::from(is_point_in_ellipses(
col_x.0,
col_y.0,
&ellipses,
ellipses_cnt,
&mut start_index,
));
builder.push(NumberScalar::UInt8(r));
}
match len {
Some(_) => Value::Column(Column::Number(builder.build())),
_ => Value::Scalar(Scalar::Number(builder.build_scalar())),
}
}
fn is_point_in_ellipses(
x: f64,
y: f64,
ellipses: &[Ellipse],
ellipses_count: usize,
start_idx: &mut usize,
) -> bool {
let mut index = *start_idx;
for _ in 0..ellipses_count {
let el = &ellipses[index];
let p1 = (x - el.x) / el.a;
let p2 = (y - el.y) / el.b;
if x <= el.x + el.a
&& x >= el.x - el.a
&& y <= el.y + el.b
&& y >= el.y - el.b
&& p1 * p1 + p2 * p2 <= 1.0
{
*start_idx = index;
return true;
}
index += 1;
if index == ellipses_count {
index = 0;
}
}
false
}
pub fn geo_dist_init() {
// Using `get_or_init` for unit tests cause each test will re-register all functions.
COS_LUT.get_or_init(|| {
let cos_lut: [f32; COS_LUT_SIZE + 1] = (0..=COS_LUT_SIZE)
.map(|i| (2f64 * PI * i as f64 / COS_LUT_SIZE as f64).cos() as f32)
.collect::<Vec<f32>>()
.try_into()
.unwrap();
cos_lut
});
ASIN_SQRT_LUT.get_or_init(|| {
let asin_sqrt_lut: [f32; ASIN_SQRT_LUT_SIZE + 1] = (0..=ASIN_SQRT_LUT_SIZE)
.map(|i| (i as f64 / ASIN_SQRT_LUT_SIZE as f64).sqrt().asin() as f32)
.collect::<Vec<f32>>()
.try_into()
.unwrap();
asin_sqrt_lut
});
Once::new().call_once(|| {
let (wsg84_metric_meters_lut, sphere_metric_meters_lut, sphere_metric_lut) = {
let mut wgs84_metric_meters_lut: [MaybeUninit<f32>; 2 * (METRIC_LUT_SIZE + 1)] =
unsafe { MaybeUninit::uninit().assume_init() };
let mut sphere_metric_meters_lut: [MaybeUninit<f32>; METRIC_LUT_SIZE + 1] =
unsafe { MaybeUninit::uninit().assume_init() };
let mut sphere_metric_lut: [MaybeUninit<f32>; METRIC_LUT_SIZE + 1] =
unsafe { MaybeUninit::uninit().assume_init() };
for i in 0..=METRIC_LUT_SIZE {
let latitude: f64 = i as f64 * (PI / METRIC_LUT_SIZE as f64) - PI * 0.5f64;
wgs84_metric_meters_lut[i].write(
(111132.09f64 - 566.05f64 * (2f64 * latitude).cos()
+ 1.20f64 * (4f64 * latitude).cos())
.sqrt() as f32,
);
wgs84_metric_meters_lut[i * 2 + 1].write(
(111415.13f64 * latitude.cos() - 94.55f64 * (3f64 * latitude).cos()
+ 0.12f64 * (5f64 * latitude).cos())
.sqrt() as f32,
);
sphere_metric_meters_lut[i]
.write(((EARTH_DIAMETER as f64 * PI / 360f64) * latitude.cos()).powi(2) as f32);
sphere_metric_lut[i].write(latitude.cos().powi(2) as f32);
}
// Everything is initialized, transmute and return.
unsafe {
(
std::mem::transmute::<_, [f32; 2 * (METRIC_LUT_SIZE + 1)]>(
wgs84_metric_meters_lut,
),
std::mem::transmute::<_, [f32; METRIC_LUT_SIZE + 1]>(sphere_metric_meters_lut),
std::mem::transmute::<_, [f32; METRIC_LUT_SIZE + 1]>(sphere_metric_lut),
)
}
};
WGS84_METRIC_METERS_LUT.get_or_init(|| wsg84_metric_meters_lut);
SPHERE_METRIC_METERS_LUT.get_or_init(|| sphere_metric_meters_lut);
SPHERE_METRIC_LUT.get_or_init(|| sphere_metric_lut);
});
}
#[inline(always)]
fn geodist_deg_diff(mut f: f32) -> f32 {
f = f.abs();
if f > 180f32 {
f = 360f32 - f;
}
f
}
#[inline]
fn geodist_fast_cos(x: f32) -> f32 {
let mut y = x.abs() * (COS_LUT_SIZE_F / PI_F / 2.0f32);
let mut i = float_to_index(y);
y -= i as f32;
i &= COS_LUT_SIZE - 1;
let cos_lut = COS_LUT.get().unwrap();
cos_lut[i] + (cos_lut[i + 1] - cos_lut[i]) * y
}
#[inline]
fn geodist_fast_sin(x: f32) -> f32 {
let mut y = x.abs() * (COS_LUT_SIZE_F / PI_F / 2.0f32);
let mut i = float_to_index(y);
y -= i as f32;
// cos(x - pi / 2) = sin(x), costable / 4 = pi / 2
i = (Wrapping(i) - Wrapping(COS_LUT_SIZE / 4)).0 & (COS_LUT_SIZE - 1);
let cos_lut = COS_LUT.get().unwrap();
cos_lut[i] + (cos_lut[i + 1] - cos_lut[i]) * y
}
#[inline]
fn geodist_fast_asin_sqrt(x: f32) -> f32 {
if x < 0.122f32 {
let x = x as f64;
let y = x.sqrt();
return (y
+ x * y * 0.166666666666666f64
+ x * x * y * 0.075f64
+ x * x * x * y * 0.044642857142857f64) as f32;
}
if x < 0.948f32 {
let x = x * ASIN_SQRT_LUT_SIZE as f32;
let i = float_to_index(x);
let asin_sqrt_lut = ASIN_SQRT_LUT.get().unwrap();
return asin_sqrt_lut[i] + (asin_sqrt_lut[i + 1] - asin_sqrt_lut[i]) * (x - i as f32);
}
x.sqrt().asin()
}
#[inline(always)]
fn float_to_index(x: f32) -> usize {
x as usize
}
fn distance(lon1deg: f32, lat1deg: f32, lon2deg: f32, lat2deg: f32, method: GeoMethod) -> f32 {
let lat_diff = geodist_deg_diff(lat1deg - lat2deg);
let lon_diff = geodist_deg_diff(lon1deg - lon2deg);
if lon_diff < 13f32 {
let latitude_midpoint: f32 = (lat1deg + lat2deg + 180f32) * METRIC_LUT_SIZE as f32 / 360f32;
let latitude_midpoint_index = float_to_index(latitude_midpoint);
let (k_lat, k_lon) = match method {
GeoMethod::SphereDegrees => {
let sphere_metric_lut = SPHERE_METRIC_LUT.get().unwrap();
let lat = 1f32;
let lon = sphere_metric_lut[latitude_midpoint_index]
+ (sphere_metric_lut[latitude_midpoint_index + 1]
- sphere_metric_lut[latitude_midpoint_index])
* (latitude_midpoint - latitude_midpoint_index as f32);
(lat, lon)
}
GeoMethod::SphereMeters => {
let sphere_metric_meters_lut = SPHERE_METRIC_METERS_LUT.get().unwrap();
let lat = (EARTH_DIAMETER * PI_F / 360f32).powi(2);
let lon = sphere_metric_meters_lut[latitude_midpoint_index]
+ (sphere_metric_meters_lut[latitude_midpoint_index + 1]
- sphere_metric_meters_lut[latitude_midpoint_index])
* (latitude_midpoint - latitude_midpoint_index as f32);
(lat, lon)
}
GeoMethod::Wgs84Meters => {
let wgs84_metric_meters_lut = WGS84_METRIC_METERS_LUT.get().unwrap();
let lat: f32 = wgs84_metric_meters_lut[latitude_midpoint_index * 2]
+ (wgs84_metric_meters_lut[(latitude_midpoint_index + 1) * 2]
- wgs84_metric_meters_lut[latitude_midpoint_index * 2])
* (latitude_midpoint - latitude_midpoint_index as f32);
let lon: f32 = wgs84_metric_meters_lut[latitude_midpoint_index * 2 + 1]
+ (wgs84_metric_meters_lut[(latitude_midpoint_index + 1) * 2 + 1]
- wgs84_metric_meters_lut[latitude_midpoint_index * 2 + 1])
* (latitude_midpoint - latitude_midpoint_index as f32);
(lat, lon)
}
};
(k_lat * lat_diff * lat_diff + k_lon * lon_diff * lon_diff).sqrt()
} else {
let a: f32 = (geodist_fast_sin(lat_diff * RAD_IN_DEG_HALF)).powi(2)
+ geodist_fast_cos(lat1deg * RAD_IN_DEG)
* geodist_fast_cos(lat2deg * RAD_IN_DEG)
* (geodist_fast_sin(lon_diff * RAD_IN_DEG_HALF)).powi(2);
if method == GeoMethod::SphereDegrees {
return (360f32 / PI_F) * geodist_fast_asin_sqrt(a);
}
EARTH_DIAMETER * geodist_fast_asin_sqrt(a)
}
}
|
use crate::account::Account;
use crate::pubkey::Pubkey;
const NATIVE_LOADER_PROGRAM_ID: [u8; 32] = [
5, 135, 132, 191, 20, 139, 164, 40, 47, 176, 18, 87, 72, 136, 169, 241, 83, 160, 125, 173, 247,
101, 192, 69, 92, 154, 151, 3, 128, 0, 0, 0,
];
pub fn id() -> Pubkey {
Pubkey::new(&NATIVE_LOADER_PROGRAM_ID)
}
pub fn check_id(program_id: &Pubkey) -> bool {
program_id.as_ref() == NATIVE_LOADER_PROGRAM_ID
}
/// Create an executable account with the given shared object name.
pub fn create_loadable_account(name: &str) -> Account {
Account {
difs: 1,
reputations: 0,
owner: id(),
data: name.as_bytes().to_vec(),
executable: true,
}
}
|
mod api;
use crate::lttp::AppState;
use axum::{
extract::Path,
http::{
header::{
HeaderValue,
CONTENT_LENGTH,
CONTENT_TYPE,
},
status::StatusCode,
HeaderMap,
},
response::{
IntoResponse,
Redirect,
Response,
},
routing::get,
Router,
};
use hyper::body::HttpBody;
use once_cell::sync;
use std::{
collections::HashMap,
path::{
self,
PathBuf,
},
sync::Arc,
};
use tower::ServiceBuilder;
use tower_http::{
set_header::SetResponseHeaderLayer,
trace::TraceLayer,
};
#[allow(unused_macros)]
macro_rules! initialize_asset {
($relative_path:literal, $absolute_path: literal) => {
UiAsset {
relative_path: $relative_path,
media_type: sync::Lazy::new(|| {
let media_type = mime_guess::from_path($relative_path).first_or_octet_stream();
String::from(media_type.essence_str())
}),
contents_bytes: include_bytes!($absolute_path),
}
};
}
#[iftree::include_file_tree(
"
paths = '/ui/dist/**'
template.initializer = 'initialize_asset'
"
)]
#[derive(Debug)]
pub struct UiAsset {
relative_path: &'static str,
media_type: sync::Lazy<String>,
contents_bytes: &'static [u8],
}
static UI_ASSET_MAP: sync::Lazy<HashMap<&str, &UiAsset>> =
sync::Lazy::new(|| ASSETS.iter().map(|asset| (asset.relative_path, asset)).collect());
pub fn build(app_state: Arc<AppState>) -> Router {
Router::new()
.nest("/api", api::build(app_state))
.route("/", get(|| async { Redirect::permanent("/ui/") }))
.route("/ui/*path", get(get_ui_file))
.route("/image/*path", get(get_image_file))
.layer(
ServiceBuilder::new()
.layer(SetResponseHeaderLayer::overriding(
CONTENT_LENGTH,
content_length_from_response,
))
.layer(TraceLayer::new_for_http()),
)
}
fn content_length_from_response<B>(response: &Response<B>) -> Option<HeaderValue>
where
B: HttpBody,
{
response
.body()
.size_hint()
.exact()
.map(|size| HeaderValue::from_str(&size.to_string()).unwrap())
}
#[allow(clippy::unused_async)]
async fn get_ui_file(Path(file_name): Path<String>) -> impl IntoResponse {
let file = PathBuf::from(file_name.trim_start_matches('/'));
let mut path = path::Path::new("ui/dist/").join(file);
let Some(mut path_str) = path.to_str() else {
return Err("Invalid UI file name".to_string());
};
let file = if let Some(f) = UI_ASSET_MAP.get(&path_str) {
f
} else {
path = path.join("index.html");
path_str = match path.to_str() {
Some(s) => s,
None => return Err("Invalid UI file name".to_string()),
};
match UI_ASSET_MAP.get(&path_str) {
Some(f) => f,
None => return Ok((StatusCode::NOT_FOUND, HeaderMap::new(), vec![])),
}
};
let mut headers = HeaderMap::new();
// TODO: Set a real CONTENT_TYPE: https://github.com/evolutics/iftree/blob/5a178ee040baa37184981d778ba9a82f8e71e3da/examples/scenario_media_type.rs
headers.insert(CONTENT_TYPE, file.media_type.parse().unwrap());
Ok((StatusCode::OK, headers, file.contents_bytes.to_vec()))
}
#[allow(clippy::unused_async)]
async fn get_image_file(Path(file_name): Path<String>) -> impl IntoResponse {
let file = PathBuf::from(file_name.trim_start_matches('/'));
let path = path::Path::new("ui/dist/image/").join(file);
let Some(path_str) = path.to_str() else {
return Err("Invalid image file name".to_string());
};
let Some(file) = UI_ASSET_MAP.get(&path_str) else {
return Ok((StatusCode::NOT_FOUND, HeaderMap::new(), vec![]));
};
let mut headers = HeaderMap::new();
headers.insert(CONTENT_TYPE, file.media_type.parse().unwrap());
Ok((StatusCode::OK, headers, file.contents_bytes.to_vec()))
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
extern crate argparse;
extern crate js;
extern crate libc;
extern crate linenoise;
use std::cell::RefCell;
use std::env;
use std::ffi::CStr;
use std::fs::File;
use std::io::Read;
use std::ptr;
use std::str;
use argparse::{ArgumentParser, StoreTrue, Store};
use js::{JSCLASS_RESERVED_SLOTS_MASK,JSCLASS_GLOBAL_SLOT_COUNT,JSCLASS_IS_GLOBAL};
use js::jsapi::{CurrentGlobalOrNull, JSCLASS_RESERVED_SLOTS_SHIFT,JS_GlobalObjectTraceHook};
use js::jsapi::{CallArgs,CompartmentOptions,OnNewGlobalHookOption,Rooted,Value};
use js::jsapi::{JS_DefineFunction,JS_Init,JS_NewGlobalObject, JS_InitStandardClasses,JS_EncodeStringToUTF8, JS_ReportPendingException, JS_BufferIsCompilableUnit};
use js::jsapi::{JSAutoCompartment,JSAutoRequest,JSContext,JSClass};
use js::jsapi::{JS_SetGCParameter, JSGCParamKey, JSGCMode};
// use jsapi::{Rooted, RootedValue, Handle, MutableHandle};
// use jsapi::{MutableHandleValue, HandleValue, HandleObject};
use js::jsapi::{RootedValue, HandleObject, HandleValue, RuntimeOptionsRef};
use js::jsapi::{JS_SetParallelParsingEnabled, JS_SetOffthreadIonCompilationEnabled, JSJitCompilerOption};
use js::jsapi::{JS_SetGlobalJitCompilerOption};
use js::jsval::UndefinedValue;
use js::rust::Runtime;
thread_local!(pub static RUNTIME: RefCell<Option<Runtime>> = RefCell::new(None));
static CLASS: &'static JSClass = &JSClass {
name: b"test\0" as *const u8 as *const libc::c_char,
flags: JSCLASS_IS_GLOBAL | ((JSCLASS_GLOBAL_SLOT_COUNT & JSCLASS_RESERVED_SLOTS_MASK) << JSCLASS_RESERVED_SLOTS_SHIFT),
addProperty: None,
delProperty: None,
getProperty: None,
setProperty: None,
enumerate: None,
resolve: None,
mayResolve: None,
finalize: None,
call: None,
hasInstance: None,
construct: None,
trace: Some(JS_GlobalObjectTraceHook),
reserved: [0 as *mut _; 23]
};
struct JSOptions {
interactive: bool,
disable_baseline: bool,
disable_ion: bool,
disable_asmjs: bool,
disable_native_regexp: bool,
disable_parallel_parsing: bool,
disable_offthread_compilation: bool,
enable_baseline_unsafe_eager_compilation: bool,
enable_ion_unsafe_eager_compilation: bool,
enable_discard_system_source: bool,
enable_asyncstack: bool,
enable_throw_on_debugee_would_run: bool,
enable_dump_stack_on_debugee_would_run: bool,
enable_werror: bool,
enable_strict: bool,
disable_shared_memory: bool,
disable_gc_per_compartment: bool,
disable_incremental: bool,
disable_compacting: bool,
disable_dynamic_work_slice: bool,
disable_dynamic_mark_slice: bool,
disable_refresh_frame_slices: bool,
disable_dynamic_heap_growth: bool,
script: String,
}
fn main() {
let js_options = parse_args();
unsafe {
JS_Init();
}
RUNTIME.with(|ref r| {
*r.borrow_mut() = Some(unsafe { Runtime::new() });
});
let cx = RUNTIME.with(|ref r| r.borrow().as_ref().unwrap().cx());
let rt = RUNTIME.with(|ref r| r.borrow().as_ref().unwrap().rt());
let h_option = OnNewGlobalHookOption::FireOnNewGlobalHook;
let c_option = CompartmentOptions::default();
let _ar = JSAutoRequest::new(cx);
let global = unsafe { JS_NewGlobalObject(cx, CLASS, ptr::null_mut(), h_option, &c_option) };
let global_root = Rooted::new(cx, global);
let global = global_root.handle();
let _ac = JSAutoCompartment::new(cx, global.get());
let rt_opts = unsafe { &mut *RuntimeOptionsRef(rt) };
rt_opts.set_baseline_(!js_options.disable_baseline);
rt_opts.set_ion_(!js_options.disable_ion);
rt_opts.set_asmJS_(!js_options.disable_asmjs);
rt_opts.set_extraWarnings_(js_options.enable_strict);
rt_opts.set_nativeRegExp_(!js_options.disable_native_regexp);
unsafe { JS_SetParallelParsingEnabled(rt, !js_options.disable_parallel_parsing); }
unsafe { JS_SetOffthreadIonCompilationEnabled(rt, !js_options.disable_offthread_compilation); }
unsafe { JS_SetGlobalJitCompilerOption(rt, JSJitCompilerOption::JSJITCOMPILER_BASELINE_WARMUP_TRIGGER,
if js_options.enable_baseline_unsafe_eager_compilation { 0i32 } else { -1i32 } as u32); }
unsafe { JS_SetGlobalJitCompilerOption(rt, JSJitCompilerOption::JSJITCOMPILER_ION_WARMUP_TRIGGER,
if js_options.enable_ion_unsafe_eager_compilation { 0i32 } else { -1i32 } as u32); }
rt_opts.set_werror_(js_options.enable_werror);
let mode = if !js_options.disable_incremental {
println!("incremental");
JSGCMode::JSGC_MODE_INCREMENTAL
} else if js_options.disable_gc_per_compartment {
println!("compartment");
JSGCMode::JSGC_MODE_COMPARTMENT
} else {
println!("global");
JSGCMode::JSGC_MODE_GLOBAL
};
unsafe { JS_SetGCParameter(rt, JSGCParamKey::JSGC_MODE, mode as u32); }
unsafe { JS_SetGCParameter(rt, JSGCParamKey::JSGC_COMPACTING_ENABLED, !js_options.disable_compacting as u32); }
unsafe { JS_SetGCParameter(rt, JSGCParamKey::JSGC_DYNAMIC_MARK_SLICE, !js_options.disable_dynamic_mark_slice as u32); }
unsafe { JS_SetGCParameter(rt, JSGCParamKey::JSGC_DYNAMIC_HEAP_GROWTH, !js_options.disable_dynamic_heap_growth as u32); }
unsafe {
JS_InitStandardClasses(cx, global);
JS_DefineFunction(cx, global, b"print\0".as_ptr() as *const libc::c_char, Some(print), 1, 0);
JS_DefineFunction(cx, global, b"load\0".as_ptr() as *const libc::c_char, Some(load), 1, 0);
}
if js_options.script != "" {
RUNTIME.with(|ref r| {
let _ = run_script(r.borrow().as_ref().unwrap(), global, &js_options.script);
});
}
if js_options.script == "" || js_options.interactive {
RUNTIME.with(|ref r| {
run_read_eval_print_loop(r.borrow().as_ref().unwrap(), global);
});
}
}
fn run_read_eval_print_loop(runtime: &Runtime, global: HandleObject) {
let mut line_no = 1u32;
loop {
let start_line = line_no;
let mut buffer = String::new();
loop {
let line = match linenoise::prompt("js> ") {
None => return,
Some(line) => line
};
buffer.push_str(&line);
line_no += 1;
linenoise::history_add(&buffer);
let script_utf8: Vec<u8> = buffer.bytes().collect();
let script_ptr = script_utf8.as_ptr() as *const i8;
let script_len = script_utf8.len() as usize;
unsafe {
if JS_BufferIsCompilableUnit(runtime.cx(), global, script_ptr, script_len) {
break;
}
}
}
let mut rval = RootedValue::new(runtime.cx(), UndefinedValue());
match runtime.evaluate_script(global, &buffer, "typein", start_line, rval.handle_mut()) {
Err(_) => unsafe { JS_ReportPendingException(runtime.cx()); },
_ => if !rval.handle().is_undefined() {
println!("{}", fmt_js_value(runtime.cx(), rval.handle()))
}
}
}
}
fn run_script(runtime: &Runtime, global: HandleObject, filename: &String) -> Result<i32, &'static str> {
let mut source = "".to_string();
{
let mut file = match File::open(&filename) {
Err(_) => return Err("Error opening source file"),
Ok(file) => file
};
if let Err(_) = file.read_to_string(&mut source) {
return Err("Error reading from source file");
}
}
let mut rval = RootedValue::new(runtime.cx(), UndefinedValue());
match runtime.evaluate_script(global, &source, filename, 1, rval.handle_mut()) {
Err(_) => unsafe { JS_ReportPendingException(runtime.cx()); Err("Uncaught exception during script execution") },
_ => Ok(1)
}
}
fn parse_args<'a>() -> JSOptions {
let mut options = JSOptions {
interactive: false,
disable_baseline: false,
disable_ion: false,
disable_asmjs: false,
disable_native_regexp: false,
disable_parallel_parsing: false,
disable_offthread_compilation: false,
enable_baseline_unsafe_eager_compilation: false,
enable_ion_unsafe_eager_compilation: false,
enable_discard_system_source: false,
enable_asyncstack: false,
enable_throw_on_debugee_would_run: false,
enable_dump_stack_on_debugee_would_run: false,
enable_werror: false,
enable_strict: false,
disable_shared_memory: false,
disable_gc_per_compartment: false,
disable_incremental: false,
disable_compacting: false,
disable_dynamic_work_slice: false,
disable_dynamic_mark_slice: false,
disable_refresh_frame_slices: false,
disable_dynamic_heap_growth: false,
script: String::new(),
};
{
let mut ap = ArgumentParser::new();
ap.set_description("The SpiderMonkey shell provides a command line interface to the
JavaScript engine. Code and file options provided via the command line are
run left to right. If provided, the optional script argument is run after
all options have been processed. Just-In-Time compilation modes may be enabled via
command line options.");
ap.refer(&mut options.interactive)
.add_option(&["-i", "--shell"], StoreTrue,
"Enter prompt after running code");
ap.refer(&mut options.disable_baseline)
.add_option(&["--no-baseline"], StoreTrue,
"Disable baseline compiler");
ap.refer(&mut options.disable_ion)
.add_option(&["--no-ion"], StoreTrue,
"Disable IonMonkey");
ap.refer(&mut options.disable_asmjs)
.add_option(&["--no-asmjs"], StoreTrue,
"Disable asm.js compilation");
ap.refer(&mut options.disable_native_regexp)
.add_option(&["--no-native-regexp"], StoreTrue,
"Disable native regexp compilation");
ap.refer(&mut options.disable_parallel_parsing)
.add_option(&["--no-parallel-parsing"], StoreTrue,
"Disable parallel parsing");
ap.refer(&mut options.disable_offthread_compilation)
.add_option(&["--no-offthread-compilation"], StoreTrue,
"Disable offthread compilation");
ap.refer(&mut options.enable_baseline_unsafe_eager_compilation)
.add_option(&["--baseline-unsafe-eager-compilation"], StoreTrue,
"Enable baseline unsafe eager compilation");
ap.refer(&mut options.enable_ion_unsafe_eager_compilation)
.add_option(&["--ion-unsafe-eager-compilation"], StoreTrue,
"Enable ion unsafe eager compilation");
ap.refer(&mut options.enable_discard_system_source)
.add_option(&["--discard-system-source"], StoreTrue,
"Enable discard system source");
ap.refer(&mut options.enable_asyncstack)
.add_option(&["--asyncstack"], StoreTrue,
"Enable asyncstack");
ap.refer(&mut options.enable_throw_on_debugee_would_run)
.add_option(&["--throw-on-debugee-would-run"], StoreTrue,
"Enable throw on debugee would run");
ap.refer(&mut options.enable_dump_stack_on_debugee_would_run)
.add_option(&["--dump-stack-on-debugee-would-run"], StoreTrue,
"Enable dump stack on debugee would run");
ap.refer(&mut options.enable_werror)
.add_option(&["--werror"], StoreTrue,
"Enable werror");
ap.refer(&mut options.enable_strict)
.add_option(&["--strict"], StoreTrue,
"Enable strict");
ap.refer(&mut options.disable_shared_memory)
.add_option(&["--no-shared-memory"], StoreTrue,
"Disable shared memory");
ap.refer(&mut options.disable_gc_per_compartment)
.add_option(&["--no-gc-per-compartment"], StoreTrue,
"Disable GC per compartment");
ap.refer(&mut options.disable_incremental)
.add_option(&["--no-incremental"], StoreTrue,
"Disable incremental");
ap.refer(&mut options.disable_compacting)
.add_option(&["--no-compacting"], StoreTrue,
"Disable compacting");
ap.refer(&mut options.disable_dynamic_work_slice)
.add_option(&["--no-dynamic-work-slice"], StoreTrue,
"Disable dynamic work slice");
ap.refer(&mut options.disable_dynamic_mark_slice)
.add_option(&["--no-dynamic-mark-slice"], StoreTrue,
"Disable dynamic mark slice");
ap.refer(&mut options.disable_refresh_frame_slices)
.add_option(&["--no-refresh_frame_slices"], StoreTrue,
"Disable refresh frame slices");
ap.refer(&mut options.disable_dynamic_heap_growth)
.add_option(&["--no-dynamic-heap-growth"], StoreTrue,
"Disable dynamic heap growth");
ap.refer(&mut options.script)
.add_argument("script", Store,
"A script to execute (after all options)");
ap.parse_args_or_exit();
}
options
}
unsafe extern "C" fn print(cx: *mut JSContext, argc: u32, vp: *mut Value) -> bool {
let args = CallArgs::from_vp(vp, argc);
let output = (0..args._base.argc_)
.map(|i| fmt_js_value(cx, args.get(i)))
.collect::<Vec<String>>()
.join(" ");
println!("{}", output);
args.rval().set(UndefinedValue());
return true;
}
unsafe extern "C" fn load(cx: *mut JSContext, argc: u32, vp: *mut Value) -> bool {
let args = CallArgs::from_vp(vp, argc);
for i in 0..args._base.argc_ {
let val = args.get(i);
let s = js::rust::ToString(cx, val);
if s.is_null() {
// report error
return false;
}
let mut filename = env::current_dir().unwrap();
let path_root = Rooted::new(cx, s);
let path = JS_EncodeStringToUTF8(cx, path_root.handle());
let path = CStr::from_ptr(path);
filename.push(str::from_utf8(path.to_bytes()).unwrap());
let global = CurrentGlobalOrNull(cx);
let global_root = Rooted::new(cx, global);
RUNTIME.with(|ref r| {
let _ = run_script(r.borrow().as_ref().unwrap(), global_root.handle(),
&filename.to_str().unwrap().to_owned());
});
}
args.rval().set(UndefinedValue());
return true;
}
fn fmt_js_value(cx: *mut JSContext, val: HandleValue) -> String {
let js = unsafe { js::rust::ToString(cx, val) };
let message_root = Rooted::new(cx, js);
let message = unsafe { JS_EncodeStringToUTF8(cx, message_root.handle()) };
let message = unsafe { CStr::from_ptr(message) };
String::from(str::from_utf8(message.to_bytes()).unwrap())
}
|
#![allow(warnings)]
use rand::prelude::StdRng;
use rand::SeedableRng;
use spacegame::core::noise::perlin::{make_permutation, perlin2d, Perlin};
fn main() {
let imgx = 2048;
let imgy = 2048;
let nb_blocks = [64, 64];
let block_size = [32u32; 32];
let image_size = [block_size[0] * nb_blocks[0], block_size[1] * nb_blocks[1]];
// Create a new ImgBuf with width: imgx and height: imgy
let mut imgbuf = image::ImageBuffer::new(image_size[0], image_size[1]);
let mut rnd = StdRng::from_entropy();
let perlin = Perlin::new(&mut rnd);
let mut max = 0.0f32;
let mut min = 0.0f32;
let values = {
let w = nb_blocks[0];
let h = nb_blocks[1];
let mut values = vec![];
for x in 0..w {
for y in 0..h {
let xf = x as f32 / w as f32;
let yf = y as f32 / h as f32;
values.push(perlin.octave_perlin(xf, yf, 2, 0.9));
}
}
values
};
assert_eq!(nb_blocks[0] * nb_blocks[1], values.len() as u32);
for x in 0..image_size[0] {
for y in 0..image_size[1] {
let mut pixel = imgbuf.get_pixel_mut(x, y);
let block_x = x / nb_blocks[0];
let block_y = y / nb_blocks[1];
assert!(block_x < nb_blocks[0]);
assert!(block_y < nb_blocks[1]);
//let perlin = perlin.octave_perlin(xf, yf, 2, 0.9);
let idx = (block_x + nb_blocks[0] * block_y) as usize;
let pixel_value = values[idx];
match pixel_value {
0.0..=0.15 => *pixel = image::Rgb([255u8, 0, 0]),
0.15..=0.35 => *pixel = image::Rgb([255u8, 133, 0]),
0.35..=0.55 => *pixel = image::Rgb([0, 255u8, 0]),
_ => *pixel = image::Rgb([0, 0, 255u8]),
}
}
}
// // Iterate over the coordinates and pixels of the image
// for (x, y, pixel) in imgbuf.enumerate_pixels_mut() {
// let xf = x as f32 / 2048.0;
// let yf = y as f32 / 2048.0;
//
// let block_x = x / nb_blocks[0];
// let block_y = x / nb_blocks[1];
//
// assert!(block_x < nb_blocks[0]);
// assert!(block_y < nb_blocks[1]);
//
// //let perlin = perlin.octave_perlin(xf, yf, 2, 0.9);
// let idx = (block_x + nb_blocks[0] * block_y) as usize;
// let pixel_value = values[idx];
//
// match pixel_value {
// 0.0..=0.15 => *pixel = image::Rgb([255u8, 0, 0]),
// 0.15..=0.35 => *pixel = image::Rgb([255u8, 133, 0]),
// 0.35..=0.55 => *pixel = image::Rgb([0, 255u8, 0]),
// _ => *pixel = image::Rgb([0, 0, 255u8]),
// }
//
// // max = max.max(perlin);
// // min = min.min(perlin);
// // let pixel_value = (perlin * 255.0) as u8;
// //*pixel = image::Rgb([pixel_value, pixel_value, pixel_value]);
// }
// Save the image as “fractal.png”, the format is deduced from the path
imgbuf.save("perlin.png").unwrap();
println!("{} to {}", min, max);
}
|
#![forbid(unsafe_code)]
use actix_web::{middleware, post, web, App, HttpRequest, HttpResponse, HttpServer};
use env_logger::Env;
use log::warn;
use serde::{Deserialize, Serialize};
use structopt::StructOpt;
use pop::notification::Notification;
#[derive(StructOpt)]
#[structopt(about, author)]
struct Opts {
/// Pushover API token
#[structopt(short, long, env = "PUSHOVER_TOKEN")]
token: String,
/// Pushover user token
#[structopt(short, long, env = "PUSHOVER_USER")]
user: String,
/// Authorization token to protect the proxy
#[structopt(short, long, env = "AUTHORIZATION")]
authorization: Option<String>,
/// host and port to bind
#[structopt(short, long, env = "BIND", default_value = "127.0.0.1:3000")]
bind: String,
}
#[derive(Default, Debug, Deserialize, Serialize)]
struct Message {
device: Option<String>,
title: Option<String>,
message: String,
html: Option<u8>,
timestamp: Option<u64>,
priority: Option<u8>,
url: Option<String>,
url_title: Option<String>,
sound: Option<String>,
image_url: Option<String>,
}
impl Message {
async fn to_notification(&self, token: &str, user: &str) -> anyhow::Result<Notification> {
let mut n = Notification::new(token, user, &self.message);
n.request.device = self.device.clone();
n.request.title = self.title.clone();
n.request.html = self.html;
n.request.timestamp = self.timestamp;
n.request.priority = self.priority;
n.request.url = self.url.clone();
n.request.url_title = self.url_title.clone();
n.request.sound = self.sound.clone();
if let Some(ref url) = self.image_url {
n.attach_url(url).await
} else {
Ok(n)
}
}
}
struct AppState {
authorization: Option<String>,
token: String,
user: String,
}
#[derive(Serialize)]
struct ErrorMessage {
message: String,
}
fn get_authorization(req: &HttpRequest) -> Option<&str> {
req.headers().get("authorization")?.to_str().ok()
}
#[post("/v1/messages")]
async fn messages(
req: HttpRequest,
data: web::Data<AppState>,
message: web::Json<Message>,
) -> HttpResponse {
if let Some(ref expected) = data.authorization {
if let Some(actual) = get_authorization(&req) {
if expected != actual {
// authorization and header are present but not equal
return HttpResponse::BadRequest().json(&ErrorMessage {
message: "unauthorized".to_string(),
});
} else {
// authorization and header are present and equal
}
} else {
// authorization is present but header is absent
return HttpResponse::BadRequest().json(&ErrorMessage {
message: "unauthorized".to_string(),
});
}
} else {
// authorization is absent
}
let notification = match message.to_notification(&data.token, &data.user).await {
Ok(n) => n,
Err(e) => return HttpResponse::BadRequest().body(format!("{:?}", e)),
};
let response = match notification.send().await {
Ok(r) => r,
Err(e) => return HttpResponse::BadRequest().body(format!("{:?}", e)),
};
if 1 == response.status {
HttpResponse::Ok().json(&response)
} else {
HttpResponse::BadRequest().json(&response)
}
}
#[actix_web::main]
async fn main() -> anyhow::Result<()> {
env_logger::Builder::from_env(Env::default().default_filter_or("info")).init();
let opts: Opts = Opts::from_args();
if opts.authorization.is_none() {
warn!("no authorization set, server is vulnerable");
}
let data = web::Data::new(AppState {
authorization: opts.authorization,
token: opts.token,
user: opts.user,
});
HttpServer::new(move || {
App::new()
.app_data(data.clone())
.wrap(middleware::Logger::default())
.service(messages)
})
.bind(&opts.bind)?
.run()
.await?;
Ok(())
}
|
use super::interface::DisplayInterface;
const REMAP_BASE: u8 = 0b00100100;
pub enum Command {
/// Column address
Column(u8,u8),
/// Row address
Row(u8,u8),
/// CommandLock
CommandLock(u8),
/// DisplayOn
DisplayOn(bool),
/// WriteRam
WriteRam,
/// ClockDiv
ClockDiv(u8),
/// MuxRatio
MuxRatio(u8),
/// SetRemap - horizontal or vertical increment, SegmentRemap, Reverse scan direction
SetRemap(bool, bool, bool),
/// Display Start Row
StartLine(u8),
/// DisplayOffset
DisplayOffset(u8),
/// SetGpio
SetGpio(u8),
/// FunctionSelect
FunctionSelect(u8),
/// PreCharge
PreCharge(u8),
/// Vcomh
Vcomh(u8),
/// NormalDisplayOn
Invert(bool),
/// Contrast
Contrast(u8),
/// ContrastMaster
ContrastCurrent(u8),
/// SetVsl
SetVsl,
/// SetPrecharge
PreCharge2(u8),
// PhaseLength(u8)
}
impl Command {
/// Send command to SSD1351
pub fn send<DI>(self, iface: &mut DI) -> Result<(), ()>
where
DI: DisplayInterface,
{
// Transform command into a fixed size array of 7 u8 and the real length for sending
// TODO can we replace the use if the static buffers?
let (command, data, len) = match self {
Command::CommandLock(val) => (0xFD, [val, 0,0,0,0,0], 1),
Command::DisplayOn(val) => ( if val { 0xAF } else { 0xAE }, [0,0,0,0,0,0], 0),
Command::ClockDiv(val) => (0xB3, [val as u8, 0,0,0,0,0], 1),
Command::MuxRatio(val) => (0xCA, [val as u8, 0,0,0,0,0], 1),
Command::SetRemap(incr, remap, scan) => (0xA0, [ REMAP_BASE | (incr as u8) << 0 | (remap as u8) << 1 | (scan as u8) << 4, 0,0,0,0,0], 1),
Command::Column(start, end) => (0x15, [start as u8, end as u8,0,0,0,0], 2),
Command::Row(start, end) => (0x75, [start as u8, end as u8,0,0,0,0], 2),
Command::StartLine(val) => (0xA1, [val as u8,0,0,0,0,0], 1),
Command::DisplayOffset(val) => (0xA2, [val as u8,0,0,0,0,0], 1),
Command::SetGpio(val) => (0xB5, [val as u8,0,0,0,0,0], 1),
Command::FunctionSelect(val) => (0xAB, [val as u8,0,0,0,0,0], 1),
Command::PreCharge(val) => (0xB1, [val as u8,0,0,0,0,0], 1),
Command::Vcomh(val) => (0xBE, [val as u8,0,0,0,0,0], 1),
Command::Invert(val) => (if val { 0xA7 } else { 0xA6 }, [0,0,0,0,0,0], 0),
Command::Contrast(val) => (0xC1, [0xC8, val as u8, 0xC8,0,0,0], 3),
Command::ContrastCurrent(val) => (0xC7, [val as u8,0,0,0,0,0], 1),
Command::SetVsl => (0xB4, [0xA0,0xB5,0x55, 0,0,0], 3),
Command::PreCharge2(val) => (0xB6, [val as u8, 0,0,0,0,0], 1),
Command::WriteRam => (0x5C, [0,0,0,0,0,0], 0),
};
// Send command over the interface
iface.send_command(command)?;
if len > 0 {
iface.send_data(&data[0..len])?;
}
Ok(())
}
}
// Transform command into a fixed size array of 7 u8 and the real length for sending
// let (data, len) = match self {
// Command::Contrast(val) => ([0x81, val, 0, 0, 0, 0, 0], 2),
// Command::AllOn(on) => ([0xA4 | (on as u8), 0, 0, 0, 0, 0, 0], 1),
// Command::Invert(inv) => ([0xA6 | (inv as u8), 0, 0, 0, 0, 0, 0], 1),
// Command::DisplayOn(on) => ([0xAE | (on as u8), 0, 0, 0, 0, 0, 0], 1),
// Command::HScrollSetup(dir, start, end, rate) => (
// [
// 0x26 | (dir as u8),
// 0,
// start as u8,
// rate as u8,
// end as u8,
// 0,
// 0xFF,
// ],
// 7,
// ),
// Command::VHScrollSetup(dir, start, end, rate, offset) => (
// [
// 0x28 | (dir as u8),
// 0,
// start as u8,
// rate as u8,
// end as u8,
// offset,
// 0,
// ],
// 6,
// ),
// Command::EnableScroll(en) => ([0x2E | (en as u8), 0, 0, 0, 0, 0, 0], 1),
// Command::VScrollArea(above, lines) => ([0xA3, above, lines, 0, 0, 0, 0], 3),
// Command::LowerColStart(addr) => ([0xF & addr, 0, 0, 0, 0, 0, 0], 1),
// Command::UpperColStart(addr) => ([0x1F & addr, 0, 0, 0, 0, 0, 0], 1),
// Command::AddressMode(mode) => ([0x20, mode as u8, 0, 0, 0, 0, 0], 2),
// Command::ColumnAddress(start, end) => ([0x21, start, end, 0, 0, 0, 0], 3),
// Command::PageAddress(start, end) => ([0x22, start as u8, end as u8, 0, 0, 0, 0], 3),
// Command::PageStart(page) => ([0xB0 | (page as u8), 0, 0, 0, 0, 0, 0], 1),
// Command::StartLine(line) => ([0x40 | (0x3F & line), 0, 0, 0, 0, 0, 0], 1),
// Command::SegmentRemap(remap) => ([0xA0 | (remap as u8), 0, 0, 0, 0, 0, 0], 1),
// Command::Multiplex(ratio) => ([0xA8, ratio, 0, 0, 0, 0, 0], 2),
// Command::ReverseComDir(rev) => ([0xC0 | ((rev as u8) << 3), 0, 0, 0, 0, 0, 0], 1),
// Command::DisplayOffset(offset) => ([0xD3, offset, 0, 0, 0, 0, 0], 2),
// Command::ComPinConfig(alt, lr) => (
// [
// 0xDA,
// 0x2 | ((alt as u8) << 4) | ((lr as u8) << 5),
// 0,
// 0,
// 0,
// 0,
// 0,
// ],
// 2,
// ),
// Command::DisplayClockDiv(fosc, div) => {
// ([0xD5, ((0xF & fosc) << 4) | (0xF & div), 0, 0, 0, 0, 0], 2)
// }
// Command::PreChargePeriod(phase1, phase2) => (
// [0xD9, ((0xF & phase2) << 4) | (0xF & phase1), 0, 0, 0, 0, 0],
// 2,
// ),
// Command::VcomhDeselect(level) => ([0xDB, (level as u8) << 4, 0, 0, 0, 0, 0], 2),
// Command::Noop => ([0xE3, 0, 0, 0, 0, 0, 0], 1),
// Command::ChargePump(en) => ([0x8D, 0x10 | ((en as u8) << 2), 0, 0, 0, 0, 0], 2),
// }; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.