text stringlengths 8 4.13M |
|---|
// unihernandez22
// https://atcoder.jp/contests/abc153/tasks/abc153_a
// math
use std::io::stdin;
fn main() {
let mut s = String::new();
stdin().read_line(&mut s).unwrap();
let words: Vec<i64> = s
.split_whitespace()
.map(|x| x.parse().unwrap())
.collect();
let h = words[0];
let a = words[1];
println!("{}", (h + a-1) / a);
}
|
#![allow(dead_code, unused)]
#![feature(arc_unwrap_or_clone)]
mod bgp_type;
pub mod config;
mod connection;
mod error;
mod event;
mod event_queue;
mod packets;
mod path_attribute;
pub mod peer;
pub mod routing;
mod state; |
fn string_compression(s: &str) -> String {
//
let mut a = 0;
let mut s1 = String::new();
let mut prev = s.chars().next().unwrap();
for c in s.chars() {
//
if c == prev {
a += 1;
} else {
s1.push_str(&*format!("{}{}", prev, a));
a = 1;
}
prev = c;
}
s1.push_str(&*format!("{}{}", prev, a));
s1
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_1() {
assert_eq!(string_compression("oooouui"), "o4u2i1");
}
#[test]
fn test_2() {
assert_eq!(string_compression("aaaaaaabbbbcccc"), "a7b4c4");
}
}
|
use std::io;
use std::error::Error;
//
fn main() -> Result<(), Box<dyn Error>> {
//Option<T>
let result = Some(5); // some method value
let fail = None;
let result = do_something(result);
println!("{}", result.unwrap_or_else(|| 666));
println!("{}", fail.unwrap_or_else(|| 666));
// fail.unwrap(); // Only catch is unwrap
// Result <T, E>
// Match
let result = match do_something_else() {
Ok(v) => Ok(v),
Err(e) => Err(e)
};
// but this can be shorthanded to
let result = do_something_else()?;
println!("{:?}", result);
Ok(())
}
fn do_something(val: Option<i32>) -> Option<i32> {
match val {
Some(i) => Some(i * i),
None => None
}
}
fn do_something_else() -> Result<i32, io::Error> {
return Result::Err(io::Error::from(io::ErrorKind::ConnectionAborted))
}
|
use http_muncher::ParserHandler;
use std::mem;
use std::str;
use std::collections::HashMap;
pub struct Request {
pub method: Option<String>,
pub path: Option<String>,
pub headers: HashMap<String, String>,
pub body: Option<String>,
last_header_field: Option<String>
}
impl Request {
pub fn new() -> Request {
Request {
method: None,
path: None,
headers: HashMap::new(),
body: None,
last_header_field: None
}
}
pub fn user_agent(&self) -> Option<&String> {
(&self.headers).get("user-agent")
}
pub fn set_header(&mut self, name: &str, value: &str) {
self.headers.insert(name.to_string(), value.to_string());
}
}
impl ParserHandler for Request {
fn on_url(&mut self, url: &[u8]) -> bool {
let url = str::from_utf8(url).unwrap();
self.path = Some(url.to_string());
true
}
fn on_header_field(&mut self, name: &[u8]) -> bool {
let header_field = str::from_utf8(name).unwrap();
self.last_header_field = Some(header_field.to_string().to_lowercase());
true
}
fn on_header_value(&mut self, name: &[u8]) -> bool {
// Assume ownership of self.last_header_field while resetting the field.
match mem::replace(&mut self.last_header_field, None) {
Some(header_field) => {
let header_value = str::from_utf8(name).unwrap();
self.headers.insert(header_field, header_value.to_string());
true
},
None => panic!("No matching header field.")
}
}
fn on_headers_complete(&mut self) -> bool {
true
}
fn on_chunk_header(&mut self) -> bool {
true
}
fn on_chunk_complete(&mut self) -> bool {
true
}
fn on_body(&mut self, part: &[u8]) -> bool {
let body = str::from_utf8(part).unwrap();
self.body = Some(body.to_string());
true
}
fn on_message_begin(&mut self) -> bool {
true
}
fn on_message_complete(&mut self) -> bool {
true
}
}
|
use byteorder::{BigEndian, LittleEndian};
use crate::{
Endianness,
errors::*,
pcap::Packet,
pcap::PcapHeader,
peek_reader::PeekReader
};
use std::io::Read;
/// Wraps another reader and uses it to read a Pcap formated stream.
///
/// It implements the Iterator trait in order to read one packet at a time
///
/// # Examples
///
/// ```rust,no_run
/// use std::fs::File;
/// use pcap_file::pcap::PcapReader;
///
/// let file_in = File::open("test.pcap").expect("Error opening file");
/// let pcap_reader = PcapReader::new(file_in).unwrap();
///
/// // Read test.pcap
/// for pcap in pcap_reader {
///
/// //Check if there is no error
/// let pcap = pcap.unwrap();
///
/// //Do something
/// }
/// ```
#[derive(Debug)]
pub struct PcapReader<T: Read> {
pub header: PcapHeader,
reader: PeekReader<T>
}
impl <T:Read> PcapReader<T>{
/// Create a new PcapReader from an existing reader.
/// This function read the global pcap header of the file to verify its integrity.
///
/// The underlying reader must point to a valid pcap file/stream.
///
/// # Errors
/// Return an error if the data stream is not in a valid pcap file format.
/// Or if the underlying data are not readable.
///
/// # Examples
/// ```rust,no_run
/// use std::fs::File;
/// use pcap_file::pcap::PcapReader;
///
/// let file_in = File::open("test.pcap").expect("Error opening file");
/// let pcap_reader = PcapReader::new(file_in).unwrap();
/// ```
pub fn new(mut reader:T) -> ResultParsing<PcapReader<T>> {
Ok(
PcapReader {
header : PcapHeader::from_reader(&mut reader)?,
reader : PeekReader::new(reader)
}
)
}
/// Consumes the `PcapReader`, returning the wrapped reader.
pub fn into_reader(self) -> T{
self.reader.inner
}
/// Gets a reference to the underlying reader.
///
/// It is not advised to directly read from the underlying reader.
pub fn get_ref(&self) -> &T{
&self.reader.inner
}
/// Gets a mutable reference to the underlying reader.
///
/// It is not advised to directly read from the underlying reader.
pub fn get_mut(&mut self) -> &mut T{
&mut self.reader.inner
}
}
impl <T:Read> Iterator for PcapReader<T> {
type Item = ResultParsing<Packet<'static>>;
fn next(&mut self) -> Option<ResultParsing<Packet<'static>>> {
match self.reader.is_empty() {
Ok(is_empty) if is_empty => {
return None;
},
Err(err) => return Some(Err(err.into())),
_ => {}
}
let ts_resolution = self.header.ts_resolution();
Some(
match self.header.endianness() {
Endianness::Big => Packet::from_reader::<_, BigEndian>(&mut self.reader, ts_resolution),
Endianness::Little => Packet::from_reader::<_, LittleEndian>(&mut self.reader, ts_resolution)
}
)
}
}
|
// This file is part of Substrate.
// Copyright (C) 2019-2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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.
mod parse;
use frame_support_procedural_tools::syn_ext as ext;
use frame_support_procedural_tools::{generate_crate_access, generate_hidden_includes};
use parse::{ModuleDeclaration, ModulePart, RuntimeDefinition, WhereSection};
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use std::collections::HashMap;
use syn::{Ident, Result, TypePath};
/// The fixed name of the system module.
const SYSTEM_MODULE_NAME: &str = "System";
/// The complete definition of a module with the resulting fixed index.
#[derive(Debug, Clone)]
pub struct Module {
pub name: Ident,
pub index: u8,
pub module: Ident,
pub instance: Option<Ident>,
pub module_parts: Vec<ModulePart>,
}
impl Module {
/// Get resolved module parts
fn module_parts(&self) -> &[ModulePart] {
&self.module_parts
}
/// Find matching parts
fn find_part(&self, name: &str) -> Option<&ModulePart> {
self.module_parts.iter().find(|part| part.name() == name)
}
/// Return whether module contains part
fn exists_part(&self, name: &str) -> bool {
self.find_part(name).is_some()
}
}
/// Convert from the parsed module to their final information.
/// Assign index to each modules using same rules as rust for fieldless enum.
/// I.e. implicit are assigned number incrementedly from last explicit or 0.
fn complete_modules(decl: impl Iterator<Item = ModuleDeclaration>) -> syn::Result<Vec<Module>> {
let mut indices = HashMap::new();
let mut last_index: Option<u8> = None;
decl.map(|module| {
let final_index = match module.index {
Some(i) => i,
None => last_index.map_or(Some(0), |i| i.checked_add(1)).ok_or_else(|| {
let msg = "Module index doesn't fit into u8, index is 256";
syn::Error::new(module.name.span(), msg)
})?,
};
last_index = Some(final_index);
if let Some(used_module) = indices.insert(final_index, module.name.clone()) {
let msg = format!(
"Module indices are conflicting: Both modules {} and {} are at index {}",
used_module, module.name, final_index,
);
let mut err = syn::Error::new(used_module.span(), &msg);
err.combine(syn::Error::new(module.name.span(), msg));
return Err(err)
}
Ok(Module {
name: module.name,
index: final_index,
module: module.module,
instance: module.instance,
module_parts: module.module_parts,
})
})
.collect()
}
pub fn construct_runtime(input: TokenStream) -> TokenStream {
let definition = syn::parse_macro_input!(input as RuntimeDefinition);
construct_runtime_parsed(definition).unwrap_or_else(|e| e.to_compile_error()).into()
}
fn construct_runtime_parsed(definition: RuntimeDefinition) -> Result<TokenStream2> {
let RuntimeDefinition {
name,
where_section: WhereSection { block, node_block, unchecked_extrinsic, .. },
modules:
ext::Braces { content: ext::Punctuated { inner: modules, .. }, token: modules_token },
..
} = definition;
let modules = complete_modules(modules.into_iter())?;
let system_module =
modules.iter().find(|decl| decl.name == SYSTEM_MODULE_NAME).ok_or_else(|| {
syn::Error::new(
modules_token.span,
"`System` module declaration is missing. \
Please add this line: `System: frame_system::{Module, Call, Storage, Config, Event<T>},`",
)
})?;
let hidden_crate_name = "construct_runtime";
let scrate = generate_crate_access(&hidden_crate_name, "frame-support");
let scrate_decl = generate_hidden_includes(&hidden_crate_name, "frame-support");
let all_but_system_modules = modules.iter().filter(|module| module.name != SYSTEM_MODULE_NAME);
let outer_event = decl_outer_event(&name, modules.iter(), &scrate)?;
let outer_origin = decl_outer_origin(&name, all_but_system_modules, &system_module, &scrate)?;
let all_modules = decl_all_modules(&name, modules.iter());
let module_to_index = decl_pallet_runtime_setup(&modules, &scrate);
let dispatch = decl_outer_dispatch(&name, modules.iter(), &scrate);
let metadata = decl_runtime_metadata(&name, modules.iter(), &scrate, &unchecked_extrinsic);
let outer_config = decl_outer_config(&name, modules.iter(), &scrate);
let inherent = decl_outer_inherent(&block, &unchecked_extrinsic, modules.iter(), &scrate);
let validate_unsigned = decl_validate_unsigned(&name, modules.iter(), &scrate);
let integrity_test = decl_integrity_test(&scrate);
let res = quote!(
#scrate_decl
// Prevent UncheckedExtrinsic to print unused warning.
const _: () = {
#[allow(unused)]
type __hidden_use_of_unchecked_extrinsic = #unchecked_extrinsic;
};
#[derive(Clone, Copy, PartialEq, Eq, #scrate::sp_runtime::RuntimeDebug)]
pub struct #name;
impl #scrate::sp_runtime::traits::GetNodeBlockType for #name {
type NodeBlock = #node_block;
}
impl #scrate::sp_runtime::traits::GetRuntimeBlockType for #name {
type RuntimeBlock = #block;
}
#outer_event
#outer_origin
#all_modules
#module_to_index
#dispatch
#metadata
#outer_config
#inherent
#validate_unsigned
#integrity_test
);
Ok(res.into())
}
fn decl_validate_unsigned<'a>(
runtime: &'a Ident,
module_declarations: impl Iterator<Item = &'a Module>,
scrate: &'a TokenStream2,
) -> TokenStream2 {
let modules_tokens = module_declarations
.filter(|module_declaration| module_declaration.exists_part("ValidateUnsigned"))
.map(|module_declaration| &module_declaration.name);
quote!(
#scrate::impl_outer_validate_unsigned!(
impl ValidateUnsigned for #runtime {
#( #modules_tokens )*
}
);
)
}
fn decl_outer_inherent<'a>(
block: &'a syn::TypePath,
unchecked_extrinsic: &'a syn::TypePath,
module_declarations: impl Iterator<Item = &'a Module>,
scrate: &'a TokenStream2,
) -> TokenStream2 {
let modules_tokens = module_declarations.filter_map(|module_declaration| {
let maybe_config_part = module_declaration.find_part("Inherent");
maybe_config_part.map(|_| {
let name = &module_declaration.name;
quote!(#name,)
})
});
quote!(
#scrate::impl_outer_inherent!(
impl Inherents where
Block = #block,
UncheckedExtrinsic = #unchecked_extrinsic
{
#(#modules_tokens)*
}
);
)
}
fn decl_outer_config<'a>(
runtime: &'a Ident,
module_declarations: impl Iterator<Item = &'a Module>,
scrate: &'a TokenStream2,
) -> TokenStream2 {
let modules_tokens = module_declarations
.filter_map(|module_declaration| {
module_declaration.find_part("Config").map(|part| {
let transformed_generics: Vec<_> =
part.generics.params.iter().map(|param| quote!(<#param>)).collect();
(module_declaration, transformed_generics)
})
})
.map(|(module_declaration, generics)| {
let module = &module_declaration.module;
let name = Ident::new(
&format!("{}Config", module_declaration.name),
module_declaration.name.span(),
);
let instance = module_declaration.instance.as_ref().into_iter();
quote!(
#name =>
#module #(#instance)* #(#generics)*,
)
});
quote!(
#scrate::sp_runtime::impl_outer_config! {
pub struct GenesisConfig for #runtime {
#(#modules_tokens)*
}
}
)
}
fn decl_runtime_metadata<'a>(
runtime: &'a Ident,
module_declarations: impl Iterator<Item = &'a Module>,
scrate: &'a TokenStream2,
extrinsic: &TypePath,
) -> TokenStream2 {
let modules_tokens = module_declarations
.filter_map(|module_declaration| {
module_declaration.find_part("Module").map(|_| {
let filtered_names: Vec<_> = module_declaration
.module_parts()
.into_iter()
.filter(|part| part.name() != "Module")
.map(|part| part.ident())
.collect();
(module_declaration, filtered_names)
})
})
.map(|(module_declaration, filtered_names)| {
let module = &module_declaration.module;
let name = &module_declaration.name;
let instance =
module_declaration.instance.as_ref().map(|name| quote!(<#name>)).into_iter();
let index = module_declaration.index;
quote!(
#module::Module #(#instance)* as #name { index #index } with #(#filtered_names)*,
)
});
quote!(
#scrate::impl_runtime_metadata!{
for #runtime with modules where Extrinsic = #extrinsic
#(#modules_tokens)*
}
)
}
fn decl_outer_dispatch<'a>(
runtime: &'a Ident,
module_declarations: impl Iterator<Item = &'a Module>,
scrate: &'a TokenStream2,
) -> TokenStream2 {
let modules_tokens = module_declarations
.filter(|module_declaration| module_declaration.exists_part("Call"))
.map(|module_declaration| {
let module = &module_declaration.module;
let name = &module_declaration.name;
let index = module_declaration.index.to_string();
quote!(#[codec(index = #index)] #module::#name)
});
quote!(
#scrate::impl_outer_dispatch! {
pub enum Call for #runtime where origin: Origin {
#(#modules_tokens,)*
}
}
)
}
fn decl_outer_origin<'a>(
runtime_name: &'a Ident,
modules_except_system: impl Iterator<Item = &'a Module>,
system_module: &'a Module,
scrate: &'a TokenStream2,
) -> syn::Result<TokenStream2> {
let mut modules_tokens = TokenStream2::new();
for module_declaration in modules_except_system {
match module_declaration.find_part("Origin") {
Some(module_entry) => {
let module = &module_declaration.module;
let instance = module_declaration.instance.as_ref();
let generics = &module_entry.generics;
if instance.is_some() && generics.params.len() == 0 {
let msg = format!(
"Instantiable module with no generic `Origin` cannot \
be constructed: module `{}` must have generic `Origin`",
module_declaration.name
);
return Err(syn::Error::new(module_declaration.name.span(), msg))
}
let index = module_declaration.index.to_string();
let tokens = quote!(#[codec(index = #index)] #module #instance #generics,);
modules_tokens.extend(tokens);
},
None => {},
}
}
let system_name = &system_module.module;
let system_index = system_module.index.to_string();
Ok(quote!(
#scrate::impl_outer_origin! {
pub enum Origin for #runtime_name where
system = #system_name,
system_index = #system_index
{
#modules_tokens
}
}
))
}
fn decl_outer_event<'a>(
runtime_name: &'a Ident,
module_declarations: impl Iterator<Item = &'a Module>,
scrate: &'a TokenStream2,
) -> syn::Result<TokenStream2> {
let mut modules_tokens = TokenStream2::new();
for module_declaration in module_declarations {
match module_declaration.find_part("Event") {
Some(module_entry) => {
let module = &module_declaration.module;
let instance = module_declaration.instance.as_ref();
let generics = &module_entry.generics;
if instance.is_some() && generics.params.len() == 0 {
let msg = format!(
"Instantiable module with no generic `Event` cannot \
be constructed: module `{}` must have generic `Event`",
module_declaration.name,
);
return Err(syn::Error::new(module_declaration.name.span(), msg))
}
let index = module_declaration.index.to_string();
let tokens = quote!(#[codec(index = #index)] #module #instance #generics,);
modules_tokens.extend(tokens);
},
None => {},
}
}
Ok(quote!(
#scrate::impl_outer_event! {
pub enum Event for #runtime_name {
#modules_tokens
}
}
))
}
fn decl_all_modules<'a>(
runtime: &'a Ident,
module_declarations: impl Iterator<Item = &'a Module>,
) -> TokenStream2 {
let mut types = TokenStream2::new();
let mut names = Vec::new();
for module_declaration in module_declarations {
let type_name = &module_declaration.name;
let module = &module_declaration.module;
let mut generics = vec![quote!(#runtime)];
generics.extend(module_declaration.instance.iter().map(|name| quote!(#module::#name)));
let type_decl = quote!(
pub type #type_name = #module::Module <#(#generics),*>;
);
types.extend(type_decl);
names.push(&module_declaration.name);
}
// Make nested tuple structure like (((Babe, Consensus), Grandpa), ...)
// But ignore the system module.
let all_modules = names
.iter()
.filter(|n| **n != SYSTEM_MODULE_NAME)
.fold(TokenStream2::default(), |combined, name| quote!((#name, #combined)));
quote!(
#types
type AllModules = ( #all_modules );
)
}
fn decl_pallet_runtime_setup(
module_declarations: &[Module],
scrate: &TokenStream2,
) -> TokenStream2 {
let names = module_declarations.iter().map(|d| &d.name);
let names2 = module_declarations.iter().map(|d| &d.name);
let name_strings = module_declarations.iter().map(|d| d.name.to_string());
let indices = module_declarations.iter().map(|module| module.index as usize);
quote!(
/// Provides an implementation of `PalletInfo` to provide information
/// about the pallet setup in the runtime.
pub struct PalletInfo;
impl #scrate::traits::PalletInfo for PalletInfo {
fn index<P: 'static>() -> Option<usize> {
let type_id = #scrate::sp_std::any::TypeId::of::<P>();
#(
if type_id == #scrate::sp_std::any::TypeId::of::<#names>() {
return Some(#indices)
}
)*
None
}
fn name<P: 'static>() -> Option<&'static str> {
let type_id = #scrate::sp_std::any::TypeId::of::<P>();
#(
if type_id == #scrate::sp_std::any::TypeId::of::<#names2>() {
return Some(#name_strings)
}
)*
None
}
}
)
}
fn decl_integrity_test(scrate: &TokenStream2) -> TokenStream2 {
quote!(
#[cfg(test)]
mod __construct_runtime_integrity_test {
use super::*;
#[test]
pub fn runtime_integrity_tests() {
<AllModules as #scrate::traits::IntegrityTest>::integrity_test();
}
}
)
}
|
use anyhow::{anyhow, bail, Result};
use serde::de::{self, DeserializeOwned, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::convert::TryInto;
use std::hash::{Hash, Hasher};
use std::{fs, fmt};
use std::io::{Seek, SeekFrom, Write};
use std::marker::PhantomData;
pub struct BinaryConfig<T, const SIZE: usize>([u8; SIZE], PhantomData<T>);
pub trait BinaryLocator {
const SECTION: &'static str;
}
impl<T, const SIZE: usize> BinaryConfig<T, SIZE>
where
T: Default + BinaryLocator + Serialize + DeserializeOwned,
{
pub const fn new() -> Self {
Self([0; SIZE], PhantomData)
}
pub fn decode(&self) -> T {
match bincode::deserialize(&self.0) {
Ok(s) => s,
Err(e) => {
println!("Deserialization Error. Ignoring. Bad Binary? {}", e);
Default::default()
}
}
}
#[cfg(target_os = "macos")]
pub fn write(&self, payload: &T) -> Result<()> {
use goblin::mach;
let mut data = read_binary()?;
let mach = mach::MachO::parse(&data, 0)?;
let segment = mach
.segments
.iter()
.find(|s| s.name().unwrap() == "__DATA")
.ok_or(anyhow!("Binary Segment not found"))?;
let (offset, size) = segment
.sections()?
.iter()
.find(|sec| sec.0.name().unwrap() == format!("__{}", T::SECTION))
.map(|x| (x.0.offset, x.0.size))
.ok_or(anyhow!("Binary Section not found"))?;
println!("Found Mach Binary segment/section.");
write_binary(&mut data, &payload, offset.into(), size)?;
Ok(())
}
#[cfg(target_os = "linux")]
pub fn write(&self, payload: &T) -> Result<()> {
use goblin::elf::Elf;
let mut data = read_binary()?;
let elf = Elf::parse(&data)?;
let section = elf
.section_headers
.iter()
.find(|sec| &elf.shdr_strtab[sec.sh_name] == ".bincrypt")
.ok_or(anyhow!("Binary Section not found"))?;
println!("Found ELF Section.");
write_binary(&mut data, &payload, section.sh_offset, section.sh_size)?;
Ok(())
}
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
pub fn write(&self, payload: &T) -> Result<()> {
panic!("Not Supported")
}
}
fn read_binary() -> Result<Vec<u8>> {
let args: Vec<String> = std::env::args().into_iter().collect();
let bytes = fs::read(&args[0])?;
Ok(bytes)
}
fn write_binary<T: Serialize>(
data: &mut Vec<u8>,
payload: &T,
offset: u64,
size: u64,
) -> Result<()> {
let payload = bincode::serialize(payload)?;
if payload.len() > size as usize {
bail!(
"Serialized size exceeds static capacity. {} > {}",
payload.len(),
size
);
}
println!(
"Writing config ({} bytes into {} byte segment)",
payload.len(),
size
);
let mut data = std::io::Cursor::new(data);
data.seek(SeekFrom::Start(offset as u64)).unwrap();
data.write(&payload)?;
let data = data.into_inner();
let args: Vec<String> = std::env::args().into_iter().collect();
let file = &args[0];
let tmpfile = format!("{}.new", file);
let perms = fs::metadata(&file)?.permissions();
fs::write(&tmpfile, &data)?;
fs::rename(&tmpfile, &file)?;
fs::set_permissions(&file, perms)?;
Ok(())
}
#[derive(Debug)]
pub struct BinHash(u64);
impl Default for BinHash {
fn default() -> Self {
BinHash(0)
}
}
// we just use two random u64 values
fn new_hasher() -> ahash::AHasher {
ahash::AHasher::new_with_keys(16465507875524386226, 2272181227724212771)
}
impl<T> From<&T> for BinHash
where
T: Hash,
{
fn from(val: &T) -> Self {
let mut hash = new_hasher();
val.hash(&mut hash);
BinHash(hash.finish())
}
}
impl Serialize for BinHash {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
if serializer.is_human_readable() {
let b64 = base64::encode(u64::to_be_bytes(self.0));
serializer.serialize_str(&b64)
}
else {
serializer.serialize_u64(self.0)
}
}
}
struct BinHashVisitor;
impl<'de> Visitor<'de> for BinHashVisitor {
type Value = BinHash;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a base64 string or u64")
}
fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(BinHash(value))
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
match base64::decode(value) {
Ok(v) => {
if v.len() != 4 {
return Err(de::Error::invalid_length(v.len(), &"expected base64 encoded value of 4 bytes"));
}
let v = u64::from_be_bytes(v[0..3].try_into().unwrap());
Ok(BinHash(v))
},
Err(e) => Err(de::Error::custom(e))
}
}
}
impl<'de> Deserialize<'de> for BinHash {
fn deserialize<D>(deserializer: D) -> Result<BinHash, D::Error>
where
D: Deserializer<'de>
{
deserializer.deserialize_u64(BinHashVisitor)
}
}
|
use assembly_fdb::mem::{Database, Tables};
use mapr::Mmap;
use std::{fs::File, path::PathBuf, time::Instant};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
/// Prints the names of all tables and their columns
struct Options {
/// The FDB file
file: PathBuf,
}
fn main() -> color_eyre::Result<()> {
color_eyre::install()?;
let opt = Options::from_args();
let start = Instant::now();
let file = File::open(&opt.file)?;
let mmap = unsafe { Mmap::map(&file)? };
let buffer: &[u8] = &mmap;
let db = Database::new(buffer);
let tables: Tables<'_> = db.tables()?;
println!("#Tables: {}", tables.len());
for table in tables.iter() {
let table = table?;
let table_name = table.name();
println!("{} ({})", table_name, table.bucket_count());
for column in table.column_iter() {
let name = column.name();
println!("- {}: {:?}", name, column.value_type());
}
}
let duration = start.elapsed();
println!(
"Finished in {}.{}s",
duration.as_secs(),
duration.subsec_millis()
);
Ok(())
}
|
mod cut_and_paste;
mod kv;
pub mod pkcs7;
|
use super::conn_pipe::*;
use super::*;
#[tokio::test]
async fn test_pipe() -> Result<()> {
let (c1, c2) = pipe();
let mut b1 = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let n = c1.send(&b1).await?;
assert_eq!(n, 10);
let mut b2 = vec![133; 100];
let n = c2.recv(&mut b2).await?;
assert_eq!(n, 10);
assert_eq!(&b2[..n], &b1[..]);
let n = c2.send(&b2[..10]).await?;
assert_eq!(n, 10);
let n = c2.send(&b2[..5]).await?;
assert_eq!(n, 5);
let n = c1.recv(&mut b1).await?;
assert_eq!(n, 10);
let n = c1.recv(&mut b1).await?;
assert_eq!(n, 5);
Ok(())
}
|
fn main() {
// let a: [f64; 4] = [32., 45., -10., 69.];
// for x in a.iter() {
// println!("{}", farenheit_to_celsius(*x));
// }
// for n in 0..10 {
// println!("{}", fibonacci(n));
// }
tweleve_days();
}
// fn farenheit_to_celsius(x: f64) -> f64 {
// (x - 32.) * (5. / 9.)
// }
// fn fibonacci(n: u32) -> u32 {
// let mut a = 0;
// let mut b = 1;
// for _ in 0..n {
// let old_a = a;
// let old_b = b;
// a = old_b;
// b = old_a + old_b;
// }
// a
// }
fn tweleve_days() {
const LINES: [&str; 11] = [
"12 drummers drumming",
"Eleven pipers piping",
"Ten lords a leaping",
"Nine ladies dancing",
"Eight maids a milking",
"Seven swans a swimming",
"Six geese a laying",
"Five gold rings, badam-pam-pam",
"Four calling birds",
"Three French hens",
"Two turtle doves",
];
const ORDINALS: [&str; 12] = [
"first",
"second",
"third",
"fourth",
"fifth",
"sixth",
"seventh",
"eighth",
"ninth",
"tenth",
"eleventh",
"twelfth"
];
println!("On the first day of Christmas");
println!("My true love gave to me");
println!("A partridge in a pear tree");
println!();
for verse_number in (1..12).rev() {
println!("On the {} day of Christmas", ORDINALS[12-verse_number]);
println!("My true love gave to me");
for line_number in verse_number-1..11 {
println!("{}", LINES[line_number]);
}
println!("And a partridge in a pear tree");
println!();
}
}
|
use std::cmp::Ordering;
fn main() {
let s = [10, 12, 13, 14, 18, 20, 25, 27, 30, 35, 40, 45, 47];
println!("{:?}", binary_search(&s, 18));
}
fn binary_search(s: &[i32], x: i32) -> Option<usize> {
location(s, x, 0, s.len())
}
fn location(s: &[i32], x: i32, low: usize, high: usize) -> Option<usize> {
if low > high {
return None;
}
let mid = (low + high) / 2;
match x.cmp(&s[mid]) {
Ordering::Equal => Some(mid),
Ordering::Less => location(s, x, low, mid - 1),
Ordering::Greater => location(s, x, mid + 1, high),
}
} |
#[macro_use]
pub mod macros;
pub mod error;
pub mod varint;
pub mod byte;
pub mod comparator;
pub mod slice;
|
use rand::prelude::*;
// Not too much revolutionary here in the definition of reference types
#[derive(Debug, PartialEq)] // deriveable traits
struct Building {
name: String,
number: u32,
owner: String,
location: String,
valdermort_controlled: bool
}
// you can seperate out your impl - Convention based on name
impl Building {
// normal method
pub fn get_name(&self) -> &String {
&self.name
}
// associated function
fn build_hogwarts() -> Building {
Building {
name: String::from("Howarts"),
number: random(),
owner: String::from("Dumbledor"),
location: String::from("UK?"),
valdermort_controlled: false
}
}
}
// Traits/Exisiting and Custom
pub trait Defend {
fn cast_protection_spell(&self);
}
impl Defend for Building {
fn cast_protection_spell(&self) {
println!("Salvio Hexia");
}
}
// Trait Bounds
pub fn trait_param(obj: impl Defend) {
obj.cast_protection_spell();
}
pub fn trait_generics<T: Defend>(obj: T, obj2: T) {
obj.cast_protection_spell();
obj2.cast_protection_spell();
}
fn main() {
let ministry = Building {
name: String::from("Ministry of Magic"),
number: 1,
owner: String::from("Cornelius Fudge"),
location: String::from("London"),
valdermort_controlled: true
};
// associated function
let hogwarts = Building::build_hogwarts();
// custom trait
hogwarts.cast_protection_spell();
// Derived traits
println!("{:?}", hogwarts);
assert_ne!(hogwarts, ministry);
// Pretty familiar loop/control constructs
let mut counter = if true { 0 } else { 1 };
loop {
counter +=1;
println!("{}", hogwarts.get_name());
if(counter == 5)
{
break;
}
}
while (counter <= 10){
println!("Harry Potter");
counter += 1;
}
for number in (1..4).rev() {
println!("{}!", number);
}
} |
mod initialize;
mod runtime;
use {
data::semantics::Semantics,
proc_macro2::{Span, TokenStream},
quote::{quote, quote_spanned},
};
impl Semantics {
pub fn runtime() -> TokenStream {
let header = Self::header();
let runtime_register_functions = Self::runtime_register_functions();
let runtime_render_functions = Self::runtime_render_functions();
let runtime_static_render_functions = Self::runtime_static_render_functions();
quote! {
#header
#runtime_register_functions
#runtime_render_functions
#runtime_static_render_functions
}
}
fn header() -> TokenStream {
quote! {
extern crate wasm_bindgen;
extern crate web_sys;
use {
std::{
cell::RefCell,
collections::HashMap,
},
self::wasm_bindgen::{
prelude::*,
JsCast,
JsValue,
},
self::web_sys::{
console,
Event,
HtmlElement,
Node,
},
};
#[derive(Clone, Hash, PartialEq, Eq)]
pub enum Property {
Css(&'static str),
Link,
Text,
Tooltip,
Image,
}
#[derive(Clone, Debug)]
pub enum Value {
Number(i32),
String(&'static str),
Variable(usize),
}
#[derive(Clone, Default)]
struct Group {
class_names: Vec<&'static str>,
selector: &'static str,
classes: Vec<Group>,
listeners: Vec<Group>,
elements: Vec<Group>,
properties: HashMap<Property, &'static str>,
variables: Vec<(usize, Value)>,
}
trait Std {
fn text(&mut self, value: &'static str);
fn css(&mut self, property: &'static str, value: &'static str);
}
impl Std for HtmlElement {
fn text(&mut self, value: &'static str) {
if let Some(element) = self
.child_nodes()
.item(0)
{
element.set_node_value(None);
}
self.prepend_with_str_1(value).unwrap();
}
fn css(&mut self, property: &'static str, value: &'static str) {
self.style().set_property(property, value).unwrap();
}
}
thread_local! {
static CLASSES: RefCell<HashMap<&'static str, Group>> = RefCell::new(HashMap::new());
}
}
}
pub fn wasm(&self, full: bool) -> TokenStream {
log::debug!("...Writing Wasm...");
let warnings = self.warnings.iter().map(|error| {
quote_spanned! {Span::call_site()=>
compile_error!(#error);
}
});
let errors = self.errors.iter().map(|error| {
quote_spanned! {Span::call_site()=>
compile_error!(#error);
}
});
let core = if !self.errors.is_empty() {
quote! {
#( #errors )*
}
} else if full {
self.full()
} else {
self.document()
};
quote! {
#( #warnings )*
#core
}
}
fn full(&self) -> TokenStream {
let header = Self::runtime();
let state = self.runtime_state();
let document = self.document();
quote! {
#header
#state
extern crate console_error_panic_hook;
#[wasm_bindgen(start)]
pub fn run() -> Result<(), JsValue> {
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
#document
Ok(())
}
}
}
}
|
#![cfg_attr(feature = "unstable", feature(test))]
// Launch program : cargo run --release < input/input.txt
// Launch benchmark : cargo +nightly bench --features "unstable"
/*
Benchmark results:
running 5 tests
test tests::test_part_1 ... ignored
test tests::test_part_2 ... ignored
test bench::bench_parse_input ... bench: 877,667 ns/iter (+/- 37,690)
test bench::bench_part_1 ... bench: 671,550 ns/iter (+/- 120,493)
test bench::bench_part_2 ... bench: 73,346,001 ns/iter (+/- 1,989,818)
*/
#[macro_use]
extern crate lazy_static;
extern crate regex;
use std::collections::HashMap;
use std::convert::TryFrom;
use std::error::Error;
use std::io::{self, Read, Write};
type Result<T> = ::std::result::Result<T, Box<dyn Error>>;
macro_rules! err {
($($tt:tt)*) => { return Err(Box::<dyn Error>::from(format!($($tt)*))) }
}
#[derive(Clone)]
enum Command {
Mask(Vec<char>),
Mem(usize, usize),
}
#[derive(Clone)]
struct System {
program: Vec<Command>,
current_mask: Vec<char>,
floating_bits: usize,
memory: HashMap<usize, usize>,
}
impl System {
fn execute_program(&mut self, decode_memory_address: bool) -> Result<()> {
for command in &self.program {
match command {
Command::Mask(mask) => {
self.current_mask = mask.to_vec();
self.floating_bits = self.current_mask.iter().filter(|&v| *v == 'X').count();
}
Command::Mem(address, value) => {
if decode_memory_address {
let masked_address = self
.current_mask
.iter()
.zip(format!("{:036b}", address).chars())
.map(|(&mask, address)| if mask == '0' { address } else { mask })
.collect::<Vec<char>>();
for i in 0..2_u64.pow(self.floating_bits as u32) {
let mut bits_to_replace =
format!("{:b}", i).chars().collect::<Vec<char>>();
let decoded_address = masked_address
.iter()
.rev()
.map(|&v| {
if v == 'X' {
match bits_to_replace.pop() {
Some(b) => b,
None => '0',
}
} else {
v
}
})
.rev()
.collect::<String>();
if let Ok(resulting_address) =
usize::from_str_radix(&decoded_address, 2)
{
self.memory.insert(resulting_address, *value);
} else {
err!(
"Could not parse binary address to usize : {:?}",
decoded_address
)
}
}
} else {
let masked_value = self
.current_mask
.iter()
.zip(format!("{:036b}", value).chars())
.map(|(&mask, value)| if mask == 'X' { value } else { mask })
.collect::<String>();
if let Ok(resulting_value) = usize::from_str_radix(&masked_value, 2) {
self.memory.insert(*address, resulting_value);
} else {
err!("Could not parse binary value to usize : {:?}", masked_value)
}
}
}
}
}
Ok(())
}
}
impl TryFrom<&str> for System {
type Error = Box<dyn Error>;
fn try_from(value: &str) -> Result<Self> {
use regex::Regex;
lazy_static! {
static ref DAY_14_PROGRAM_LINE_REGEX: Regex =
Regex::new(r"^(?P<command>mask|mem\[(?P<address>\d+)\]) = ((?P<mask>[X01]{36})|(?P<value>\d+))$")
.expect("Invalid DAY_14_PROGRAM_LINE_REGEX!");
}
let mut program: Vec<Command> = vec![];
for line in value.lines() {
if let Some(cap) = DAY_14_PROGRAM_LINE_REGEX.captures(line) {
match &cap["command"] {
"mask" => {
if let Some(mask) = cap.name("mask") {
program.push(Command::Mask(mask.as_str().chars().collect()));
} else {
err!("Invalid input mask : {}", line)
}
}
_ => {
if let Some(value) = cap.name("value") {
program.push(Command::Mem(
cap["address"].parse::<usize>()?,
value.as_str().parse::<usize>()?,
))
} else {
err!("Invalid input memory value : {}", line)
}
}
}
} else {
err!("Couldn't parse input : {}", line)
}
}
Ok(System {
program,
current_mask: vec!['X'; 36],
floating_bits: 36,
memory: HashMap::new(),
})
}
}
fn main() -> Result<()> {
let mut input = String::new();
io::stdin().read_to_string(&mut input)?;
let system = parse_input(&input)?;
writeln!(io::stdout(), "Part 1 : {}", part_1(system.clone())?)?;
writeln!(io::stdout(), "Part 2 : {}", part_2(system)?)?;
Ok(())
}
fn parse_input(input: &str) -> Result<System> {
System::try_from(input)
}
fn part_1(mut system: System) -> Result<usize> {
system.execute_program(false)?;
Ok(system.memory.iter().map(|(_, &v)| v).sum())
}
fn part_2(mut system: System) -> Result<usize> {
system.execute_program(true)?;
Ok(system.memory.iter().map(|(_, &v)| v).sum())
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs::File;
fn read_test_file() -> Result<String> {
let mut input = String::new();
File::open("input/test.txt")?.read_to_string(&mut input)?;
Ok(input)
}
fn read_test_file_2() -> Result<String> {
let mut input = String::new();
File::open("input/test2.txt")?.read_to_string(&mut input)?;
Ok(input)
}
#[test]
fn test_part_1() -> Result<()> {
let system = parse_input(&read_test_file()?)?;
assert_eq!(part_1(system)?, 165);
Ok(())
}
#[test]
fn test_part_2() -> Result<()> {
let system = parse_input(&read_test_file_2()?)?;
assert_eq!(part_2(system)?, 208);
Ok(())
}
}
#[cfg(all(feature = "unstable", test))]
mod bench {
extern crate test;
use super::*;
use std::fs::File;
use test::Bencher;
fn read_input_file() -> Result<String> {
let mut input = String::new();
File::open("input/input.txt")?.read_to_string(&mut input)?;
Ok(input)
}
#[bench]
fn bench_parse_input(b: &mut Bencher) -> Result<()> {
let input = read_input_file()?;
b.iter(|| test::black_box(parse_input(&input)));
Ok(())
}
#[bench]
fn bench_part_1(b: &mut Bencher) -> Result<()> {
let system = parse_input(&read_input_file()?)?;
b.iter(|| test::black_box(part_1(system.clone())));
Ok(())
}
#[bench]
fn bench_part_2(b: &mut Bencher) -> Result<()> {
let system = parse_input(&read_input_file()?)?;
b.iter(|| test::black_box(part_2(system.clone())));
Ok(())
}
}
|
use crate::common::{delay_for, factories::prelude::*};
use common::futures_util::stream::StreamExt;
use common::log::Level;
use common::rsip::{self, prelude::*};
use models::transport::TransportMsg;
use sip_server::transport::processor::Processor as TransportProcessor;
use std::any::Any;
use std::convert::{TryFrom, TryInto};
use std::net::{IpAddr, Ipv4Addr};
#[tokio::test]
async fn incoming_response_asserts_with_wrong_sent_by() -> Result<(), sip_server::Error> {
use rsip::Uri;
let processor = TransportProcessor::default();
let mut response: rsip::Response =
responses::response(Some(Uri::default()), Some(Uri::default().with_port(5090)));
let mut via_header = response.via_header_mut()?;
via_header.replace(
via_header
.typed()?
.with_uri(Uri::default().with_port(5070).into()),
);
let server_msg = models::server::UdpTuple {
bytes: response.into(),
peer: SocketAddrBuilder::localhost_with_port(5090).into(),
};
match processor
.process_incoming_message(server_msg.try_into()?)
.await
{
Err(sip_server::Error {
kind: sip_server::ErrorKind::Custom(error),
}) => assert!(error.contains("sent-by") && error.contains("different")),
res => panic!("unexpected result: {:?}", res),
}
Ok(())
}
#[tokio::test]
async fn incoming_response_asserts_with_correct_sent_by() -> Result<(), sip_server::Error> {
use rsip::Uri;
let processor = TransportProcessor::default();
let response: rsip::Response =
responses::response(Some(Uri::default()), Some(Uri::default().with_port(5090)));
let server_msg = models::server::UdpTuple {
bytes: response.into(),
peer: SocketAddrBuilder::localhost_with_port(5090).into(),
};
assert!(processor
.process_incoming_message(server_msg.try_into()?)
.await
.is_ok());
Ok(())
}
#[tokio::test]
async fn outgoing_transaction_request_applies_maddr() -> Result<(), sip_server::Error> {
use rsip::{param::Maddr, Param, Uri};
let processor = TransportProcessor::default();
let transport_msg = models::transport::TransportMsg {
peer: SocketAddrBuilder {
ip_addr: IpAddrBuilder {
multicast: true,
..Default::default()
}
.build(),
..Default::default()
}
.into(),
..Randomized::default()
};
let message = processor.process_outgoing_message(transport_msg.clone())?;
let request: rsip::Request = message.sip_message.try_into()?;
let typed_via_uri = &request.via_header()?.typed()?;
let maddr_param = typed_via_uri
.params
.iter()
.find(|s| matches!(s, Param::Maddr(_)))
.expect("no maddr found");
assert_eq!(
maddr_param,
&Param::Maddr(Maddr::new(transport_msg.peer.ip().to_string()))
);
Ok(())
}
#[tokio::test]
async fn outgoing_transaction_request_applies_ttl() -> Result<(), sip_server::Error> {
use rsip::{param::Ttl, Param, Uri};
let processor = TransportProcessor::default();
let transport_msg = TransportMsg {
peer: SocketAddrBuilder {
ip_addr: IpAddrBuilder {
version: IpVersion::V4,
..Default::default()
}
.build(),
..Default::default()
}
.into(),
..Randomized::default()
};
let message = processor.process_outgoing_message(transport_msg.clone())?;
let request: rsip::Request = message.sip_message.try_into()?;
let typed_via_header = &request.via_header()?.typed()?;
let maddr_param = typed_via_header
.params
.iter()
.find(|s| matches!(s, Param::Ttl(_)))
.expect("ttl param is missing");
assert_eq!(maddr_param, &Param::Ttl(Ttl::new("1")));
Ok(())
}
#[tokio::test]
async fn outgoing_transaction_request_applies_sent_by() -> Result<(), sip_server::Error> {
use rsip::Uri;
let processor = TransportProcessor::default();
let transport_msg = TransportMsg {
peer: SocketAddrBuilder {
ip_addr: IpAddrBuilder {
version: IpVersion::V4,
..Default::default()
}
.build(),
..Default::default()
}
.into(),
..Randomized::default()
};
let message = processor.process_outgoing_message(transport_msg.clone())?;
let request: rsip::Request = message.sip_message.try_into()?;
let typed_via_header = &request.via_header()?.typed()?;
assert_eq!(
typed_via_header.uri.host_with_port,
common::CONFIG.default_addr()
);
Ok(())
}
#[tokio::test]
async fn outgoing_core_request_applies_maddr() -> Result<(), sip_server::Error> {
use rsip::{param::Maddr, Param, Uri};
let processor = TransportProcessor::default();
let transport_msg = TransportMsg {
peer: SocketAddrBuilder {
ip_addr: IpAddrBuilder {
multicast: true,
..Default::default()
}
.build(),
..Default::default()
}
.into(),
..Randomized::default()
};
let message = processor.process_outgoing_message(transport_msg.clone())?;
let request: rsip::Request = message.sip_message.try_into()?;
let typed_via_header = &request.via_header()?.typed()?;
let maddr_param = typed_via_header
.params
.iter()
.find(|s| matches!(s, Param::Maddr(_)))
.expect("maddr param is missing when address is multicast");
assert_eq!(
maddr_param,
&Param::Maddr(Maddr::new(transport_msg.peer.ip().to_string()))
);
Ok(())
}
#[tokio::test]
async fn outgoing_core_request_applies_ttl() -> Result<(), sip_server::Error> {
use rsip::{param::Ttl, Param, Uri};
let processor = TransportProcessor::default();
let transport_msg = TransportMsg {
peer: SocketAddrBuilder {
ip_addr: IpAddrBuilder {
version: IpVersion::V4,
..Default::default()
}
.build(),
..Default::default()
}
.into(),
..Randomized::default()
};
let message = processor.process_outgoing_message(transport_msg.clone())?;
let request: rsip::Request = message.sip_message.try_into()?;
let typed_via_header = &request.via_header()?.typed()?;
let maddr_param = typed_via_header
.params
.iter()
.find(|s| matches!(s, Param::Ttl(_)))
.expect("ttl param is missing");
assert_eq!(maddr_param, &Param::Ttl(Ttl::new("1")));
Ok(())
}
#[tokio::test]
async fn outgoing_core_request_applies_sent_by() -> Result<(), sip_server::Error> {
use rsip::Uri;
let processor = TransportProcessor::default();
let transport_msg = TransportMsg {
peer: SocketAddrBuilder {
ip_addr: IpAddrBuilder {
version: IpVersion::V4,
..Default::default()
}
.build(),
..Default::default()
}
.into(),
..Randomized::default()
};
let message = processor.process_outgoing_message(transport_msg.clone())?;
let request: rsip::Request = message.sip_message.try_into()?;
let typed_via_header = &request.via_header()?.typed()?;
assert_eq!(
typed_via_header.uri.host_with_port,
common::CONFIG.default_addr()
);
Ok(())
}
|
///// chapter 3 "using functions and control structures"
///// program section:
//
fn increment_power(power: i32) -> i32 {
println!("my power is going to increase:");
if power < 100 { 999 } else { 0 }
}
fn main() {
///// function is called
//
let power = increment_power(1);
println!("my power level is now: {}", power);
}
///// output should be:
/*
*/// end of output
|
use std::fmt;
use crate::{
error::{cuda_error, CudaResult},
sys, Cuda,
};
/// A CUDA device or API version
#[derive(Clone, Copy, Debug)]
pub struct CudaVersion {
pub major: u32,
pub minor: u32,
}
impl From<u32> for CudaVersion {
fn from(version: u32) -> Self {
CudaVersion {
major: version as u32 / 1000,
minor: (version as u32 % 1000) / 10,
}
}
}
impl Into<(u32, u32)> for CudaVersion {
fn into(self) -> (u32, u32) {
(self.major, self.minor)
}
}
impl From<(u32, u32)> for CudaVersion {
fn from(other: (u32, u32)) -> Self {
CudaVersion {
major: other.0,
minor: other.1,
}
}
}
impl fmt::Display for CudaVersion {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}.{}", self.major, self.minor)
}
}
impl Cuda {
/// Gets the local driver version (not to be confused with device compute capability)
pub fn version() -> CudaResult<CudaVersion> {
let mut version = 0i32;
cuda_error(unsafe { sys::cuDriverGetVersion(&mut version as *mut i32) })?;
Ok((version as u32).into())
}
}
|
pub mod thick_2_ofn;
pub mod util;
pub mod ofn_typing;
pub mod ofn_labeling;
pub mod ldtab_2_ofn;
pub mod ofn_2_man;
pub mod ofn_2_ldtab;
pub mod ofn_2_rdfa;
pub mod ofn_2_thick;
pub mod owl;
|
#[derive(Debug)]
pub struct FitHeader {
pub size: u8,
pub protocol_version: u8,
pub profile_version: u16,
pub data_size: u32,
pub fit_str: String,
pub crc: u16
}
impl Default for FitHeader {
fn default() -> FitHeader {
return FitHeader{
fit_str: String::new(),
profile_version: 0,
protocol_version: 0,
data_size: 0,
crc: 0,
size: 0
}
}
}
|
#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use]
extern crate rocket;
mod web;
mod data;
mod demo;
mod leet_code;
fn main() {
//力扣
leet_code::main();
//测试demo
demo::main();
//init web service
web::main();
}
|
use proconio::input;
#[allow(unused_imports)]
use proconio::source::auto::AutoSource;
#[allow(unused_imports)]
use proconio::marker::{Chars, Bytes};
#[allow(unused_imports)]
use num::integer::{sqrt, gcd, lcm};
#[allow(unused_imports)]
use std::cmp::{max, min, Reverse};
fn main() {
// let source = AutoSource::from("5 1 5");
input!{
// from source,
n: usize,
x: usize,
y: usize
};
let mut dp = vec![vec![0usize; n+1];n+1];
for i in 1..n{
for j in i+1..=n{
dp[i][j] = j - i
}
}
for i in 1..n{
for j in i+1..=n{
dp[i][j] = min(dp[i][j], (x as isize - i as isize).abs() as usize + (y as isize - j as isize).abs() as usize + 1)
}
}
// println!("{:?}", dp);
let mut bucket = vec![0i64; n+1];
for i in 1..n{
for j in i+1..=n{
bucket[dp[i][j]] += 1;
}
}
for i in 1..n{
println!("{}", bucket[i]);
}
}
|
#![allow(dead_code)]
use std::io;
use std::error::Error;
use std::result::Result;
use std::iter::{Iterator, IntoIterator};
use std::collections::HashMap;
use std::collections::hash_map;
use std::vec::Vec;
use std::vec;
use std::cmp::{Eq, PartialEq};
use std::hash::{Hash, Hasher};
use std::convert::From;
use std::slice;
use std::fmt;
pub type Pixels = usize;
pub type FileName = String;
pub type FilePath = String;
#[derive(Clone, Eq, PartialEq, Hash, Debug)]
pub enum ResolutionUnits {
PixelsPerInch,
PixelsPerCentimeter,
}
impl fmt::Display for ResolutionUnits {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
ResolutionUnits::PixelsPerInch => "Pixels per inch".fmt(f),
ResolutionUnits::PixelsPerCentimeter => "Pixels per centimeter".fmt(f),
}
}
}
#[derive(Clone, Eq, PartialEq, Hash, Debug)]
pub enum Direction {
Horizontal,
Vertical,
}
impl fmt::Display for Direction {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Direction::Horizontal => "Horizontal".fmt(f),
Direction::Vertical => "Vertical".fmt(f),
}
}
}
#[derive(Clone, Eq, PartialEq, Hash, Debug)]
pub enum ImageFileFormat {
TIFF,
PNG,
JPEG,
UNKNOWN,
}
impl fmt::Display for ImageFileFormat {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
ImageFileFormat::TIFF => "TIFF".fmt(f),
ImageFileFormat::PNG => "PNG".fmt(f),
ImageFileFormat::JPEG => "JPEG".fmt(f),
ImageFileFormat::UNKNOWN => "UNKNOWN FORMAT".fmt(f),
}
}
}
#[derive(Clone, Eq, PartialEq, Hash, Debug)]
pub struct ImageDimensions {
x_pixels: Pixels,
y_pixels: Pixels,
}
impl ImageDimensions {
fn new(x: Pixels, y: Pixels) -> ImageDimensions {
ImageDimensions {
x_pixels: x,
y_pixels: y,
}
}
}
impl fmt::Display for ImageDimensions {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} x {} Pixels", self.x_pixels, self.y_pixels)
}
}
#[derive(Clone, Eq, PartialEq, Hash, Debug)]
pub struct ImageResolution {
amount: Pixels,
units: ResolutionUnits,
}
impl ImageResolution {
fn new(amount: usize, units: ResolutionUnits) -> ImageResolution {
ImageResolution {
amount: amount,
units: units,
}
}
}
impl fmt::Display for ImageResolution {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} {}", self.amount, self.units)
}
}
/// The most primitive page operations defined for working with
/// pdf files. The basic operations allow one to rescale pages, expand edges,
/// and adjust DPI for normalizing page dimensions.
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum PageOps {
NoOperation,
Identify(FileName, FilePath),
Rescale(Pixels, Direction),
ExpandLeftEdge(Pixels),
ExpandRightEdge(Pixels),
ExpandTopEdge(Pixels),
ExpandBottomEdge(Pixels),
TrimLeftEdge(Pixels),
TrimRightEdge(Pixels),
TrimTopEdge(Pixels),
TrimBottomEdge(Pixels),
SetResolution(ImageResolution),
}
pub trait ElementaryPageOperations {
fn identify(file_name: FileName, path: FilePath) -> Self;
fn rescale(amount: Pixels, dir: Direction) -> Self;
fn expand_left_edge(amount: Pixels) -> Self;
fn expand_right_edge(amount: Pixels) -> Self;
fn expand_top_edge(amount: Pixels) -> Self;
fn expand_bottom_edge(amount: Pixels) -> Self;
fn trim_left_edge(amount: Pixels) -> Self;
fn trim_right_edge(amount: Pixels) -> Self;
fn trim_top_edge(amount: Pixels) -> Self;
fn trim_bottom_edge(amount: Pixels) -> Self;
fn set_resolution(res: ImageResolution) -> Self;
fn no_operation() -> Self;
}
/// Display implementations for forward facing data types.
impl fmt::Display for PageOps {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
PageOps::NoOperation => write!(f, "NoOperation"),
PageOps::Identify(ref file_name, ref file_path) => write!(f, "Identify({}, {})", file_name, file_path),
PageOps::Rescale(pixels, ref dir) => write!(f, "Rescale({} Pixels, {})", pixels, dir),
PageOps::ExpandLeftEdge(pixels) => write!(f, "ExpandLeftEdge({} Pixels)", pixels),
PageOps::ExpandRightEdge(pixels) => write!(f, "ExpandRightEdge({} Pixels)", pixels),
PageOps::ExpandTopEdge(pixels) => write!(f, "ExpandTopEdge({} Pixels)", pixels),
PageOps::ExpandBottomEdge(pixels) => write!(f, "ExpandBottomEdge({} Pixels)", pixels),
PageOps::TrimLeftEdge(pixels) => write!(f, "TrimLeftEdge({} Pixels)", pixels),
PageOps::TrimRightEdge(pixels) => write!(f, "TrimRightEdge({} Pixels)", pixels),
PageOps::TrimTopEdge(pixels) => write!(f, "TrimTopEdge({} Pixels)", pixels),
PageOps::TrimBottomEdge(pixels) => write!(f, "TrimBottomEdge({} Pixels)", pixels),
PageOps::SetResolution(ref res) => write!(f, "SetResolution({})", res),
}
}
}
pub trait RunOperation {
fn run_operation(op: Self) -> OperationResults;
}
trait CompileOperation<OpType, Op> {
fn compile_operation(op: OpType) -> Op;
}
impl<Op> CompileOperation<PageOps, Op> for Op where Op: ElementaryPageOperations {
fn compile_operation(op: PageOps) -> Op {
match op {
PageOps::Identify(file, path) => Op::identify(file, path),
PageOps::Rescale(amount, dir) => Op::rescale(amount, dir),
PageOps::ExpandLeftEdge(amount) => Op::expand_left_edge(amount),
PageOps::ExpandRightEdge(amount) => Op::expand_right_edge(amount),
PageOps::ExpandTopEdge(amount) => Op::expand_top_edge(amount),
PageOps::ExpandBottomEdge(amount) => Op::expand_bottom_edge(amount),
PageOps::TrimLeftEdge(amount) => Op::trim_left_edge(amount),
PageOps::TrimRightEdge(amount) => Op::trim_right_edge(amount),
PageOps::TrimTopEdge(amount) => Op::trim_top_edge(amount),
PageOps::TrimBottomEdge(amount) => Op::trim_bottom_edge(amount),
PageOps::SetResolution(res) => Op::set_resolution(res),
PageOps::NoOperation => Op::no_operation(),
}
}
}
/// CompoundPageOperation enables the ability to apply more than one
/// page operation in sequence, so that more complicated page operations
/// may be constructed in terms of the elementary page operations.
#[derive(Clone, Debug)]
struct CompoundPageOperation<Op> {
page_name: FileName,
page_path: FilePath,
ops: Vec<Op>,
}
impl<Op> CompoundPageOperation<Op> where Op: Clone {
fn new(page_name: FileName, page_path: FilePath, ops: &[Op]) -> CompoundPageOperation<Op> {
let mut vec = Vec::new();
for op in ops.iter() {
vec.push(op.clone());
}
CompoundPageOperation {
page_name: page_name,
page_path: page_path,
ops: vec,
}
}
fn make_no_op(page_name: FileName, page_path: FilePath) -> CompoundPageOperation<Op> {
CompoundPageOperation {
page_name: page_name,
page_path: page_path,
ops: Vec::new(),
}
}
fn is_no_op(&self) -> bool {
self.ops.is_empty()
}
fn iter(&self) -> CPOIter<Op> {
CPOIter {
inner: self.ops.iter()
}
}
}
impl CompoundPageOperation<PageOps> {
fn is_no_op(&self) -> bool {
for op in self.ops.iter() {
if *op == PageOps::NoOperation {
return true;
}
}
false
}
}
impl<Op> fmt::Display for CompoundPageOperation<Op> where Op: Clone + fmt::Display {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut op_string = String::new();
for i in 0..self.ops.len()-1 {
op_string.push_str(self.ops[i].to_string().as_str());
op_string.push_str(", ");
}
op_string.push_str(self.ops[self.ops.len()-1].to_string().as_str());
write!(f, "PageOps([{}])", op_string)
}
}
/// Implementation of CompileOperation for compiling between CompoundPageOperations.
impl<Op, OtherOp> CompileOperation<CompoundPageOperation<Op>, CompoundPageOperation<OtherOp>>
for CompoundPageOperation<Op>
where Op: Clone + CompileOperation<Op, OtherOp>,
OtherOp: Clone
{
fn compile_operation(old_ops: CompoundPageOperation<Op>) -> CompoundPageOperation<OtherOp> {
let mut new_ops = Vec::new();
for old_op in old_ops.clone() {
let new_op = Op::compile_operation(old_op);
new_ops.push(new_op);
}
CompoundPageOperation::new(old_ops.page_name.clone(), old_ops.page_path.clone(), new_ops.as_ref())
}
}
impl<Op> RunOperation for CompoundPageOperation<Op>
where Op: RunOperation {
fn run_operation(op: CompoundPageOperation<Op>) -> OperationResults {
let mut final_results = OperationResults::new();
for elem_op in op {
let mut results = Op::run_operation(elem_op);
final_results.append(&mut results);
}
final_results
}
}
/// Iterator interface for a CompoundPageOperation.
struct CPOIter<'a, Op> where Op: 'a {
inner: slice::Iter<'a, Op>,
}
impl<'a, Op> Iterator for CPOIter<'a, Op> {
type Item = &'a Op;
fn next(&mut self) -> Option<&'a Op> {
self.inner.next()
}
}
struct CPOIntoIter<Op> {
inner: vec::IntoIter<Op>,
}
impl<Op> IntoIterator for CompoundPageOperation<Op> {
type Item = Op;
type IntoIter = CPOIntoIter<Op>;
fn into_iter(self) -> CPOIntoIter<Op> {
CPOIntoIter {
inner: self.ops.into_iter(),
}
}
}
impl<Op> Iterator for CPOIntoIter<Op> {
type Item = Op;
fn next(&mut self) -> Option<Op> {
self.inner.next()
}
}
impl<'a, Op> IntoIterator for &'a CompoundPageOperation<Op> where Op: Clone {
type Item = &'a Op;
type IntoIter = CPOIter<'a, Op>;
fn into_iter(self) -> CPOIter<'a, Op> {
self.iter()
}
}
impl<Op> AsRef<[Op]> for CompoundPageOperation<Op> {
fn as_ref(&self) -> &[Op] {
self.ops.as_ref()
}
}
#[derive(Clone, Eq, Debug)]
struct Page {
file_name: FileName,
file_extension: ImageFileFormat,
file_path: FilePath,
dimensions: ImageDimensions,
resolution: ImageResolution,
}
impl Page {
fn new (
file_name: FileName,
file_extension: ImageFileFormat,
file_path: FilePath,
dimensions: ImageDimensions,
resolution: ImageResolution
) -> Page
{
Page {
file_name: file_name,
file_extension: file_extension,
file_path: file_path,
dimensions: dimensions,
resolution: resolution,
}
}
}
impl PartialEq for Page {
fn eq(&self, other: &Page) -> bool {
self.file_name == other.file_name
&& self.file_extension == other.file_extension
&& self.file_path == other.file_path
&& self.dimensions == other.dimensions
&& self.resolution == other.resolution
}
}
impl Hash for Page {
fn hash<H>(&self, state: &mut H) where H: Hasher {
self.file_name.hash(state);
self.file_extension.hash(state);
self.file_path.hash(state);
self.dimensions.hash(state);
self.resolution.hash(state);
}
}
impl fmt::Display for Page {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Page({}, {}, {}, {})", self.file_name, self.file_extension, self.dimensions, self.resolution)
}
}
pub type OperationResult = io::Result<String>;
#[derive(Clone, Eq, PartialEq, Debug)]
enum OperationStatus {
NotExecuted, // Not (yet) run
Completed, // Ran to completion with not errors reported
Failed, // Completed with errors.
Aborted, // Operation aborted.
}
impl fmt::Display for OperationStatus {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
OperationStatus::NotExecuted => "NotExecuted".fmt(f),
OperationStatus::Completed => "Completed".fmt(f),
OperationStatus::Failed => "Failed".fmt(f),
OperationStatus::Aborted => "Aborted".fmt(f),
}
}
}
#[derive(Debug)]
pub struct OperationResults {
status: OperationStatus,
results: Vec<OperationResult>,
}
impl OperationResults {
pub fn new() -> OperationResults {
OperationResults {
status: OperationStatus::NotExecuted,
results: Vec::new(),
}
}
pub fn push(&mut self, result: OperationResult) {
if result.is_err() {
self.status = OperationStatus::Failed;
}
if self.status == OperationStatus::NotExecuted {
self.status = OperationStatus::Completed;
}
self.results.push(result);
}
pub fn append(&mut self, other: &mut OperationResults) {
let mut status = OperationStatus::NotExecuted;
for res in other.results.iter() {
if res.is_err() {
status = OperationStatus::Failed;
break;
}
}
if other.is_empty() {
status = OperationStatus::Completed;
}
self.results.append(&mut other.results);
self.status = status;
}
pub fn is_failed(&self) -> bool {
self.status == OperationStatus::Failed
}
pub fn is_aborted(&self) -> bool {
self.status == OperationStatus::Aborted
}
pub fn is_empty(&self) -> bool {
self.results.len() == 0
}
}
/// Destructive conversion from a mutable vector of OperationResult
/// to simplify the process of returning results from running operations.
impl<'a> From<&'a mut Vec<OperationResult>> for OperationResults {
fn from(vec: &mut Vec<OperationResult>) -> OperationResults {
let mut results = Vec::new();
results.append(vec);
let mut status = OperationStatus::Completed;
for result in results.iter() {
if result.is_err() {
status = OperationStatus::Failed;
break;
}
}
OperationResults {
status: status,
results: results,
}
}
}
/// Generates an OperationResults struct from a single OperationResult.
/// For compatibility between operations that may return multiple results
/// and ones that may return only one result.
impl From<OperationResult> for OperationResults {
fn from(op_res: OperationResult) -> OperationResults {
let mut results = Vec::new();
let status = if op_res.is_err() {
OperationStatus::Failed
} else {
OperationStatus::Completed
};
results.push(op_res);
OperationResults {
status: status,
results: results,
}
}
}
/// Enables the ability to read operation result as a slice.
impl AsRef<[OperationResult]> for OperationResults {
fn as_ref(&self) -> &[OperationResult] {
self.results.as_ref()
}
}
impl fmt::Display for OperationResults {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut output = String::new();
output.push_str("OperationResults(");
output.push_str("status: ");
output.push_str(self.status.to_string().as_ref());
output.push_str(", results: [");
for i in 0..self.results.len()-1 {
let res = match &self.results[i] {
&Ok(ref s) => s.clone(),
&Err(ref e) => String::from(e.description()),
};
output.push_str(res.as_ref());
output.push_str(", ");
}
let final_res = match &self.results[self.results.len()-1] {
&Ok(ref s) => s.clone(),
&Err(ref e) => String::from(e.description()),
};
output.push_str(final_res.as_ref());
output.push_str("])");
write!(f, "{}", output)
}
}
#[derive(Clone, Debug)]
struct OperationPlan<Op> {
plan: HashMap<Page, CompoundPageOperation<Op>>,
}
impl<Op> OperationPlan<Op> where Op: Clone {
fn new() -> OperationPlan<Op> {
OperationPlan {
plan: HashMap::new(),
}
}
fn insert(&mut self, page: Page, op: CompoundPageOperation<Op>) {
self.plan.insert(page, op);
}
fn build_schedule(pages: &[Page], ops: &[CompoundPageOperation<Op>]) -> Result<Self, String> {
if pages.len() == ops.len() {
let mut plan = OperationPlan::new();
for page_number in 0..pages.len() {
plan.insert(pages[page_number].clone(), ops[page_number].clone());
}
Ok(plan)
} else {
Err(String::from("Length Mismatch"))
}
}
fn iter(&self) -> OpPlanIter<Op> {
OpPlanIter {
inner: self.plan.iter()
}
}
}
impl<Op, OtherOp> CompileOperation<OperationPlan<Op>, OperationPlan<OtherOp>>
for OperationPlan<Op>
where Op: CompileOperation<Op, OtherOp> + Clone,
OtherOp: Clone
{
fn compile_operation(old_plan: OperationPlan<Op>) -> OperationPlan<OtherOp> {
let mut new_plan = OperationPlan::new();
for (page, old_op) in old_plan.clone() {
let new_op = CompoundPageOperation::<Op>::compile_operation(old_op);
new_plan.insert(page.clone(), new_op);
}
new_plan
}
}
/// Iterator implementation for OperationPlan.
struct OpPlanIter<'a, Op: 'a> {
inner: hash_map::Iter<'a, Page, CompoundPageOperation<Op>>
}
impl<'a, Op> Iterator for OpPlanIter<'a, Op> {
type Item = (&'a Page, &'a CompoundPageOperation<Op>);
fn next(&mut self) -> Option<Self::Item> {
self.inner.next()
}
}
/// IntoIterator implementation for OperationPlan.
impl<'a, Op> IntoIterator for &'a OperationPlan<Op> where Op: Clone {
type Item = (&'a Page, &'a CompoundPageOperation<Op>);
type IntoIter = OpPlanIter<'a, Op>;
fn into_iter(self) -> OpPlanIter<'a, Op> {
self.iter()
}
}
struct OpPlanIntoIter<Op> {
inner: hash_map::IntoIter<Page, CompoundPageOperation<Op>>,
}
impl<Op> IntoIterator for OperationPlan<Op> {
type Item = (Page, CompoundPageOperation<Op>);
type IntoIter = OpPlanIntoIter<Op>;
fn into_iter(self) -> OpPlanIntoIter<Op> {
OpPlanIntoIter {
inner: self.plan.into_iter()
}
}
}
impl<Op> Iterator for OpPlanIntoIter<Op> {
type Item = (Page, CompoundPageOperation<Op>);
fn next(&mut self) -> Option<(Page, CompoundPageOperation<Op>)> {
self.inner.next()
}
}
#[derive(Clone, Eq, PartialEq, Debug)]
enum OperationPlanStatus {
NotCompleted,
Completed,
Failed,
Aborted,
}
impl fmt::Display for OperationPlanStatus {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
OperationPlanStatus::NotCompleted => "NotCompleted".fmt(f),
OperationPlanStatus::Completed => "Completed".fmt(f),
OperationPlanStatus::Failed => "Failed".fmt(f),
OperationPlanStatus::Aborted => "Aborted".fmt(f),
}
}
}
#[derive(Debug)]
struct OperationPlanResult {
status: OperationPlanStatus,
results: HashMap<Page, OperationResults>,
}
impl OperationPlanResult {
fn new() -> OperationPlanResult {
OperationPlanResult {
status: OperationPlanStatus::NotCompleted,
results: HashMap::new(),
}
}
fn insert(&mut self, page: Page, res: OperationResults) {
let status = res.status.clone();
self.status = match self.status {
OperationPlanStatus::Failed => OperationPlanStatus::Failed,
OperationPlanStatus::NotCompleted => {
match status {
OperationStatus::NotExecuted => OperationPlanStatus::NotCompleted,
OperationStatus::Completed => OperationPlanStatus::Completed,
OperationStatus::Failed => OperationPlanStatus::Failed,
OperationStatus::Aborted => OperationPlanStatus::Aborted,
}
}
OperationPlanStatus::Completed => {
match status {
OperationStatus::NotExecuted => OperationPlanStatus::NotCompleted, // FIXME: Change this case.
OperationStatus::Completed => OperationPlanStatus::Completed,
OperationStatus::Failed => OperationPlanStatus::Failed,
OperationStatus::Aborted => OperationPlanStatus::Failed,
}
}
OperationPlanStatus::Aborted => {
match status {
OperationStatus::Aborted => OperationPlanStatus::Aborted,
_ => OperationPlanStatus::Failed,
}
}
};
self.results.insert(page, res);
}
fn iter(&self) -> OpPlanResultIter {
OpPlanResultIter {
inner: self.results.iter()
}
}
fn plan_status(&self) -> OperationPlanStatus {
self.status.clone()
}
fn is_not_completed(&self) -> bool {
self.status == OperationPlanStatus::NotCompleted
}
}
/// Iterator instances for running over operaton plan results.
struct OpPlanResultIter<'a> {
inner: hash_map::Iter<'a, Page, OperationResults>,
}
impl<'a> Iterator for OpPlanResultIter<'a> {
type Item = (&'a Page, &'a OperationResults);
fn next(&mut self) -> Option<Self::Item> {
self.inner.next()
}
}
/// IntoIterator implementation for OpPlanResultIter.
impl<'a> IntoIterator for &'a OperationPlanResult {
type Item = (&'a Page, &'a OperationResults);
type IntoIter = OpPlanResultIter<'a>;
fn into_iter(self) -> OpPlanResultIter<'a> {
self.iter()
}
}
struct OpPlanResultIntoIter {
inner: hash_map::IntoIter<Page, OperationResults>,
}
impl IntoIterator for OperationPlanResult {
type Item = (Page, OperationResults);
type IntoIter = OpPlanResultIntoIter;
fn into_iter(self) -> OpPlanResultIntoIter {
OpPlanResultIntoIter {
inner: self.results.into_iter()
}
}
}
impl Iterator for OpPlanResultIntoIter {
type Item = (Page, OperationResults);
fn next(&mut self) -> Option<Self::Item> {
self.inner.next()
}
}
impl fmt::Display for OperationPlanResult {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut output = String::new();
output.push_str("Operation Results: \n");
output.push_str("STATUS: ");
output.push_str(self.status.to_string().as_ref());
output.push('\n');
for (page, res) in self.iter() {
output.push_str(page.file_name.as_ref());
output.push_str(": ");
output.push_str(res.to_string().as_ref());
output.push('\n');
}
write!(f, "{}", output)
}
}
trait ExecutePlan<OpType> where OpType: RunOperation {
type ExecutionResult;
fn execute_plan(&self) -> Self::ExecutionResult;
fn abort_plan(&self, result: &mut Self::ExecutionResult) -> Self::ExecutionResult;
}
impl<Op> ExecutePlan<Op> for OperationPlan<Op>
where Op: RunOperation + Clone
{
type ExecutionResult = OperationPlanResult;
/// Execute plan does not short circuit by default.
/// TODO: Incorporate Execution strategies into executing plans.
fn execute_plan(&self) -> OperationPlanResult {
let mut report = OperationPlanResult::new();
for (page, op) in self {
let result = CompoundPageOperation::<Op>::run_operation(op.clone());
report.insert(page.clone(), result);
}
report
}
/// Aborts execution of an operation plan. If the operation plan did not run yet,
/// it terminates with an Aborted status. If it was being run, it terminates with a
/// Failed status.
fn abort_plan(&self, result: &mut OperationPlanResult) -> OperationPlanResult {
unimplemented!();
}
}
|
pub fn a() {}
#[cfg(test)]
mod tests {
use crate::a;
#[test]
fn it_works() {
a();
}
}
|
//! This module contains a configuration of a [`Border`] or a [`Table`] to set its borders color via [`Color`].
//!
//! [`Border`]: crate::settings::Border
//! [`Table`]: crate::Table
use std::{borrow::Cow, ops::BitOr};
use crate::{
grid::{
color::{AnsiColor, StaticColor},
config::{ColoredConfig, Entity},
},
settings::{CellOption, TableOption},
};
/// Color represents a color which can be set to things like [`Border`], [`Padding`] and [`Margin`].
///
/// # Example
///
/// ```
/// use tabled::{settings::Color, Table};
///
/// let data = [
/// (0u8, "Hello"),
/// (1u8, "World"),
/// ];
///
/// let table = Table::new(data)
/// .with(Color::BG_BLUE)
/// .to_string();
///
/// println!("{}", table);
/// ```
///
/// [`Padding`]: crate::settings::Padding
/// [`Margin`]: crate::settings::Margin
/// [`Border`]: crate::settings::Border
#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Color(AnsiColor<'static>);
#[rustfmt::skip]
impl Color {
/// A color representation.
///
/// Notice that the colors are constants so you can't combine them.
pub const FG_BLACK: Self = Self(AnsiColor::new(Cow::Borrowed("\u{1b}[30m"), Cow::Borrowed("\u{1b}[39m")));
/// A color representation.
///
/// Notice that the colors are constants so you can't combine them.
pub const FG_BLUE: Self = Self(AnsiColor::new(Cow::Borrowed("\u{1b}[34m"), Cow::Borrowed("\u{1b}[39m")));
/// A color representation.
///
/// Notice that the colors are constants so you can't combine them.
pub const FG_BRIGHT_BLACK: Self = Self(AnsiColor::new(Cow::Borrowed("\u{1b}[90m"), Cow::Borrowed("\u{1b}[39m")));
/// A color representation.
///
/// Notice that the colors are constants so you can't combine them.
pub const FG_BRIGHT_BLUE: Self = Self(AnsiColor::new(Cow::Borrowed("\u{1b}[94m"), Cow::Borrowed("\u{1b}[39m")));
/// A color representation.
///
/// Notice that the colors are constants so you can't combine them.
pub const FG_BRIGHT_CYAN: Self = Self(AnsiColor::new(Cow::Borrowed("\u{1b}[96m"), Cow::Borrowed("\u{1b}[39m")));
/// A color representation.
///
/// Notice that the colors are constants so you can't combine them.
pub const FG_BRIGHT_GREEN: Self = Self(AnsiColor::new(Cow::Borrowed("\u{1b}[92m"), Cow::Borrowed("\u{1b}[39m")));
/// A color representation.
///
/// Notice that the colors are constants so you can't combine them.
pub const FG_BRIGHT_MAGENTA: Self = Self(AnsiColor::new(Cow::Borrowed("\u{1b}[95m"), Cow::Borrowed("\u{1b}[39m")));
/// A color representation.
///
/// Notice that the colors are constants so you can't combine them.
pub const FG_BRIGHT_RED: Self = Self(AnsiColor::new(Cow::Borrowed("\u{1b}[91m"), Cow::Borrowed("\u{1b}[39m")));
/// A color representation.
///
/// Notice that the colors are constants so you can't combine them.
pub const FG_BRIGHT_WHITE: Self = Self(AnsiColor::new(Cow::Borrowed("\u{1b}[97m"), Cow::Borrowed("\u{1b}[39m")));
/// A color representation.
///
/// Notice that the colors are constants so you can't combine them.
pub const FG_BRIGHT_YELLOW: Self = Self(AnsiColor::new(Cow::Borrowed("\u{1b}[93m"), Cow::Borrowed("\u{1b}[39m")));
/// A color representation.
///
/// Notice that the colors are constants so you can't combine them.
pub const FG_CYAN: Self = Self(AnsiColor::new(Cow::Borrowed("\u{1b}[36m"), Cow::Borrowed("\u{1b}[39m")));
/// A color representation.
///
/// Notice that the colors are constants so you can't combine them.
pub const FG_GREEN: Self = Self(AnsiColor::new(Cow::Borrowed("\u{1b}[32m"), Cow::Borrowed("\u{1b}[39m")));
/// A color representation.
///
/// Notice that the colors are constants so you can't combine them.
pub const FG_MAGENTA: Self = Self(AnsiColor::new(Cow::Borrowed("\u{1b}[35m"), Cow::Borrowed("\u{1b}[39m")));
/// A color representation.
///
/// Notice that the colors are constants so you can't combine them.
pub const FG_RED: Self = Self(AnsiColor::new(Cow::Borrowed("\u{1b}[31m"), Cow::Borrowed("\u{1b}[39m")));
/// A color representation.
///
/// Notice that the colors are constants so you can't combine them.
pub const FG_WHITE: Self = Self(AnsiColor::new(Cow::Borrowed("\u{1b}[37m"), Cow::Borrowed("\u{1b}[39m")));
/// A color representation.
///
/// Notice that the colors are constants so you can't combine them.
pub const FG_YELLOW: Self = Self(AnsiColor::new(Cow::Borrowed("\u{1b}[33m"), Cow::Borrowed("\u{1b}[39m")));
/// A color representation.
///
/// Notice that the colors are constants so you can't combine them.
pub const BG_BLACK: Self = Self(AnsiColor::new(Cow::Borrowed("\u{1b}[40m"), Cow::Borrowed("\u{1b}[49m")));
/// A color representation.
///
/// Notice that the colors are constants so you can't combine them.
pub const BG_BLUE: Self = Self(AnsiColor::new(Cow::Borrowed("\u{1b}[44m"), Cow::Borrowed("\u{1b}[49m")));
/// A color representation.
///
/// Notice that the colors are constants so you can't combine them.
pub const BG_BRIGHT_BLACK: Self = Self(AnsiColor::new(Cow::Borrowed("\u{1b}[100m"), Cow::Borrowed("\u{1b}[49m")));
/// A color representation.
///
/// Notice that the colors are constants so you can't combine them.
pub const BG_BRIGHT_BLUE: Self = Self(AnsiColor::new(Cow::Borrowed("\u{1b}[104m"), Cow::Borrowed("\u{1b}[49m")));
/// A color representation.
///
/// Notice that the colors are constants so you can't combine them.
pub const BG_BRIGHT_CYAN: Self = Self(AnsiColor::new(Cow::Borrowed("\u{1b}[106m"), Cow::Borrowed("\u{1b}[49m")));
/// A color representation.
///
/// Notice that the colors are constants so you can't combine them.
pub const BG_BRIGHT_GREEN: Self = Self(AnsiColor::new(Cow::Borrowed("\u{1b}[102m"), Cow::Borrowed("\u{1b}[49m")));
/// A color representation.
///
/// Notice that the colors are constants so you can't combine them.
pub const BG_BRIGHT_MAGENTA: Self = Self(AnsiColor::new(Cow::Borrowed("\u{1b}[105m"), Cow::Borrowed("\u{1b}[49m")));
/// A color representation.
///
/// Notice that the colors are constants so you can't combine them.
pub const BG_BRIGHT_RED: Self = Self(AnsiColor::new(Cow::Borrowed("\u{1b}[101m"), Cow::Borrowed("\u{1b}[49m")));
/// A color representation.
///
/// Notice that the colors are constants so you can't combine them.
pub const BG_BRIGHT_WHITE: Self = Self(AnsiColor::new(Cow::Borrowed("\u{1b}[107m"), Cow::Borrowed("\u{1b}[49m")));
/// A color representation.
///
/// Notice that the colors are constants so you can't combine them.
pub const BG_BRIGHT_YELLOW: Self = Self(AnsiColor::new(Cow::Borrowed("\u{1b}[103m"), Cow::Borrowed("\u{1b}[49m")));
/// A color representation.
///
/// Notice that the colors are constants so you can't combine them.
pub const BG_CYAN: Self = Self(AnsiColor::new(Cow::Borrowed("\u{1b}[46m"), Cow::Borrowed("\u{1b}[49m")));
/// A color representation.
///
/// Notice that the colors are constants so you can't combine them.
pub const BG_GREEN: Self = Self(AnsiColor::new(Cow::Borrowed("\u{1b}[42m"), Cow::Borrowed("\u{1b}[49m")));
/// A color representation.
///
/// Notice that the colors are constants so you can't combine them.
pub const BG_MAGENTA: Self = Self(AnsiColor::new(Cow::Borrowed("\u{1b}[45m"), Cow::Borrowed("\u{1b}[49m")));
/// A color representation.
///
/// Notice that the colors are constants so you can't combine them.
pub const BG_RED: Self = Self(AnsiColor::new(Cow::Borrowed("\u{1b}[41m"), Cow::Borrowed("\u{1b}[49m")));
/// A color representation.
///
/// Notice that the colors are constants so you can't combine them.
pub const BG_WHITE: Self = Self(AnsiColor::new(Cow::Borrowed("\u{1b}[47m"), Cow::Borrowed("\u{1b}[49m")));
/// A color representation.
///
/// Notice that the colors are constants so you can't combine them.
pub const BG_YELLOW: Self = Self(AnsiColor::new(Cow::Borrowed("\u{1b}[43m"), Cow::Borrowed("\u{1b}[49m")));
/// A color representation.
///
/// Notice that the colors are constants so you can't combine them.
pub const BOLD: Self = Self(AnsiColor::new(Cow::Borrowed("\u{1b}[1m"), Cow::Borrowed("\u{1b}[22m")));
}
impl Color {
/// Creates a new [`Color`]` instance, with ANSI prefix and ANSI suffix.
/// You can use [`TryFrom`] to construct it from [`String`].
pub fn new(prefix: String, suffix: String) -> Self {
Self(AnsiColor::new(prefix.into(), suffix.into()))
}
}
impl From<Color> for AnsiColor<'static> {
fn from(c: Color) -> Self {
c.0
}
}
impl From<AnsiColor<'static>> for Color {
fn from(c: AnsiColor<'static>) -> Self {
Self(c)
}
}
impl From<StaticColor> for Color {
fn from(c: StaticColor) -> Self {
Self(AnsiColor::new(
Cow::Borrowed(c.get_prefix()),
Cow::Borrowed(c.get_suffix()),
))
}
}
impl BitOr for Color {
type Output = Color;
fn bitor(self, rhs: Self) -> Self::Output {
let l_prefix = self.0.get_prefix();
let l_suffix = self.0.get_suffix();
let r_prefix = rhs.0.get_prefix();
let r_suffix = rhs.0.get_suffix();
let mut prefix = l_prefix.to_string();
if l_prefix != r_prefix {
prefix.push_str(r_prefix);
}
let mut suffix = l_suffix.to_string();
if l_suffix != r_suffix {
suffix.push_str(r_suffix);
}
Self::new(prefix, suffix)
}
}
#[cfg(feature = "color")]
impl std::convert::TryFrom<&str> for Color {
type Error = ();
fn try_from(value: &str) -> Result<Self, Self::Error> {
AnsiColor::try_from(value).map(Color)
}
}
#[cfg(feature = "color")]
impl std::convert::TryFrom<String> for Color {
type Error = ();
fn try_from(value: String) -> Result<Self, Self::Error> {
AnsiColor::try_from(value).map(Color)
}
}
impl<R, D> TableOption<R, D, ColoredConfig> for Color {
fn change(self, _: &mut R, cfg: &mut ColoredConfig, _: &mut D) {
let _ = cfg.set_color(Entity::Global, self.0.clone());
}
fn hint_change(&self) -> Option<Entity> {
None
}
}
impl<R> CellOption<R, ColoredConfig> for Color {
fn change(self, _: &mut R, cfg: &mut ColoredConfig, entity: Entity) {
let _ = cfg.set_color(entity, self.0.clone());
}
fn hint_change(&self) -> Option<Entity> {
None
}
}
impl<R> CellOption<R, ColoredConfig> for &Color {
fn change(self, _: &mut R, cfg: &mut ColoredConfig, entity: Entity) {
let _ = cfg.set_color(entity, self.0.clone());
}
fn hint_change(&self) -> Option<Entity> {
None
}
}
impl crate::grid::color::Color for Color {
fn fmt_prefix<W: std::fmt::Write>(&self, f: &mut W) -> std::fmt::Result {
self.0.fmt_prefix(f)
}
fn fmt_suffix<W: std::fmt::Write>(&self, f: &mut W) -> std::fmt::Result {
self.0.fmt_suffix(f)
}
fn colorize<W: std::fmt::Write>(&self, f: &mut W, text: &str) -> std::fmt::Result {
self.0.colorize(f, text)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(feature = "color")]
use ::{owo_colors::OwoColorize, std::convert::TryFrom};
#[test]
fn test_xor_operation() {
assert_eq!(
Color::FG_BLACK | Color::FG_BLUE,
Color::new(
String::from("\u{1b}[30m\u{1b}[34m"),
String::from("\u{1b}[39m")
)
);
assert_eq!(
Color::FG_BRIGHT_GREEN | Color::BG_BLUE,
Color::new(
String::from("\u{1b}[92m\u{1b}[44m"),
String::from("\u{1b}[39m\u{1b}[49m")
)
);
assert_eq!(
Color::new(String::from("..."), String::from("!!!"))
| Color::new(String::from("@@@"), String::from("###")),
Color::new(String::from("...@@@"), String::from("!!!###"))
);
assert_eq!(
Color::new(String::from("..."), String::from("!!!"))
| Color::new(String::from("@@@"), String::from("###"))
| Color::new(String::from("$$$"), String::from("%%%")),
Color::new(String::from("...@@@$$$"), String::from("!!!###%%%"))
);
}
#[cfg(feature = "color")]
#[test]
fn test_try_from() {
assert_eq!(Color::try_from(""), Err(()));
assert_eq!(Color::try_from("".red().on_green().to_string()), Err(()));
assert_eq!(
Color::try_from("."),
Ok(Color::new(String::new(), String::new()))
);
assert_eq!(
Color::try_from("...."),
Ok(Color::new(String::new(), String::new()))
);
assert_eq!(
Color::try_from(".".red().on_green().to_string()),
Ok(Color::new(
String::from("\u{1b}[31m\u{1b}[42m"),
String::from("\u{1b}[39m\u{1b}[49m")
))
);
assert_eq!(
Color::try_from("....".red().on_green().to_string()),
Ok(Color::new(
String::from("\u{1b}[31m\u{1b}[42m"),
String::from("\u{1b}[39m\u{1b}[49m")
))
);
}
}
|
/// An enum to represent all characters in the Osmanya block.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum Osmanya {
/// \u{10480}: '𐒀'
LetterAlef,
/// \u{10481}: '𐒁'
LetterBa,
/// \u{10482}: '𐒂'
LetterTa,
/// \u{10483}: '𐒃'
LetterJa,
/// \u{10484}: '𐒄'
LetterXa,
/// \u{10485}: '𐒅'
LetterKha,
/// \u{10486}: '𐒆'
LetterDeel,
/// \u{10487}: '𐒇'
LetterRa,
/// \u{10488}: '𐒈'
LetterSa,
/// \u{10489}: '𐒉'
LetterShiin,
/// \u{1048a}: '𐒊'
LetterDha,
/// \u{1048b}: '𐒋'
LetterCayn,
/// \u{1048c}: '𐒌'
LetterGa,
/// \u{1048d}: '𐒍'
LetterFa,
/// \u{1048e}: '𐒎'
LetterQaaf,
/// \u{1048f}: '𐒏'
LetterKaaf,
/// \u{10490}: '𐒐'
LetterLaan,
/// \u{10491}: '𐒑'
LetterMiin,
/// \u{10492}: '𐒒'
LetterNuun,
/// \u{10493}: '𐒓'
LetterWaw,
/// \u{10494}: '𐒔'
LetterHa,
/// \u{10495}: '𐒕'
LetterYa,
/// \u{10496}: '𐒖'
LetterA,
/// \u{10497}: '𐒗'
LetterE,
/// \u{10498}: '𐒘'
LetterI,
/// \u{10499}: '𐒙'
LetterO,
/// \u{1049a}: '𐒚'
LetterU,
/// \u{1049b}: '𐒛'
LetterAa,
/// \u{1049c}: '𐒜'
LetterEe,
/// \u{1049d}: '𐒝'
LetterOo,
/// \u{104a0}: '𐒠'
DigitZero,
/// \u{104a1}: '𐒡'
DigitOne,
/// \u{104a2}: '𐒢'
DigitTwo,
/// \u{104a3}: '𐒣'
DigitThree,
/// \u{104a4}: '𐒤'
DigitFour,
/// \u{104a5}: '𐒥'
DigitFive,
/// \u{104a6}: '𐒦'
DigitSix,
/// \u{104a7}: '𐒧'
DigitSeven,
/// \u{104a8}: '𐒨'
DigitEight,
/// \u{104a9}: '𐒩'
DigitNine,
}
impl Into<char> for Osmanya {
fn into(self) -> char {
match self {
Osmanya::LetterAlef => '𐒀',
Osmanya::LetterBa => '𐒁',
Osmanya::LetterTa => '𐒂',
Osmanya::LetterJa => '𐒃',
Osmanya::LetterXa => '𐒄',
Osmanya::LetterKha => '𐒅',
Osmanya::LetterDeel => '𐒆',
Osmanya::LetterRa => '𐒇',
Osmanya::LetterSa => '𐒈',
Osmanya::LetterShiin => '𐒉',
Osmanya::LetterDha => '𐒊',
Osmanya::LetterCayn => '𐒋',
Osmanya::LetterGa => '𐒌',
Osmanya::LetterFa => '𐒍',
Osmanya::LetterQaaf => '𐒎',
Osmanya::LetterKaaf => '𐒏',
Osmanya::LetterLaan => '𐒐',
Osmanya::LetterMiin => '𐒑',
Osmanya::LetterNuun => '𐒒',
Osmanya::LetterWaw => '𐒓',
Osmanya::LetterHa => '𐒔',
Osmanya::LetterYa => '𐒕',
Osmanya::LetterA => '𐒖',
Osmanya::LetterE => '𐒗',
Osmanya::LetterI => '𐒘',
Osmanya::LetterO => '𐒙',
Osmanya::LetterU => '𐒚',
Osmanya::LetterAa => '𐒛',
Osmanya::LetterEe => '𐒜',
Osmanya::LetterOo => '𐒝',
Osmanya::DigitZero => '𐒠',
Osmanya::DigitOne => '𐒡',
Osmanya::DigitTwo => '𐒢',
Osmanya::DigitThree => '𐒣',
Osmanya::DigitFour => '𐒤',
Osmanya::DigitFive => '𐒥',
Osmanya::DigitSix => '𐒦',
Osmanya::DigitSeven => '𐒧',
Osmanya::DigitEight => '𐒨',
Osmanya::DigitNine => '𐒩',
}
}
}
impl std::convert::TryFrom<char> for Osmanya {
type Error = ();
fn try_from(c: char) -> Result<Self, Self::Error> {
match c {
'𐒀' => Ok(Osmanya::LetterAlef),
'𐒁' => Ok(Osmanya::LetterBa),
'𐒂' => Ok(Osmanya::LetterTa),
'𐒃' => Ok(Osmanya::LetterJa),
'𐒄' => Ok(Osmanya::LetterXa),
'𐒅' => Ok(Osmanya::LetterKha),
'𐒆' => Ok(Osmanya::LetterDeel),
'𐒇' => Ok(Osmanya::LetterRa),
'𐒈' => Ok(Osmanya::LetterSa),
'𐒉' => Ok(Osmanya::LetterShiin),
'𐒊' => Ok(Osmanya::LetterDha),
'𐒋' => Ok(Osmanya::LetterCayn),
'𐒌' => Ok(Osmanya::LetterGa),
'𐒍' => Ok(Osmanya::LetterFa),
'𐒎' => Ok(Osmanya::LetterQaaf),
'𐒏' => Ok(Osmanya::LetterKaaf),
'𐒐' => Ok(Osmanya::LetterLaan),
'𐒑' => Ok(Osmanya::LetterMiin),
'𐒒' => Ok(Osmanya::LetterNuun),
'𐒓' => Ok(Osmanya::LetterWaw),
'𐒔' => Ok(Osmanya::LetterHa),
'𐒕' => Ok(Osmanya::LetterYa),
'𐒖' => Ok(Osmanya::LetterA),
'𐒗' => Ok(Osmanya::LetterE),
'𐒘' => Ok(Osmanya::LetterI),
'𐒙' => Ok(Osmanya::LetterO),
'𐒚' => Ok(Osmanya::LetterU),
'𐒛' => Ok(Osmanya::LetterAa),
'𐒜' => Ok(Osmanya::LetterEe),
'𐒝' => Ok(Osmanya::LetterOo),
'𐒠' => Ok(Osmanya::DigitZero),
'𐒡' => Ok(Osmanya::DigitOne),
'𐒢' => Ok(Osmanya::DigitTwo),
'𐒣' => Ok(Osmanya::DigitThree),
'𐒤' => Ok(Osmanya::DigitFour),
'𐒥' => Ok(Osmanya::DigitFive),
'𐒦' => Ok(Osmanya::DigitSix),
'𐒧' => Ok(Osmanya::DigitSeven),
'𐒨' => Ok(Osmanya::DigitEight),
'𐒩' => Ok(Osmanya::DigitNine),
_ => Err(()),
}
}
}
impl Into<u32> for Osmanya {
fn into(self) -> u32 {
let c: char = self.into();
let hex = c
.escape_unicode()
.to_string()
.replace("\\u{", "")
.replace("}", "");
u32::from_str_radix(&hex, 16).unwrap()
}
}
impl std::convert::TryFrom<u32> for Osmanya {
type Error = ();
fn try_from(u: u32) -> Result<Self, Self::Error> {
if let Ok(c) = char::try_from(u) {
Self::try_from(c)
} else {
Err(())
}
}
}
impl Iterator for Osmanya {
type Item = Self;
fn next(&mut self) -> Option<Self> {
let index: u32 = (*self).into();
use std::convert::TryFrom;
Self::try_from(index + 1).ok()
}
}
impl Osmanya {
/// The character with the lowest index in this unicode block
pub fn new() -> Self {
Osmanya::LetterAlef
}
/// The character's name, in sentence case
pub fn name(&self) -> String {
let s = std::format!("Osmanya{:#?}", self);
string_morph::to_sentence_case(&s)
}
}
|
#[derive(Default, Debug, Clone, PartialEq, serde_derive::Serialize, serde_derive::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Root {
pub id: String,
pub sector_tree: SectorTree,
pub content: Content,
}
#[derive(Default, Debug, Clone, PartialEq, serde_derive::Serialize, serde_derive::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SectorTree {
pub security: String,
pub id: String,
pub name: String,
pub ni_codes: Vec<String>,
pub children: Vec<Children>,
pub percent_change1_day: f64,
pub weight: i64,
pub last_update_epoch: String,
}
#[derive(Default, Debug, Clone, PartialEq, serde_derive::Serialize, serde_derive::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Children {
pub security: String,
pub id: i64,
pub name: String,
pub ni_codes: Vec<String>,
pub children: Vec<Children2>,
pub percent_change1_day: f64,
pub weight: f64,
pub last_update_epoch: String,
}
#[derive(Default, Debug, Clone, PartialEq, serde_derive::Serialize, serde_derive::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Children2 {
pub security: String,
pub id: i64,
pub name: String,
pub ni_codes: Vec<String>,
pub percent_change1_day: f64,
pub weight: f64,
pub last_update_epoch: String,
}
#[derive(Default, Debug, Clone, PartialEq, serde_derive::Serialize, serde_derive::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Content {
pub id: String,
pub articles: Vec<Article>,
pub videos: Vec<Video>,
}
#[derive(Default, Debug, Clone, PartialEq, serde_derive::Serialize, serde_derive::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Article {
pub headline: String,
pub url: String,
pub summary: String,
pub updated_at: String,
pub thumbnail: Thumbnail,
#[serde(rename = "updatedAtISO")]
pub updated_at_iso: String,
}
#[derive(Default, Debug, Clone, PartialEq, serde_derive::Serialize, serde_derive::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Thumbnail {
pub base_url: String,
pub orig_width: i64,
}
#[derive(Default, Debug, Clone, PartialEq, serde_derive::Serialize, serde_derive::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Video {
pub headline: String,
pub url: String,
pub summary: String,
pub updated_at: String,
pub thumbnail: Thumbnail2,
#[serde(rename = "updatedAtISO")]
pub updated_at_iso: String,
}
#[derive(Default, Debug, Clone, PartialEq, serde_derive::Serialize, serde_derive::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Thumbnail2 {
pub base_url: String,
}
|
use amethyst::ecs::prelude::{Component, VecStorage};
/// A physics-affected entity need to have either friction, air resistance or both,
/// otherwise it won't move.
#[derive(Debug, Default, Clone)]
pub struct PhysicalProperties {
/// The weight of the entity itself, like a car's empty mass.
pub mass: f32,
/// The resistance against rotational acceleration.
/// If it is `None`, this entity cannot be rotated.
pub inertia: Option<f32,>,
/// The value of the friction coefficient.
/// If it is `None`, this entity has supposedly no ground contact,
/// e.g. the Ship, as it is supported by the Tracks.
pub friction: Option<f32,>,
/// The value of the air-resistance coefficient.
/// If it is `None`, this entity has supposedly no air resistance,
/// e.g. the Drill, as it is supposed to be pulled into the Ship when flying.
pub air_resistance: Option<f32,>,
}
impl PhysicalProperties {
pub fn new(
mass: f32,
inertia: Option<f32,>,
friction: Option<f32,>,
air_resistance: Option<f32,>,
) -> Self {
PhysicalProperties {
mass,
inertia,
friction,
air_resistance,
}
}
}
impl Component for PhysicalProperties {
type Storage = VecStorage<Self,>;
}
|
use cid::Cid;
use sp_std::{
self,
collections::btree_map::BTreeMap,
vec::Vec,
};
#[derive(Clone, PartialEq)]
pub enum Ipld {
/// Represents the absence of a value or the value undefined.
Null,
/// Represents a boolean value.
Bool(bool),
/// Represents an integer.
Integer(i128),
/// Represents a floating point value.
Float(f64),
/// Represents an UTF-8 string.
String(String),
/// Represents a sequence of bytes.
Bytes(Vec<u8>),
/// Represents a list.
List(Vec<Ipld>),
/// Represents a map of strings.
StringMap(BTreeMap<String, Ipld>),
/// Represents a link to an Ipld node.
Link(Cid),
}
impl sp_std::fmt::Debug for Ipld {
fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
use Ipld::*;
match self {
Null => write!(f, "null"),
Bool(b) => write!(f, "{:?}", b),
Integer(i) => write!(f, "{:?}", i),
Float(i) => write!(f, "{:?}", i),
String(s) => write!(f, "{:?}", s),
Bytes(b) => write!(f, "{:?}", b),
List(l) => write!(f, "{:?}", l),
StringMap(m) => write!(f, "{:?}", m),
Link(cid) => write!(f, "{}", cid),
}
}
}
#[cfg(test)]
pub mod tests {
use super::*;
use crate::rand::Rng;
use multihash::{
Code,
MultihashDigest,
};
use quickcheck::{
Arbitrary,
Gen,
};
pub fn arbitrary_cid(g: &mut Gen) -> Cid {
let mut bytes: [u8; 32] = [0; 32];
for x in bytes.iter_mut() {
*x = Arbitrary::arbitrary(g);
}
Cid::new_v1(0x55, Code::Blake2b256.digest(&bytes))
}
pub fn frequency<T, F: Fn(&mut Gen) -> T>(
g: &mut Gen,
gens: Vec<(i64, F)>,
) -> T {
if gens.iter().any(|(v, _)| *v < 0) {
panic!("Negative weight");
}
let sum: i64 = gens.iter().map(|x| x.0).sum();
let mut rng = rand::thread_rng();
let mut weight: i64 = rng.gen_range(1..=sum);
// let mut weight: i64 = g.rng.gen_range(1, sum);
for gen in gens {
if weight - gen.0 <= 0 {
return gen.1(g);
}
else {
weight -= gen.0;
}
}
panic!("Calculation error for weight = {}", weight);
}
fn arbitrary_null() -> Box<dyn Fn(&mut Gen) -> Ipld> {
Box::new(move |_: &mut Gen| Ipld::Null)
}
fn arbitrary_bool() -> Box<dyn Fn(&mut Gen) -> Ipld> {
Box::new(move |g: &mut Gen| Ipld::Bool(Arbitrary::arbitrary(g)))
}
fn arbitrary_link() -> Box<dyn Fn(&mut Gen) -> Ipld> {
Box::new(move |g: &mut Gen| Ipld::Link(arbitrary_cid(g)))
}
pub fn arbitrary_i128() -> Box<dyn Fn(&mut Gen) -> i128> {
Box::new(move |g: &mut Gen| {
let sgn: bool = Arbitrary::arbitrary(g);
if sgn {
let x: u64 = Arbitrary::arbitrary(g);
x as i128
}
else {
let x: i64 = Arbitrary::arbitrary(g);
if x.is_positive() { -x as i128 } else { x as i128 }
}
})
}
pub fn arbitrary_integer() -> Box<dyn Fn(&mut Gen) -> Ipld> {
Box::new(move |g: &mut Gen| Ipld::Integer(arbitrary_i128()(g)))
}
fn arbitrary_string() -> Box<dyn Fn(&mut Gen) -> Ipld> {
Box::new(move |g: &mut Gen| Ipld::String(Arbitrary::arbitrary(g)))
}
fn arbitrary_bytes() -> Box<dyn Fn(&mut Gen) -> Ipld> {
Box::new(move |g: &mut Gen| Ipld::Bytes(Arbitrary::arbitrary(g)))
}
fn arbitrary_float() -> Box<dyn Fn(&mut Gen) -> Ipld> {
Box::new(move |g: &mut Gen| Ipld::Float(Arbitrary::arbitrary(g)))
}
pub fn arbitrary_list() -> Box<dyn Fn(&mut Gen) -> Ipld> {
Box::new(move |g: &mut Gen| {
let mut rng = rand::thread_rng();
let size = rng.gen_range(0..5);
Ipld::List((0..size).map(|_| Arbitrary::arbitrary(g)).collect())
})
}
pub fn arbitrary_stringmap() -> Box<dyn Fn(&mut Gen) -> Ipld> {
Box::new(move |g: &mut Gen| {
let mut rng = rand::thread_rng();
let size = rng.gen_range(0..5);
Ipld::StringMap((0..size).map(|_| Arbitrary::arbitrary(g)).collect())
})
}
impl Arbitrary for Ipld {
fn arbitrary(g: &mut Gen) -> Self {
frequency(g, vec![
(100, arbitrary_null()),
(100, arbitrary_bool()),
(100, arbitrary_link()),
(100, arbitrary_integer()),
(100, arbitrary_string()),
(100, arbitrary_bytes()),
(30, arbitrary_list()),
(30, arbitrary_stringmap()),
])
}
}
}
|
mod call_stack;
use std::iter;
use datum::Datum;
use spell::Instruction;
use spell::Local;
use spell::SpellId;
pub use self::call_stack::*;
/// Interpret a single instruction and return what should happen to the call
/// stack.
#[inline(always)]
pub fn interpret_instruction<'a>(
program_counter: ProgramCounter<'a>,
local_variables: &'a mut [Datum],
) -> CallStackMutation<'a> {
macro_rules! local {
($l:expr) => {{
local_variables.get($l.0 as usize)
.expect("Local variable out of bounds")
.clone()
}};
($l:expr, $v:expr) => {{
*local_variables.get_mut($l.0 as usize)
.expect("Local variable out of bounds")
= $v;
}};
}
match program_counter.get() {
Instruction::Copy{from, to} => {
let value = local!(from);
local!(to, value);
CallStackMutation{
jump: program_counter.advance(),
exit: None,
call: None,
}
},
Instruction::InvokeStatic{result, spellbook, spell, arguments} => {
let argument_values: Box<[Datum]> =
arguments.iter().map(|l| local!(l)).collect();
let callee = SpellId{
spellbook: *spellbook,
spell: *spell,
arity: argument_values.len(),
};
let call = Call{
callee: callee,
arguments: argument_values,
return_into: *result,
};
CallStackMutation{
jump: program_counter.advance(),
exit: None,
call: Some(call),
}
},
Instruction::InvokeDynamic{result, spell, receiver, arguments} => {
let receiver_value = local!(receiver);
let argument_values: Box<[Datum]> =
iter::once(receiver_value.clone())
.chain(arguments.iter().map(|l| local!(l)))
.collect();
let callee = SpellId{
spellbook: receiver_value.enchantment(),
spell: *spell,
arity: argument_values.len(),
};
let call = Call{
callee: callee,
arguments: argument_values,
return_into: *result,
};
CallStackMutation{
jump: program_counter.advance(),
exit: None,
call: Some(call),
}
},
Instruction::Return{result} => {
let value = local!(result);
CallStackMutation{
jump: program_counter,
exit: Some(value),
call: None,
}
},
}
}
/// A description of what must happen to the call stack after interpreting an
/// instruction.
///
/// Both exit and call may be set. In that case, a tail call must occur.
#[derive(Debug)]
pub struct CallStackMutation<'a> {
/// Which instruction to jump to before changing the active stack
/// frame. Not relevant if exit is set.
pub jump: ProgramCounter<'a>,
/// Exit the stack frame with a return value.
pub exit: Option<Datum<'a>>,
/// Create a new stack frame, invoking a spell with some arguments.
pub call: Option<Call<'a>>,
}
/// A call to be performed.
#[derive(Debug)]
pub struct Call<'a> {
pub callee: SpellId,
pub arguments: Box<[Datum<'a>]>,
pub return_into: Local,
}
|
fn main() {
// Line comments
/*
Block Comments
*/
// println!("Rust or Go?")
/*
public static void main(String[] args) {
System.out.print.ln("Hello, World!");
}
*/
println!("Hello World!");
println!("I'm Rustacean!\nAre you?");
let x = 5 + /* 90 + */ 5;
println!("Is `x` 10 or 100? x = {}", x);
}
|
fn down_heap<T: Ord>(a: &mut [T], i: usize, n: usize) {
let mut p = i;
loop {
let q = p;
let left = (q << 1) + 1;
if left < n && a[p] < a[left] {
p = left
}
let right = (q << 1) + 2;
if right < n && a[p] < a[right] {
p = right
}
a.swap(q, p);
if q == p {
break;
}
}
}
fn heap_sort<T: Ord>(a: &mut [T]) {
let len = a.len();
for i in (0, len / 2 + 1).rev() {
down_heap(a, i, len);
}
for i in (1, len).rev() {
a.swap(0, i);
down_heap(a, 0, i - 1);
}
}
fn main() {
let a: &mut [u32] = &mut[1, 5, 3, 2, 10, 30, 2, 5, 6];
heap_sort(a);
for i in a.iter() {
print!("{} ", i);
}
} |
use std::collections::HashMap;
use std::iter::empty;
use std::time::Instant;
use hymns::vector2::Point2;
const INPUT: &str = include_str!("../input.txt");
fn make_point(coord: &str) -> Point2<i32> {
let mut coords = coord.split(',').map(|c| c.parse().unwrap());
let x: i32 = coords.next().unwrap();
let y: i32 = coords.next().unwrap();
Point2::new(x, y)
}
fn generate_points_on_line_segment(
start: &Point2<i32>,
end: &Point2<i32>,
include_diagonal: bool,
) -> Box<dyn Iterator<Item = Point2<i32>>> {
if start.x == end.x {
let min_y = start.y.min(end.y);
let max_y = start.y.max(end.y);
let x = start.x;
Box::new((min_y..=max_y).map(move |y| Point2::new(x, y)))
} else {
let m = (end.y - start.y) / (end.x - start.x);
if m.abs() == 1 && !include_diagonal {
return Box::new(empty());
}
let xrange = if start.x < end.x {
start.x..=end.x
} else {
end.x..=start.x
};
let b = start.y - m * start.x;
Box::new(xrange.map(move |x| Point2::new(x, m * x + b)))
}
}
fn evaluate_lines(include_diagonal: bool) -> usize {
let mut points = HashMap::new();
for line in INPUT.lines() {
let mut pairs = line.split(" -> ");
let start = make_point(pairs.next().unwrap());
let end = make_point(pairs.next().unwrap());
for point in generate_points_on_line_segment(&start, &end, include_diagonal) {
points
.entry(point)
.and_modify(|count| *count += 1)
.or_insert(1);
}
}
points.into_iter().filter(|(_, count)| *count >= 2).count()
}
fn part1() -> usize {
evaluate_lines(false)
}
fn part2() -> usize {
evaluate_lines(true)
}
fn main() {
let start = Instant::now();
println!("part 1: {}", part1());
println!("part 1 took {}ms", (Instant::now() - start).as_millis());
let start = Instant::now();
println!("part 2: {}", part2());
println!("part 2 took {}ms", (Instant::now() - start).as_millis());
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_part1() {
assert_eq!(part1(), 7380);
}
#[test]
fn test_part2() {
assert_eq!(part2(), 21373);
}
}
|
extern crate proc_macro;
mod debug_with;
#[proc_macro_derive(DebugWith)]
pub fn derive_debug_with(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
// Parse the input tokens into a syntax tree.
let input = syn::parse_macro_input!(input as syn::DeriveInput);
// Used in the quasi-quotation below as `#name`.
let name = &input.ident;
// Generate an expression to sum up the heap size of each field.
let debug_with = debug_with::debug_with(&input);
let generics = debug_with::add_trait_bounds(input.generics);
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
let expanded = quote::quote! {
// The generated impl.
impl #impl_generics ::valis_ds::DebugWith for #name #ty_generics #where_clause {
fn fmt_with<Cx: ?Sized>(&self, cx: &Cx, fmt: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
#debug_with
}
}
};
if std::env::var("VALIS_DEBUG_DERIVE").is_ok() {
eprintln!("expanded = {}", expanded);
}
// Hand the output tokens back to the compiler.
proc_macro::TokenStream::from(expanded)
}
|
use crate::config::rule::Modifier;
use crate::error::MatcherError;
use log::*;
use tornado_common_api::Value;
pub mod lowercase;
pub mod replace;
pub mod trim;
#[derive(Debug, PartialEq)]
pub enum ValueModifier {
Lowercase,
ReplaceAll { find: String, replace: String },
Trim,
}
impl ValueModifier {
pub fn build(
_rule_name: &str,
modifiers: &[Modifier],
) -> Result<Vec<ValueModifier>, MatcherError> {
let mut value_modifiers = vec![];
for modifier in modifiers {
match modifier {
Modifier::Lowercase {} => {
trace!("Add post modifier to extractor: lowercase");
value_modifiers.push(ValueModifier::Lowercase);
}
Modifier::ReplaceAll { find, replace } => {
trace!("Add post modifier to extractor: replace");
value_modifiers.push(ValueModifier::ReplaceAll {
find: find.clone(),
replace: replace.clone(),
});
}
Modifier::Trim {} => {
trace!("Add post modifier to extractor: trim");
value_modifiers.push(ValueModifier::Trim);
}
}
}
Ok(value_modifiers)
}
pub fn apply(&self, variable_name: &str, value: &mut Value) -> Result<(), MatcherError> {
match self {
ValueModifier::Lowercase => lowercase::lowercase(variable_name, value),
ValueModifier::ReplaceAll { find, replace } => {
replace::replace_all(variable_name, value, find, replace)
}
ValueModifier::Trim => trim::trim(variable_name, value),
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn should_build_empty_value_modifiers() {
// Arrange
let modifiers = vec![];
// Act
let value_modifiers = ValueModifier::build("", &modifiers).unwrap();
// Assert
assert!(value_modifiers.is_empty());
}
#[test]
fn should_build_trim_value_modifiers() {
// Arrange
let modifiers = vec![Modifier::Trim {}, Modifier::Trim {}];
let expected_value_modifiers = vec![ValueModifier::Trim, ValueModifier::Trim];
// Act
let value_modifiers = ValueModifier::build("", &modifiers).unwrap();
// Assert
assert_eq!(2, value_modifiers.len());
assert_eq!(expected_value_modifiers, value_modifiers);
}
#[test]
fn should_build_lowercase_value_modifiers() {
// Arrange
let modifiers = vec![Modifier::Lowercase {}, Modifier::Trim {}];
let expected_value_modifiers = vec![ValueModifier::Lowercase, ValueModifier::Trim];
// Act
let value_modifiers = ValueModifier::build("", &modifiers).unwrap();
// Assert
assert_eq!(2, value_modifiers.len());
assert_eq!(expected_value_modifiers, value_modifiers);
}
#[test]
fn trim_modifier_should_trim_a_string() {
// Arrange
let value_modifier = ValueModifier::Trim;
// Act & Assert
{
let mut input = Value::Text("".to_owned());
value_modifier.apply("", &mut input).unwrap();
assert_eq!(Value::Text("".to_owned()), input);
}
{
let mut input = Value::Text("not to trim".to_owned());
value_modifier.apply("", &mut input).unwrap();
assert_eq!(Value::Text("not to trim".to_owned()), input);
}
{
let mut input = Value::Text(" to be trimmed ".to_owned());
value_modifier.apply("", &mut input).unwrap();
assert_eq!(Value::Text("to be trimmed".to_owned()), input);
}
}
#[test]
fn lowercase_modifier_should_lowercase_a_string() {
// Arrange
let value_modifier = ValueModifier::Lowercase;
// Act & Assert
{
let mut input = Value::Text("".to_owned());
value_modifier.apply("", &mut input).unwrap();
assert_eq!(Value::Text("".to_owned()), input);
}
{
let mut input = Value::Text("ok".to_owned());
value_modifier.apply("", &mut input).unwrap();
assert_eq!(Value::Text("ok".to_owned()), input);
}
{
let mut input = Value::Text("OK".to_owned());
value_modifier.apply("", &mut input).unwrap();
assert_eq!(Value::Text("ok".to_owned()), input);
}
}
#[test]
fn replace_modifier_should_replace_a_string() {
// Arrange
let value_modifier =
ValueModifier::ReplaceAll { find: "Hello".to_owned(), replace: "World".to_owned() };
// Act & Assert
{
let mut input = Value::Text("Hello World".to_owned());
value_modifier.apply("", &mut input).unwrap();
assert_eq!(Value::Text("World World".to_owned()), input);
}
}
}
|
#[doc = "Register `APB1RSTR1` reader"]
pub type R = crate::R<APB1RSTR1_SPEC>;
#[doc = "Register `APB1RSTR1` writer"]
pub type W = crate::W<APB1RSTR1_SPEC>;
#[doc = "Field `TIM2RST` reader - TIM2 timer reset"]
pub type TIM2RST_R = crate::BitReader<TIM2RST_A>;
#[doc = "TIM2 timer reset\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TIM2RST_A {
#[doc = "0: No effect"]
NoReset = 0,
#[doc = "1: Reset peripheral"]
Reset = 1,
}
impl From<TIM2RST_A> for bool {
#[inline(always)]
fn from(variant: TIM2RST_A) -> Self {
variant as u8 != 0
}
}
impl TIM2RST_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TIM2RST_A {
match self.bits {
false => TIM2RST_A::NoReset,
true => TIM2RST_A::Reset,
}
}
#[doc = "No effect"]
#[inline(always)]
pub fn is_no_reset(&self) -> bool {
*self == TIM2RST_A::NoReset
}
#[doc = "Reset peripheral"]
#[inline(always)]
pub fn is_reset(&self) -> bool {
*self == TIM2RST_A::Reset
}
}
#[doc = "Field `TIM2RST` writer - TIM2 timer reset"]
pub type TIM2RST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, TIM2RST_A>;
impl<'a, REG, const O: u8> TIM2RST_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "No effect"]
#[inline(always)]
pub fn no_reset(self) -> &'a mut crate::W<REG> {
self.variant(TIM2RST_A::NoReset)
}
#[doc = "Reset peripheral"]
#[inline(always)]
pub fn reset(self) -> &'a mut crate::W<REG> {
self.variant(TIM2RST_A::Reset)
}
}
#[doc = "Field `SPI2S2RST` reader - SPI2S2 reset"]
pub use TIM2RST_R as SPI2S2RST_R;
#[doc = "Field `USART2RST` reader - USART2 reset"]
pub use TIM2RST_R as USART2RST_R;
#[doc = "Field `I2C1RST` reader - I2C1 reset"]
pub use TIM2RST_R as I2C1RST_R;
#[doc = "Field `I2C2RST` reader - I2C2 reset"]
pub use TIM2RST_R as I2C2RST_R;
#[doc = "Field `I2C3RST` reader - I2C3 reset"]
pub use TIM2RST_R as I2C3RST_R;
#[doc = "Field `DACRST` reader - DAC1 reset"]
pub use TIM2RST_R as DACRST_R;
#[doc = "Field `LPTIM1RST` reader - Low Power Timer 1 reset"]
pub use TIM2RST_R as LPTIM1RST_R;
#[doc = "Field `SPI2S2RST` writer - SPI2S2 reset"]
pub use TIM2RST_W as SPI2S2RST_W;
#[doc = "Field `USART2RST` writer - USART2 reset"]
pub use TIM2RST_W as USART2RST_W;
#[doc = "Field `I2C1RST` writer - I2C1 reset"]
pub use TIM2RST_W as I2C1RST_W;
#[doc = "Field `I2C2RST` writer - I2C2 reset"]
pub use TIM2RST_W as I2C2RST_W;
#[doc = "Field `I2C3RST` writer - I2C3 reset"]
pub use TIM2RST_W as I2C3RST_W;
#[doc = "Field `DACRST` writer - DAC1 reset"]
pub use TIM2RST_W as DACRST_W;
#[doc = "Field `LPTIM1RST` writer - Low Power Timer 1 reset"]
pub use TIM2RST_W as LPTIM1RST_W;
impl R {
#[doc = "Bit 0 - TIM2 timer reset"]
#[inline(always)]
pub fn tim2rst(&self) -> TIM2RST_R {
TIM2RST_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 14 - SPI2S2 reset"]
#[inline(always)]
pub fn spi2s2rst(&self) -> SPI2S2RST_R {
SPI2S2RST_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bit 17 - USART2 reset"]
#[inline(always)]
pub fn usart2rst(&self) -> USART2RST_R {
USART2RST_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bit 21 - I2C1 reset"]
#[inline(always)]
pub fn i2c1rst(&self) -> I2C1RST_R {
I2C1RST_R::new(((self.bits >> 21) & 1) != 0)
}
#[doc = "Bit 22 - I2C2 reset"]
#[inline(always)]
pub fn i2c2rst(&self) -> I2C2RST_R {
I2C2RST_R::new(((self.bits >> 22) & 1) != 0)
}
#[doc = "Bit 23 - I2C3 reset"]
#[inline(always)]
pub fn i2c3rst(&self) -> I2C3RST_R {
I2C3RST_R::new(((self.bits >> 23) & 1) != 0)
}
#[doc = "Bit 29 - DAC1 reset"]
#[inline(always)]
pub fn dacrst(&self) -> DACRST_R {
DACRST_R::new(((self.bits >> 29) & 1) != 0)
}
#[doc = "Bit 31 - Low Power Timer 1 reset"]
#[inline(always)]
pub fn lptim1rst(&self) -> LPTIM1RST_R {
LPTIM1RST_R::new(((self.bits >> 31) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - TIM2 timer reset"]
#[inline(always)]
#[must_use]
pub fn tim2rst(&mut self) -> TIM2RST_W<APB1RSTR1_SPEC, 0> {
TIM2RST_W::new(self)
}
#[doc = "Bit 14 - SPI2S2 reset"]
#[inline(always)]
#[must_use]
pub fn spi2s2rst(&mut self) -> SPI2S2RST_W<APB1RSTR1_SPEC, 14> {
SPI2S2RST_W::new(self)
}
#[doc = "Bit 17 - USART2 reset"]
#[inline(always)]
#[must_use]
pub fn usart2rst(&mut self) -> USART2RST_W<APB1RSTR1_SPEC, 17> {
USART2RST_W::new(self)
}
#[doc = "Bit 21 - I2C1 reset"]
#[inline(always)]
#[must_use]
pub fn i2c1rst(&mut self) -> I2C1RST_W<APB1RSTR1_SPEC, 21> {
I2C1RST_W::new(self)
}
#[doc = "Bit 22 - I2C2 reset"]
#[inline(always)]
#[must_use]
pub fn i2c2rst(&mut self) -> I2C2RST_W<APB1RSTR1_SPEC, 22> {
I2C2RST_W::new(self)
}
#[doc = "Bit 23 - I2C3 reset"]
#[inline(always)]
#[must_use]
pub fn i2c3rst(&mut self) -> I2C3RST_W<APB1RSTR1_SPEC, 23> {
I2C3RST_W::new(self)
}
#[doc = "Bit 29 - DAC1 reset"]
#[inline(always)]
#[must_use]
pub fn dacrst(&mut self) -> DACRST_W<APB1RSTR1_SPEC, 29> {
DACRST_W::new(self)
}
#[doc = "Bit 31 - Low Power Timer 1 reset"]
#[inline(always)]
#[must_use]
pub fn lptim1rst(&mut self) -> LPTIM1RST_W<APB1RSTR1_SPEC, 31> {
LPTIM1RST_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "APB1 peripheral reset register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb1rstr1::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`apb1rstr1::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct APB1RSTR1_SPEC;
impl crate::RegisterSpec for APB1RSTR1_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`apb1rstr1::R`](R) reader structure"]
impl crate::Readable for APB1RSTR1_SPEC {}
#[doc = "`write(|w| ..)` method takes [`apb1rstr1::W`](W) writer structure"]
impl crate::Writable for APB1RSTR1_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets APB1RSTR1 to value 0"]
impl crate::Resettable for APB1RSTR1_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use super::constants::*;
use crate::constants::*;
use crate::engine::{
input::GameInput,
ui::{view, UIComponent, ViewAttr::*, ViewBuilder},
};
use sdl2::{keyboard::Keycode, render::Canvas, video::Window};
use std::{collections::HashMap, path::Path};
const game_dir: &str = "~/personal/rust/game/";
const game_config_fn: &str = "gameconfig.json";
#[derive(Debug, Copy, Clone)]
pub struct EditorProps {
entity_select_open: bool,
}
impl Default for EditorProps {
fn default() -> Self {
Self {
entity_select_open: true
}
}
}
pub enum EditorActions {
OpenEntitySelect,
Up,
Down
}
pub struct Editor {
pub ui: UIComponent<EditorProps, EditorActions>,
}
fn entity_select() -> ViewBuilder {
view().attr(FlexGrow(1.0)).attr(BgColorRGB(255, 0, 0))
}
impl Editor {
pub fn new() -> Self {
Self {
ui: UIComponent::new(
EditorProps::default(),
|props, actions| match actions {
EditorActions::OpenEntitySelect => {
props.entity_select_open = !props.entity_select_open
},
EditorActions::Up => {
},
EditorActions::Down => {
}
},
|props| {
let mut root = view()
.attr(WidthPx(SCREEN_WIDTH as f32))
.attr(HeightPx(SCREEN_HEIGHT as f32));
if props.entity_select_open {
root.child(entity_select());
}
root
},
),
}
}
pub fn update(&mut self, inputs: Vec<GameInput>) {
for input in inputs.iter() {
match input {
GameInput::Other(kc) => match kc {
Keycode::F1 => self.ui.dispatch(EditorActions::OpenEntitySelect),
_ => {}
},
_ => {}
}
}
}
}
|
use log::info;
use std::time::Duration;
use tokio::sync::mpsc::Sender;
use tokio::timer::Interval;
use crate::fetcher;
use crate::{Configuration, Messages};
pub async fn run_iterations(config: Configuration, sender: Sender<Messages>) {
let mut iteration: usize = 0;
let mut interval = Interval::new_interval(Duration::from_millis(config.interval_between_fetch));
let mut sender = sender.clone();
let websites = config
.websites
.iter()
.map(|site| reqwest::Url::parse(site).expect("Url should be valid !"))
.collect();
sender.send(Messages::StartIteration).await.unwrap();
while config.run_forever || iteration <= config.stop_after_iteration {
info!("[iteration:{}] Starting to fetch websites...", iteration);
fetcher::fetch_all_websites(&config, &websites, sender.clone()).await;
info!("[iteration:{}] Fetching finished", iteration);
iteration += 1;
interval.next().await;
}
sender.send(Messages::EndIteration).await.unwrap();
}
|
use super::identifier::*;
use super::MatrixErrorBody;
use actix_web::{
get, post,
web::{HttpResponse, Json},
Responder,
};
use serde::{Deserialize, Serialize};
/// Represents the list of login flows returned by the serve_login_types endpoint
#[derive(Serialize)]
struct LoginFlow<'a> {
flows: [LoginType<'a>; 2],
}
const LOGIN_FLOWS: LoginFlow = LoginFlow {
flows: [
LoginType::new("m.login.password"),
LoginType::new("m.login.token"),
],
};
/// Represents a login type on the list returned by the serve_login_types endpoint
#[derive(Serialize)]
struct LoginType<'a> {
r#type: &'a str,
}
impl<'a> LoginType<'a> {
pub const fn new(r#type: &'a str) -> Self {
Self { r#type }
}
}
#[derive(Serialize)]
struct LoginRateLimitedBody<'a> {
errcode: &'a str,
error: &'a str,
retry_after_ms: u32,
}
/// Gives the different login flows that are supported by the server
#[get("/_matrix/client/r0/login")]
pub async fn serve_login_types() -> HttpResponse {
// TODO: Supposed to be a rate-limited endpoint
HttpResponse::Ok().json(LOGIN_FLOWS)
}
/// On an auth request, the client sends this request in JSON format, wich we can parse using this struct
#[derive(Deserialize)]
struct AuthRequestBody {
r#type: String,
identifier: UserIdentifier,
user: Option<String>,
medium: Option<String>,
address: Option<String>,
password: Option<String>,
token: Option<String>,
device_id: Option<String>,
initial_device_display_name: Option<String>,
}
// TODO: AUTH
#[post("/_matrix/client/r0/login")]
pub async fn auth(request_body: Json<AuthRequestBody>) -> impl Responder {
let response = match decode_identifier_type(&request_body.identifier) {
IdentifierType::MIdUser(identifier) => {
format!("MIdUser !")
}
IdentifierType::MIdThirdparty(identifier) => {
format!("MId3rd !")
}
IdentifierType::MIdPhone(identifier) => {
format!("MIdPhone !")
}
IdentifierType::None => format!("fail !"), /*HttpResponse::BadRequest().json(MatrixErrorBody {
errcode: "M_UNKNOWN",
error: "Bad login type.",
})*/
};
response
}
#[post("/_matrix/client/r0/logout")]
pub async fn logout() -> impl Responder {
format!("salut")
}
#[post("/_matrix/client/r0/logout/all")]
pub async fn logout_all() -> impl Responder {
format!("salut")
}
|
extern crate ctest;
use std::env;
use std::path::PathBuf;
fn main() {
let root = PathBuf::from(env::var_os("DEP_JEMALLOC_ROOT").unwrap());
let mut cfg = ctest::TestGenerator::new();
cfg.header("jemalloc/jemalloc.h")
.include(root.join("include"))
.fn_cname(|rust, link_name| link_name.unwrap_or(rust).to_string());
if cfg!(target_os = "linux") {
cfg.skip_fn(|f| f == "malloc_usable_size");
}
cfg.generate("../jemalloc-sys/src/lib.rs", "all.rs");
}
|
use libc::{c_int, c_longlong, c_uint, c_ulonglong, c_void, size_t};
pub type herr_t = c_int;
pub type htri_t = c_int;
pub type hsize_t = c_ulonglong;
pub type hssize_t = c_longlong;
pub type hbool_t = c_uint;
#[cfg(target_pointer_width = "32")]
pub type haddr_t = u32;
#[cfg(target_pointer_width = "64")]
pub type haddr_t = u64;
#[derive(Clone, Copy, Debug)]
#[repr(C)]
pub enum H5_iter_order_t {
H5_ITER_UNKNOWN = -1,
H5_ITER_INC,
H5_ITER_DEC,
H5_ITER_NATIVE,
H5_ITER_N,
}
pub use self::H5_iter_order_t::*;
#[derive(Clone, Copy, Debug)]
#[repr(C)]
pub enum H5_index_t {
H5_INDEX_UNKNOWN = -1,
H5_INDEX_NAME,
H5_INDEX_CRT_ORDER,
H5_INDEX_N,
}
pub use self::H5_index_t::*;
#[derive(Debug)]
#[repr(C)]
pub struct H5_ih_info_t {
pub index_size: hsize_t,
pub heap_size: hsize_t,
}
extern "C" {
pub fn H5open() -> herr_t;
pub fn H5dont_atexit() -> herr_t;
pub fn H5set_free_list_limits(reg_global_lim: c_int, reg_list_lim: c_int,
arr_global_lim: c_int, arr_list_lim: c_int,
blk_global_lim: c_int, blk_list_lim: c_int) -> herr_t;
pub fn H5garbage_collect() -> herr_t;
pub fn H5allocate_memory(size: size_t, clear: hbool_t) -> *mut c_void;
pub fn H5resize_memory(mem: *mut c_void, size: size_t ) -> *mut c_void;
pub fn H5free_memory(buf: *mut c_void) -> herr_t;
pub fn H5get_libversion(majnum: *mut c_uint, minnum: *mut c_uint, relnum: *mut c_uint)
-> herr_t;
pub fn H5check_version(majnum: c_uint, minnum: c_uint, relnum: c_uint) -> herr_t;
pub fn H5is_library_threadsafe(is_ts: *mut hbool_t) -> herr_t;
}
|
use async_metronome::{assert_tick, await_tick};
use futures::{channel::mpsc, SinkExt, StreamExt};
#[async_metronome::test]
async fn test_send_receive() {
let (mut sender, mut receiver) = mpsc::channel::<usize>(1);
let sender = async move {
assert_tick!(0);
sender.send(42).await.unwrap();
sender.send(17).await.unwrap();
assert_tick!(1);
};
let receiver = async move {
assert_tick!(0);
await_tick!(1);
receiver.next().await;
receiver.next().await;
};
let sender = async_metronome::spawn(sender);
let receiver = async_metronome::spawn(receiver);
sender.await;
receiver.await;
}
|
use std::env;
use std::fs::File;
use std::io::{self, BufRead, BufReader, BufWriter, Write};
use glob::{ GlobResult, glob };
mod graph;
use graph::*;
fn main() -> Result<(), Box<dyn std::error::Error>>{
let mut args = env::args();
args.next().unwrap();
let output_path = args.next().unwrap();
let mut graph = Graph::new();
let omega_glob = args
.fold(Box::new(std::iter::empty()) as Box<dyn Iterator<Item=GlobResult>>, |acc, mut p| {
println!("Visiting: {}", p);
p.push_str("*");
let mini_glob = glob(&p).unwrap();
Box::new(acc.chain(mini_glob))
});
for glob_res in omega_glob {
let path = glob_res?;
let string_path = path.to_str().expect("Input path not utf8").to_string();
let (_, _, ext) = get_data(&string_path);
if !path.is_file() {
continue
}
let file = File::open(path)?;
let mut reader = BufReader::new(file);
if ext == ".js" || ext == ".ts" || ext == ".arr.ts" || ext == ".arr.js" {
let canon_path = canon_require_path(&string_path);
generate_from_js(&mut graph, &canon_path, &mut reader)?;
} else if ext == ".arr" {
let canon_path = canon_require_path(&string_path);
generate_from_pyret(&mut graph, &canon_path, &mut reader)?;
} else if ext == ".arr.json" || ext == ".json" || ext.contains("swp") || ext.contains("stopped") {
continue;
} else {
panic!("Unknown top-level extension: \"{}\" [{}]", ext, string_path);
}
}
println!("Finished reading inputs...");
println!("Writing results to {}", output_path);
let output_file = File::create(&output_path)?;
let mut writer = BufWriter::new(output_file);
writer.write("digraph mygraph {\n".as_bytes())?;
graph.write_graph(&mut writer)?;
writer.write("\n}".as_bytes())?;
Ok(())
}
fn generate_from_pyret<T: BufRead>(graph: &mut Graph, current: &str, input: &mut T) -> io::Result<()> {
for line in input.lines() {
let line = line?;
if let Some(to) = locate_dep(&line) {
graph.add_edge(current, to);
}
}
Ok(())
}
fn locate_dep(input: &str) -> Option<String> {
if input.starts_with("include ") {
let input = &input[8..];
if !input.starts_with("from") {
return Some(strip_protocol_dep(input));
}
}
if input.starts_with("import ") {
let input = &input[7..];
let end = input.find(" as ").unwrap();
let input = &input[..end];
return Some(strip_protocol_dep(input));
}
None
}
fn strip_protocol_dep(input: &str) -> String {
if let Some(file_index) = input.find("file(\"") {
let input = &input[file_index + 6..];
let end = input.find("\"").unwrap();
let input = &input[..end];
return canon_require_path(input);
}
if let Some(file_index) = input.find("jsfile(\"") {
let input = &input[file_index + 8..];
let end = input.find("\"").unwrap();
let input = &input[..end];
return canon_require_path(input);
}
input.to_string()
}
fn generate_from_js<T: BufRead>(graph: &mut Graph, current: &str, input: &mut T) -> io::Result<()> {
for line in input.lines() {
let line = line?;
if let Some(to) = locate_requires(&line) {
let to = canon_require_path(&to);
graph.add_edge(current, to);
}
}
Ok(())
}
fn canon_require_path(input: &str) -> String {
let mut result = String::new();
let ( file_name, file_stem, ext ) = get_data(input);
if ext == ".arr.js" || ext == ".arr"|| ext == ".arr.ts" {
result.push_str(file_stem);
} else if ext == ".js" || ext == ".ts" {
result.push_str(file_name);
} else if ext == "" {
result.push_str(file_name);
} else {
panic!("Unable to handle extension: \"{}\" [{}]", ext, input);
}
result
}
fn get_data(input: &str) -> ( &str, &str, &str ) {
let file_name_index = match input.rfind("/") {
Some(i) => i + 1,
None => 0
};
let file_name = &input[file_name_index..];
let (file_stem, ext) = match file_name.find(".") {
Some(first_dot_index) => {
let ext = &file_name[first_dot_index..];
let file_stem = &file_name[..first_dot_index];
(file_stem, ext)
}
None => {
(file_name, "")
}
};
( file_name, file_stem, ext )
}
fn locate_requires(input: &str) -> Option<String> {
if let Some(require_index) = input.find("require(\"") {
let start = require_index + 9;
let target = &input[start..];
let end = target.find("\"").unwrap();
return Some((&target[..end]).to_owned());
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_locate_requires() {
assert_eq!(locate_requires("require(\"foo/bar\")"), Some("foo/bar".to_string()));
}
#[test]
fn test_canon_path() {
assert_eq!(canon_require_path("foo/bar.arr.js"), "bar");
assert_eq!(canon_require_path("foo/bar.js"), "bar.js");
assert_eq!(canon_require_path("foo/bar.ts"), "bar.ts");
assert_eq!(canon_require_path("foo/bar.arr"), "bar");
}
#[test]
fn test_locate_dep() {
assert_eq!(locate_dep("include from global"), None);
assert_eq!(locate_dep("include global"), Some("global".to_string()));
assert_eq!(locate_dep("include file(\"foo/global.arr\")"), Some("global".to_string()));
assert_eq!(locate_dep("import file(\"foo/global.arr\") as G"), Some("global".to_string()));
assert_eq!(locate_dep("import global as G"), Some("global".to_string()));
}
}
|
//! Executable for working with .sdc files.
extern crate docopt;
extern crate rustc_serialize;
extern crate sdc;
use std::process::exit;
use docopt::Docopt;
use sdc::{Reader, Version};
const USAGE: &'static str = "
Work with .sdc files.
Usage:
sdc info <infile> [--brief]
\
sdc (--help | --version)
Options:
-h --help Show this \
screen.
--version Show version.
--brief Only \
display information from the header.
";
#[derive(Debug, RustcDecodable)]
struct Args {
arg_infile: String,
flag_brief: bool,
flag_help: bool,
flag_version: bool,
cmd_info: bool,
}
fn main() {
let args: Args = Docopt::new(USAGE)
.and_then(|d| {
d.version(Some(env!("CARGO_PKG_VERSION").to_string()))
.help(true)
.decode()
})
.unwrap_or_else(|e| e.exit());
if args.cmd_info {
let reader = match Reader::from_path(&args.arg_infile) {
Ok(reader) => reader,
Err(err) => {
println!("ERROR: unable to create reader for {}: {}",
args.arg_infile,
err);
exit(1);
}
};
let Version {major, minor} = reader.version();
println!("version: {}.{}", major, minor);
match reader.header_information_as_str() {
Ok(info) => println!("header information:\n{}", info),
Err(err) => println!("WARNING: cannot display header information: {}", err),
}
if !args.flag_brief {
let points: Vec<_> = reader.into_iter().collect();
println!("number of points: {}", points.len());
}
exit(0);
}
unreachable!()
}
|
use crate::preset;
use crate::layer;
use crate::output;
use std::io::prelude::*;
use std::net::TcpStream;
use std::{thread,time};
#[derive(Debug)]
enum Command {
DiVentix(String),
DelayMS(u64),
}
#[derive(Debug)]
pub struct Cmd {
cmds: Vec<Command>,
}
impl Cmd {
pub fn new() -> Cmd {
Cmd {
cmds: Vec::new(),
}
}
fn sleep_delay(delay: u64) {
if delay > 0 {
let ms = time::Duration::from_millis(delay);
thread::sleep(ms);
}
}
pub fn delay(mut self, delay: u64) -> Self {
self.cmds.push(Command::DelayMS(delay));
self
}
pub fn preset(mut self, layout: preset::Layout) -> Self {
for cmd in preset::layout(layout).drain(..) {
self.cmds.push(Command::DiVentix(cmd));
}
self
}
pub fn layer(mut self, layer: layer::Layer, action: layer::Action) -> Self {
for cmd in layer::layer(layer, action).drain(..) {
self.cmds.push(Command::DiVentix(cmd));
}
self
}
pub fn output(mut self, port: output::Port, action: output::Action) -> Self {
for cmd in output::output(port, action).drain(..) {
self.cmds.push(Command::DiVentix(cmd));
}
self
}
fn write(conn: &mut TcpStream, cmd: String) -> Result<(), std::io::Error> {
conn.write(cmd.as_bytes())?;
let mut buf = vec![0u8; 128];
let response = conn.read(&mut buf)?;
println!("Response: {:?}: {}", response, String::from_utf8_lossy(&buf));
Ok(())
}
pub fn send(&mut self, conn: &mut TcpStream) -> Result<(), std::io::Error> {
for cmd in self.cmds.drain(..) {
match cmd {
Command::DiVentix(c) => { Cmd::write(conn, c)?; },
Command::DelayMS(d) => { Cmd::sleep_delay(d); },
}
}
Ok(())
}
}
|
//! ## Data for the [`Pet Control` component](https://docs.lu-dev.net/en/latest/components/034-pet-control.html)
use serde::{Deserialize, Serialize};
/// Data for the [`Pet Control` component](https://docs.lu-dev.net/en/latest/components/034-pet-control.html)
#[derive(Default, Debug, PartialEq, Deserialize, Serialize)]
pub struct Pets {
/// List of pets
#[serde(default, rename = "p")]
pub children: Vec<Pet>,
}
/// A single pet
#[derive(Default, Debug, PartialEq, Deserialize, Serialize)]
pub struct Pet {
/// Pet ObjectID
pub id: u64,
/// Pet template (LOT)
#[serde(rename = "l")]
pub lot: u32,
/// Moderation status (?)
#[serde(rename = "m")]
pub moderation_status: u8,
/// Name of the pet
#[serde(rename = "n")]
pub name: String,
/// ???
pub t: u8,
}
|
#![deny(warnings)]
#[macro_use]
extern crate warp;
use warp::Filter;
fn main() {
let route_home = warp::filters::path::end()
.map(|| "home");
let route_info = warp::path("info")
.map(|| "info");
let cors = warp::cors()
.allow_any_origin()
.allow_method("post")
.allow_method("get")
.allow_header("content-type");
let route_post = warp::path("post")
.and(warp::post2())
.map(|| "endpoint")
.with(cors.clone())
.boxed();
let api_a = path!("api" / "a")
.map(|| "a");
let api_b = path!("api" / "b")
.and(warp::post2())
.map(|| "b")
.with(cors)
.boxed();
let api = api_a.or(api_b);
let routes = route_home
.or(api)
.or(route_info)
.or(route_post);
warp::serve(routes).run(([127, 0, 0, 1], 3030));
}
|
use crossterm::event::{self, Event as CEvent, KeyEvent};
use std::{convert::TryInto, io::{Stdout}, sync::mpsc::Sender, thread, time::{Duration, Instant}};
use tui::{Frame, backend::CrosstermBackend, layout::{Constraint, Direction, Layout}, style::{Color, Modifier, Style}, widgets::{Block, Borders, List, ListItem}};
use strum::IntoEnumIterator;
use super::{app::App, dice::Dice};
pub enum Event<I> {
Input(I),
Tick,
}
// Can this be more generic?
pub fn draw(f: &mut Frame<CrosstermBackend<Stdout>>, app: &mut App) {
let chunks = Layout::default()
.direction(Direction::Horizontal)
.margin(2)
.constraints([Constraint::Percentage(20), Constraint::Percentage(50)].as_ref())
.split(f.size());
let items: Vec<tui::widgets::ListItem> =
Dice::iter().map(|d| ListItem::new(d.to_string().to_ascii_lowercase())).collect();
let block = Block::default().title("Dice").borders(Borders::ALL);
let list = List::new(items)
.block(block)
.highlight_style(
Style::default()
.bg(Color::LightGreen)
.add_modifier(Modifier::BOLD),
)
.highlight_symbol(">> ");
f.render_stateful_widget(list, chunks[0], &mut app.items.state);
// f.render_widget(block, chunks[0]);
let block = Block::default().title("Rolled Values").borders(Borders::ALL);
let event_items: Vec<tui::widgets::ListItem> = app.events.iter().map(|i| {
ListItem::new(i.to_string())
}).collect();
// I think this is -2 because of the margin.
let height = chunks[1].height - 2;
let list = if event_items.len() > 0 {
let can_fit_x_items: u16 = (height as usize / event_items[0].height()).try_into().unwrap();
if can_fit_x_items < event_items.len() as u16 {
let sliding_frame_index: usize = event_items.len() - can_fit_x_items as usize;
List::new(event_items.get(sliding_frame_index..).unwrap()).block(block)
} else {
List::new(event_items).block(block)
}
} else {
List::new(event_items).block(block)
};
f.render_widget(list, chunks[1]);
}
pub fn initialize_ui_thread(tx: Sender<Event<KeyEvent>>) {
let tick_rate = Duration::from_millis(250);
thread::spawn(move || {
let mut last_tick = Instant::now();
loop {
// poll for tick rate duration, if no events, sent tick event.
let timeout = tick_rate
.checked_sub(last_tick.elapsed())
.unwrap_or_else(|| Duration::from_secs(0));
if event::poll(timeout).unwrap() {
if let CEvent::Key(key) = event::read().unwrap() {
tx.send(Event::Input(key)).unwrap();
}
}
if last_tick.elapsed() >= tick_rate {
tx.send(Event::Tick).unwrap();
last_tick = Instant::now();
}
}
});
} |
/*
* Copyright 2020 Damian Peckett <damian@pecke.tt>
*
* 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 snafu::Snafu;
/// Pangolin error types.
#[derive(Debug, Snafu)]
#[snafu(visibility = "pub(crate)")]
pub enum Error {
/// General HTTP client errors.
#[snafu(display("http client error: {}", source))]
HttpClient { source: reqwest::Error },
/// JSON serialization errors.
#[snafu(display("json serialization error: {}", source))]
JsonSerialization { source: serde_json::Error },
/// Kubernetes API related errors.
#[snafu(display("kubernetes error: {}", source))]
Kube { source: kube::Error },
/// Kubernetes specification errors.
#[snafu(display("kubernetes spec is missing fields"))]
KubeSpec {},
}
|
use fake::{Dummy, Fake};
use serde::{Deserialize, Serialize};
pub mod api;
pub mod db;
#[derive(Debug, Dummy, Clone, PartialEq, Serialize, Deserialize)]
pub struct Entry {
pub id: Option<i32>,
pub start: String,
pub stop: String,
pub week_day: String,
pub code: String,
pub memo: String,
}
#[derive(Debug, Dummy, Clone, PartialEq, Serialize, Deserialize)]
pub struct Project {
pub id: Option<i32>,
pub name: String,
pub code: String,
}
|
#[doc = "Register `PDCRD` reader"]
pub type R = crate::R<PDCRD_SPEC>;
#[doc = "Register `PDCRD` writer"]
pub type W = crate::W<PDCRD_SPEC>;
#[doc = "Field `PD0` reader - Port D pull-down bit i (i = 3 to 0) Setting PDi bit while the APC bit of the PWR_CR3 register is set activates a pull-down device on the PD\\[i\\]
I/O."]
pub type PD0_R = crate::BitReader;
#[doc = "Field `PD0` writer - Port D pull-down bit i (i = 3 to 0) Setting PDi bit while the APC bit of the PWR_CR3 register is set activates a pull-down device on the PD\\[i\\]
I/O."]
pub type PD0_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PD1` reader - Port D pull-down bit i (i = 3 to 0) Setting PDi bit while the APC bit of the PWR_CR3 register is set activates a pull-down device on the PD\\[i\\]
I/O."]
pub type PD1_R = crate::BitReader;
#[doc = "Field `PD1` writer - Port D pull-down bit i (i = 3 to 0) Setting PDi bit while the APC bit of the PWR_CR3 register is set activates a pull-down device on the PD\\[i\\]
I/O."]
pub type PD1_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PD2` reader - Port D pull-down bit i (i = 3 to 0) Setting PDi bit while the APC bit of the PWR_CR3 register is set activates a pull-down device on the PD\\[i\\]
I/O."]
pub type PD2_R = crate::BitReader;
#[doc = "Field `PD2` writer - Port D pull-down bit i (i = 3 to 0) Setting PDi bit while the APC bit of the PWR_CR3 register is set activates a pull-down device on the PD\\[i\\]
I/O."]
pub type PD2_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PD3` reader - Port D pull-down bit i (i = 3 to 0) Setting PDi bit while the APC bit of the PWR_CR3 register is set activates a pull-down device on the PD\\[i\\]
I/O."]
pub type PD3_R = crate::BitReader;
#[doc = "Field `PD3` writer - Port D pull-down bit i (i = 3 to 0) Setting PDi bit while the APC bit of the PWR_CR3 register is set activates a pull-down device on the PD\\[i\\]
I/O."]
pub type PD3_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - Port D pull-down bit i (i = 3 to 0) Setting PDi bit while the APC bit of the PWR_CR3 register is set activates a pull-down device on the PD\\[i\\]
I/O."]
#[inline(always)]
pub fn pd0(&self) -> PD0_R {
PD0_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - Port D pull-down bit i (i = 3 to 0) Setting PDi bit while the APC bit of the PWR_CR3 register is set activates a pull-down device on the PD\\[i\\]
I/O."]
#[inline(always)]
pub fn pd1(&self) -> PD1_R {
PD1_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - Port D pull-down bit i (i = 3 to 0) Setting PDi bit while the APC bit of the PWR_CR3 register is set activates a pull-down device on the PD\\[i\\]
I/O."]
#[inline(always)]
pub fn pd2(&self) -> PD2_R {
PD2_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - Port D pull-down bit i (i = 3 to 0) Setting PDi bit while the APC bit of the PWR_CR3 register is set activates a pull-down device on the PD\\[i\\]
I/O."]
#[inline(always)]
pub fn pd3(&self) -> PD3_R {
PD3_R::new(((self.bits >> 3) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - Port D pull-down bit i (i = 3 to 0) Setting PDi bit while the APC bit of the PWR_CR3 register is set activates a pull-down device on the PD\\[i\\]
I/O."]
#[inline(always)]
#[must_use]
pub fn pd0(&mut self) -> PD0_W<PDCRD_SPEC, 0> {
PD0_W::new(self)
}
#[doc = "Bit 1 - Port D pull-down bit i (i = 3 to 0) Setting PDi bit while the APC bit of the PWR_CR3 register is set activates a pull-down device on the PD\\[i\\]
I/O."]
#[inline(always)]
#[must_use]
pub fn pd1(&mut self) -> PD1_W<PDCRD_SPEC, 1> {
PD1_W::new(self)
}
#[doc = "Bit 2 - Port D pull-down bit i (i = 3 to 0) Setting PDi bit while the APC bit of the PWR_CR3 register is set activates a pull-down device on the PD\\[i\\]
I/O."]
#[inline(always)]
#[must_use]
pub fn pd2(&mut self) -> PD2_W<PDCRD_SPEC, 2> {
PD2_W::new(self)
}
#[doc = "Bit 3 - Port D pull-down bit i (i = 3 to 0) Setting PDi bit while the APC bit of the PWR_CR3 register is set activates a pull-down device on the PD\\[i\\]
I/O."]
#[inline(always)]
#[must_use]
pub fn pd3(&mut self) -> PD3_W<PDCRD_SPEC, 3> {
PD3_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "PWR Port D pull-down control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`pdcrd::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`pdcrd::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct PDCRD_SPEC;
impl crate::RegisterSpec for PDCRD_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`pdcrd::R`](R) reader structure"]
impl crate::Readable for PDCRD_SPEC {}
#[doc = "`write(|w| ..)` method takes [`pdcrd::W`](W) writer structure"]
impl crate::Writable for PDCRD_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets PDCRD to value 0"]
impl crate::Resettable for PDCRD_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
// 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 common_exception::Result;
use common_meta_api_vo::CreateDatabaseReply;
use common_meta_api_vo::CreateTableReply;
use common_meta_api_vo::DatabaseInfo;
use common_meta_api_vo::GetDatabasesReply;
use common_meta_api_vo::GetTablesReply;
use common_meta_api_vo::TableInfo;
use common_metatypes::MetaId;
use common_metatypes::MetaVersion;
use common_planners::CreateDatabasePlan;
use common_planners::CreateTablePlan;
use common_planners::DropDatabasePlan;
use common_planners::DropTablePlan;
#[async_trait::async_trait]
pub trait MetaApi: Send + Sync {
// database
async fn create_database(&self, plan: CreateDatabasePlan) -> Result<CreateDatabaseReply>;
async fn drop_database(&self, plan: DropDatabasePlan) -> Result<()>;
async fn get_database(&self, db: &str) -> Result<DatabaseInfo>;
async fn get_databases(&self) -> Result<GetDatabasesReply>;
// table
async fn create_table(&self, plan: CreateTablePlan) -> Result<CreateTableReply>;
async fn drop_table(&self, plan: DropTablePlan) -> Result<()>;
async fn get_table(&self, db: &str, table: &str) -> Result<TableInfo>;
async fn get_tables(&self, db: &str) -> Result<GetTablesReply>;
async fn get_table_by_id(
&self,
table_id: MetaId,
db_ver: Option<MetaVersion>,
) -> Result<TableInfo>;
}
|
/// gives a feature to generic operations that most types except enum cannot be used with the operations.
pub(crate) trait EnumSpecific {}
|
#[doc = "Register `CIER` reader"]
pub type R = crate::R<CIER_SPEC>;
#[doc = "Register `CIER` writer"]
pub type W = crate::W<CIER_SPEC>;
#[doc = "Field `LSIRDYIE` reader - LSI ready interrupt enable"]
pub type LSIRDYIE_R = crate::BitReader;
#[doc = "Field `LSIRDYIE` writer - LSI ready interrupt enable"]
pub type LSIRDYIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `LSERDYIE` reader - LSE ready interrupt enable"]
pub type LSERDYIE_R = crate::BitReader;
#[doc = "Field `LSERDYIE` writer - LSE ready interrupt enable"]
pub type LSERDYIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `HSIRDYIE` reader - HSI ready interrupt enable"]
pub type HSIRDYIE_R = crate::BitReader;
#[doc = "Field `HSIRDYIE` writer - HSI ready interrupt enable"]
pub type HSIRDYIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `HSERDYIE` reader - HSE ready interrupt enable"]
pub type HSERDYIE_R = crate::BitReader;
#[doc = "Field `HSERDYIE` writer - HSE ready interrupt enable"]
pub type HSERDYIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PLLRDYIE` reader - PLL ready interrupt enable"]
pub type PLLRDYIE_R = crate::BitReader;
#[doc = "Field `PLLRDYIE` writer - PLL ready interrupt enable"]
pub type PLLRDYIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `LSECSSIE` reader - LSE clock security system interrupt enable"]
pub type LSECSSIE_R = crate::BitReader;
#[doc = "Field `LSECSSIE` writer - LSE clock security system interrupt enable"]
pub type LSECSSIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `HSI48RDYIE` reader - HSI48 ready interrupt enable"]
pub type HSI48RDYIE_R = crate::BitReader;
#[doc = "Field `HSI48RDYIE` writer - HSI48 ready interrupt enable"]
pub type HSI48RDYIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - LSI ready interrupt enable"]
#[inline(always)]
pub fn lsirdyie(&self) -> LSIRDYIE_R {
LSIRDYIE_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - LSE ready interrupt enable"]
#[inline(always)]
pub fn lserdyie(&self) -> LSERDYIE_R {
LSERDYIE_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 3 - HSI ready interrupt enable"]
#[inline(always)]
pub fn hsirdyie(&self) -> HSIRDYIE_R {
HSIRDYIE_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - HSE ready interrupt enable"]
#[inline(always)]
pub fn hserdyie(&self) -> HSERDYIE_R {
HSERDYIE_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - PLL ready interrupt enable"]
#[inline(always)]
pub fn pllrdyie(&self) -> PLLRDYIE_R {
PLLRDYIE_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 9 - LSE clock security system interrupt enable"]
#[inline(always)]
pub fn lsecssie(&self) -> LSECSSIE_R {
LSECSSIE_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - HSI48 ready interrupt enable"]
#[inline(always)]
pub fn hsi48rdyie(&self) -> HSI48RDYIE_R {
HSI48RDYIE_R::new(((self.bits >> 10) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - LSI ready interrupt enable"]
#[inline(always)]
#[must_use]
pub fn lsirdyie(&mut self) -> LSIRDYIE_W<CIER_SPEC, 0> {
LSIRDYIE_W::new(self)
}
#[doc = "Bit 1 - LSE ready interrupt enable"]
#[inline(always)]
#[must_use]
pub fn lserdyie(&mut self) -> LSERDYIE_W<CIER_SPEC, 1> {
LSERDYIE_W::new(self)
}
#[doc = "Bit 3 - HSI ready interrupt enable"]
#[inline(always)]
#[must_use]
pub fn hsirdyie(&mut self) -> HSIRDYIE_W<CIER_SPEC, 3> {
HSIRDYIE_W::new(self)
}
#[doc = "Bit 4 - HSE ready interrupt enable"]
#[inline(always)]
#[must_use]
pub fn hserdyie(&mut self) -> HSERDYIE_W<CIER_SPEC, 4> {
HSERDYIE_W::new(self)
}
#[doc = "Bit 5 - PLL ready interrupt enable"]
#[inline(always)]
#[must_use]
pub fn pllrdyie(&mut self) -> PLLRDYIE_W<CIER_SPEC, 5> {
PLLRDYIE_W::new(self)
}
#[doc = "Bit 9 - LSE clock security system interrupt enable"]
#[inline(always)]
#[must_use]
pub fn lsecssie(&mut self) -> LSECSSIE_W<CIER_SPEC, 9> {
LSECSSIE_W::new(self)
}
#[doc = "Bit 10 - HSI48 ready interrupt enable"]
#[inline(always)]
#[must_use]
pub fn hsi48rdyie(&mut self) -> HSI48RDYIE_W<CIER_SPEC, 10> {
HSI48RDYIE_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "Clock interrupt enable register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cier::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cier::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct CIER_SPEC;
impl crate::RegisterSpec for CIER_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`cier::R`](R) reader structure"]
impl crate::Readable for CIER_SPEC {}
#[doc = "`write(|w| ..)` method takes [`cier::W`](W) writer structure"]
impl crate::Writable for CIER_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets CIER to value 0"]
impl crate::Resettable for CIER_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use {SystrayError};
pub struct Window {
}
impl Window {
pub fn new() -> Result<Window, SystrayError> {
Err(SystrayError::NotImplementedError)
}
}
|
use crossbeam::crossbeam_channel::*;
#[derive(Debug)]
pub struct VM {
pub memory: Vec<isize>,
ip: usize,
sp: usize,
pub input: Sender<isize>,
reader: Receiver<isize>,
pub output: Receiver<isize>,
writer: Sender<isize>,
}
#[derive(PartialEq, Debug, Copy, Clone)]
pub enum Address {
Position(isize),
Immediate(isize),
Relative(isize),
}
impl From<(isize, isize)> for Address {
fn from((mode, value): (isize, isize)) -> Address {
match mode {
0 => Address::Position(value),
1 => Address::Immediate(value),
2 => Address::Relative(value),
_ => unreachable!(),
}
}
}
#[derive(Debug, Copy, Clone)]
pub enum Instruction {
Halt,
Add(Address, Address, Address),
Multiply(Address, Address, Address),
Input(Address),
Output(Address),
JumpNZ(Address, Address),
JumpZ(Address, Address),
IfLess(Address, Address, Address),
IfEqual(Address, Address, Address),
AdjustSP(Address),
Unknown(isize),
}
impl Instruction {
fn arity(&self) -> usize {
match self {
Instruction::Halt => 1,
Instruction::Add(_, _, _) => 4,
Instruction::Multiply(_, _, _) => 4,
Instruction::Input(_) => 2,
Instruction::Output(_) => 2,
Instruction::JumpNZ(_, _) => 3,
Instruction::JumpZ(_, _) => 3,
Instruction::IfLess(_, _, _) => 4,
Instruction::IfEqual(_, _, _) => 4,
Instruction::AdjustSP(_) => 2,
Instruction::Unknown(_) => 0,
}
}
}
impl VM {
pub fn new(initial_memory: &[isize]) -> Self {
let (input, reader) = unbounded();
let (writer, output) = unbounded();
let mut memory = initial_memory.to_vec();
memory.resize(4000, 0);
Self {
memory,
ip: 0,
sp: 0,
input,
reader,
output,
writer,
}
}
pub fn op(&self) -> Instruction {
let i = self.memory[self.ip];
let op = i % 100;
let mode_one = (i / 100) % 10;
let mode_two = (i / 1_000) % 10;
let mode_three = (i / 10_000) % 10;
match op {
1 => Instruction::Add(
(mode_one, self.memory[self.ip + 1]).into(),
(mode_two, self.memory[self.ip + 2]).into(),
(mode_three, self.memory[self.ip + 3]).into(),
),
2 => Instruction::Multiply(
(mode_one, self.memory[self.ip + 1]).into(),
(mode_two, self.memory[self.ip + 2]).into(),
(mode_three, self.memory[self.ip + 3]).into(),
),
3 => Instruction::Input((mode_one, self.memory[self.ip + 1]).into()),
4 => Instruction::Output((mode_one, self.memory[self.ip + 1]).into()),
5 => Instruction::JumpNZ(
(mode_one, self.memory[self.ip + 1]).into(),
(mode_two, self.memory[self.ip + 2]).into(),
),
6 => Instruction::JumpZ(
(mode_one, self.memory[self.ip + 1]).into(),
(mode_two, self.memory[self.ip + 2]).into(),
),
7 => Instruction::IfLess(
(mode_one, self.memory[self.ip + 1]).into(),
(mode_two, self.memory[self.ip + 2]).into(),
(mode_three, self.memory[self.ip + 3]).into(),
),
8 => Instruction::IfEqual(
(mode_one, self.memory[self.ip + 1]).into(),
(mode_two, self.memory[self.ip + 2]).into(),
(mode_three, self.memory[self.ip + 3]).into(),
),
9 => Instruction::AdjustSP((mode_one, self.memory[self.ip + 1]).into()),
99 => Instruction::Halt,
n => Instruction::Unknown(n),
}
}
pub fn at(&self, idx: Address) -> isize {
match idx {
Address::Immediate(v) => v,
Address::Position(p) => self.memory[p as usize],
Address::Relative(r) => self.memory[(self.sp as isize + r) as usize],
}
}
pub fn set(&mut self, idx: Address, val: isize) {
match idx {
Address::Immediate(v) => self.memory[v as usize] = val,
Address::Position(p) => self.memory[p as usize] = val,
Address::Relative(r) => self.memory[(self.sp as isize + r) as usize] = val,
};
}
pub fn run(&mut self) -> isize {
let mut latest_output = 0;
loop {
let op = self.op();
let arity = op.arity();
match op {
Instruction::Unknown(n) => panic!("unimplemented opcode: {}", n),
Instruction::Halt => break,
Instruction::Multiply(a, b, c) => {
let a = self.at(a);
let b = self.at(b);
self.set(c, a * b);
}
Instruction::Add(a, b, c) => {
let a = self.at(a);
let b = self.at(b);
self.set(c, a + b);
}
Instruction::Input(a) => {
let n = self.reader.recv().unwrap();
self.set(a, n);
}
Instruction::Output(a) => {
let a = self.at(a);
latest_output = a;
self.writer.send(a).unwrap_or_default();
}
Instruction::JumpNZ(a, b) => {
let a = self.at(a);
let b = self.at(b);
if a != 0 {
self.ip = b as usize;
continue;
}
}
Instruction::JumpZ(a, b) => {
let a = self.at(a);
let b = self.at(b);
if a == 0 {
self.ip = b as usize;
continue;
}
}
Instruction::IfLess(a, b, c) => {
let a = self.at(a);
let b = self.at(b);
self.set(c, if a < b { 1 } else { 0 });
}
Instruction::IfEqual(a, b, c) => {
let a = self.at(a);
let b = self.at(b);
self.set(c, if a == b { 1 } else { 0 });
}
Instruction::AdjustSP(a) => {
let a = self.at(a);
self.sp = (self.sp as isize + a) as usize;
}
}
self.ip += arity;
}
latest_output
}
pub fn pipe(&mut self, to: &mut Self) {
let (tx, rx) = unbounded();
self.writer = tx.clone();
to.input = tx.clone();
to.reader = rx;
}
}
impl From<&str> for VM {
fn from(input: &str) -> Self {
use itertools::Itertools;
let mem = input
.split(',')
.flat_map(|c| c.trim().parse())
.collect_vec();
Self::new(&mem)
}
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Profile control"]
pub ctl: CTL,
#[doc = "0x04 - Profile status"]
pub status: STATUS,
_reserved2: [u8; 8usize],
#[doc = "0x10 - Profile command"]
pub cmd: CMD,
_reserved3: [u8; 1964usize],
#[doc = "0x7c0 - Profile interrupt"]
pub intr: INTR,
#[doc = "0x7c4 - Profile interrupt set"]
pub intr_set: INTR_SET,
#[doc = "0x7c8 - Profile interrupt mask"]
pub intr_mask: INTR_MASK,
#[doc = "0x7cc - Profile interrupt masked"]
pub intr_masked: INTR_MASKED,
_reserved7: [u8; 48usize],
#[doc = "0x800 - Profile counter structure"]
pub cnt_struct0: CNT_STRUCT,
_reserved8: [u8; 4usize],
#[doc = "0x810 - Profile counter structure"]
pub cnt_struct1: CNT_STRUCT,
_reserved9: [u8; 4usize],
#[doc = "0x820 - Profile counter structure"]
pub cnt_struct2: CNT_STRUCT,
_reserved10: [u8; 4usize],
#[doc = "0x830 - Profile counter structure"]
pub cnt_struct3: CNT_STRUCT,
_reserved11: [u8; 4usize],
#[doc = "0x840 - Profile counter structure"]
pub cnt_struct4: CNT_STRUCT,
_reserved12: [u8; 4usize],
#[doc = "0x850 - Profile counter structure"]
pub cnt_struct5: CNT_STRUCT,
_reserved13: [u8; 4usize],
#[doc = "0x860 - Profile counter structure"]
pub cnt_struct6: CNT_STRUCT,
_reserved14: [u8; 4usize],
#[doc = "0x870 - Profile counter structure"]
pub cnt_struct7: CNT_STRUCT,
}
#[doc = r"Register block"]
#[repr(C)]
pub struct CNT_STRUCT {
#[doc = "0x00 - Profile counter configuration"]
pub ctl: self::cnt_struct::CTL,
_reserved1: [u8; 4usize],
#[doc = "0x08 - Profile counter value"]
pub cnt: self::cnt_struct::CNT,
}
#[doc = r"Register block"]
#[doc = "Profile counter structure"]
pub mod cnt_struct;
#[doc = "Profile control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [ctl](ctl) module"]
pub type CTL = crate::Reg<u32, _CTL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CTL;
#[doc = "`read()` method returns [ctl::R](ctl::R) reader structure"]
impl crate::Readable for CTL {}
#[doc = "`write(|w| ..)` method takes [ctl::W](ctl::W) writer structure"]
impl crate::Writable for CTL {}
#[doc = "Profile control"]
pub mod ctl;
#[doc = "Profile status\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [status](status) module"]
pub type STATUS = crate::Reg<u32, _STATUS>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _STATUS;
#[doc = "`read()` method returns [status::R](status::R) reader structure"]
impl crate::Readable for STATUS {}
#[doc = "Profile status"]
pub mod status;
#[doc = "Profile command\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [cmd](cmd) module"]
pub type CMD = crate::Reg<u32, _CMD>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CMD;
#[doc = "`read()` method returns [cmd::R](cmd::R) reader structure"]
impl crate::Readable for CMD {}
#[doc = "`write(|w| ..)` method takes [cmd::W](cmd::W) writer structure"]
impl crate::Writable for CMD {}
#[doc = "Profile command"]
pub mod cmd;
#[doc = "Profile interrupt\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [intr](intr) module"]
pub type INTR = crate::Reg<u32, _INTR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTR;
#[doc = "`read()` method returns [intr::R](intr::R) reader structure"]
impl crate::Readable for INTR {}
#[doc = "`write(|w| ..)` method takes [intr::W](intr::W) writer structure"]
impl crate::Writable for INTR {}
#[doc = "Profile interrupt"]
pub mod intr;
#[doc = "Profile interrupt set\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [intr_set](intr_set) module"]
pub type INTR_SET = crate::Reg<u32, _INTR_SET>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTR_SET;
#[doc = "`read()` method returns [intr_set::R](intr_set::R) reader structure"]
impl crate::Readable for INTR_SET {}
#[doc = "`write(|w| ..)` method takes [intr_set::W](intr_set::W) writer structure"]
impl crate::Writable for INTR_SET {}
#[doc = "Profile interrupt set"]
pub mod intr_set;
#[doc = "Profile interrupt mask\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [intr_mask](intr_mask) module"]
pub type INTR_MASK = crate::Reg<u32, _INTR_MASK>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTR_MASK;
#[doc = "`read()` method returns [intr_mask::R](intr_mask::R) reader structure"]
impl crate::Readable for INTR_MASK {}
#[doc = "`write(|w| ..)` method takes [intr_mask::W](intr_mask::W) writer structure"]
impl crate::Writable for INTR_MASK {}
#[doc = "Profile interrupt mask"]
pub mod intr_mask;
#[doc = "Profile interrupt masked\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [intr_masked](intr_masked) module"]
pub type INTR_MASKED = crate::Reg<u32, _INTR_MASKED>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTR_MASKED;
#[doc = "`read()` method returns [intr_masked::R](intr_masked::R) reader structure"]
impl crate::Readable for INTR_MASKED {}
#[doc = "Profile interrupt masked"]
pub mod intr_masked;
|
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_lambda::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// The AWS Region in which the client is created.
#[structopt(short, long)]
region: Option<String>,
/// Just show runtimes for indicated language.
/// dotnet, go, node, java, etc.
#[structopt(short, long)]
language: Option<String>,
/// Whether to display additional runtime information.
#[structopt(short, long)]
verbose: bool,
}
/// Lists the ARNs and runtimes of all Lambda functions in all Regions.
// snippet-start:[lambda.rust.list-all-function-runtimes]
async fn show_lambdas(verbose: bool, language: &str, reg: &'static str) {
let region_provider = RegionProviderChain::default_provider().or_else(reg);
let config = aws_config::from_env().region(region_provider).load().await;
let client = Client::new(&config);
let resp = client.list_functions().send().await;
let functions = resp.unwrap().functions.unwrap_or_default();
let max_functions = functions.len();
let mut num_functions = 0;
for function in functions {
let rt_str: String = String::from(function.runtime.unwrap().as_ref());
// If language is set (!= ""), show only those with that runtime.
let ok = rt_str
.to_ascii_lowercase()
.contains(&language.to_ascii_lowercase());
if ok || language.is_empty() {
println!(" ARN: {}", function.function_arn.unwrap());
println!(" Runtime: {}", rt_str);
println!();
num_functions += 1;
}
}
if num_functions > 0 || verbose {
println!(
"Found {} function(s) (out of {}) in {} region.",
num_functions, max_functions, reg
);
println!();
}
}
// snippet-end:[lambda.rust.list-all-function-runtimes]
/// Lists the ARNs and runtimes of your Lambda functions in all available regions.
/// # Arguments
///
/// * `[-r REGION]` - The Region in which the client is created.
/// If not supplied, uses the value of the **AWS_REGION** environment variable.
/// If the environment variable is not set, defaults to **us-west-2**.
/// * `[-v]` - Whether to display additional information.
#[tokio::main]
async fn main() -> Result<(), Error> {
tracing_subscriber::fmt::init();
let Opt {
language,
region,
verbose,
} = Opt::from_args();
let region_provider = RegionProviderChain::first_try(region.map(Region::new))
.or_default_provider()
.or_else(Region::new("us-west-2"));
println!();
if verbose {
println!("EC2 client version: {}", aws_sdk_ec2::PKG_VERSION);
println!("Lambda client version: {}", PKG_VERSION);
println!(
"Region: {}",
region_provider.region().await.unwrap().as_ref()
);
println!();
}
// Get list of available regions.
let shared_config = aws_config::from_env().region(region_provider).load().await;
let ec2_client = aws_sdk_ec2::Client::new(&shared_config);
let resp = ec2_client.describe_regions().send().await;
for region in resp.unwrap().regions.unwrap_or_default() {
let reg: &'static str = Box::leak(region.region_name.unwrap().into_boxed_str());
show_lambdas(verbose, language.as_deref().unwrap_or_default(), reg).await;
}
Ok(())
}
|
extern crate diesel_demo;
extern crate diesel;
use self::diesel_demo::*;
use std::io::stdin;
fn main() {
let connection = establish_connection();
println!("Title:");
let mut title = String::new();
stdin().read_line(&mut title).unwrap();
let title = &title[..(title.len() - 1)]; // Drop the newline character
println!("Director:");
let mut director = String::new();
stdin().read_line(&mut director).unwrap();
let director = &director[..(director.len() - 1)];
println!("Release year:");
let mut year = String::new();
stdin().read_line(&mut year).unwrap();
let year: i32 = year.trim().parse().unwrap();
let movie = create_movie(&connection, title, &director, &year);
println!("\nSaved movie {} with id {}", title, movie.id);
}
#[cfg(not(windows))]
const EOF: &'static str = "CTRL+D";
#[cfg(windows)]
const EOF: &'static str = "CTRL+Z"; |
//! # Pcf8523
//!
//! `Pcf8523` is a crate which abstracts away managing a PCF8523 device on an
//! I2C bus. You can read the time and write the time, and someday in the future
//! do other configuration tasks as well.
use chrono::prelude::*;
use i2cdev::core::*;
use i2cdev::linux::LinuxI2CDevice;
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
fn bcd_decode(x: u8) -> u32 {
((((x & 0xF0) >> 4) * 10) + (x & 0x0F)) as u32
}
fn bcd_encode(x: u32) -> u8 {
if x >= 100 {
panic!("Tried to BCD encode value {} >= 100", x);
}
let lower = x % 10;
let upper = x / 10;
(lower | (upper << 4)) as u8
}
pub struct Pcf8523 {
dev: LinuxI2CDevice,
}
impl Pcf8523 {
/// Returns a new Pcf8523 using the specified path to an i2c-dev device.
///
/// # Arguments
///
/// * `i2cpath` - Path to the I2C device, e.g. /dev/i2c-1
///
/// # Panics
///
/// This function panics if there is an issue opening the device.
pub fn new(i2cpath: &str) -> Pcf8523 {
let i2caddr = 0x68;
let mut dev = LinuxI2CDevice::new(i2cpath, i2caddr).unwrap();
println!("{}", dev.smbus_read_byte_data(0x04).unwrap());
Pcf8523{
dev: dev,
}
}
/// Returns the time in UTC from the device.
///
/// # Panics
///
/// Panics if there is an issue reading the I2C bus, or if the data stored
/// on the chip is not a valid UTC time.
pub fn get_time(&mut self) -> chrono::DateTime<Utc> {
let fields = self.dev.smbus_read_i2c_block_data(0x03, 7).unwrap();
let sec = bcd_decode(fields[0]);
let min = bcd_decode(fields[1]);
let hour = bcd_decode(fields[2]);
let day = bcd_decode(fields[3]);
let mon = bcd_decode(fields[5]);
let yr = bcd_decode(fields[6]);
Utc.ymd(2000 + yr as i32, mon, day).and_hms(hour, min, sec)
}
/// Programs the given time, in UTC, to the device.
///
/// # Panics
///
/// Panics if:
/// - The current year is < 2000 or >= 2100, or
/// - If there is an error writing to the I2C bus.
pub fn set_time(&mut self, time: chrono::DateTime<Utc>) {
let sec = bcd_encode(time.second());
let min = bcd_encode(time.minute());
let hour = bcd_encode(time.hour());
let day = bcd_encode(time.day());
// chrono has Sunday == 7, PCF8523 has Sunday == 0 (like a sane person)
let days_since_monday = time.weekday().number_from_monday();
let dow = bcd_encode(if days_since_monday == 7 { 0 } else { days_since_monday });
let mon = bcd_encode(time.month());
let yr = bcd_encode(time.year() as u32 - 2000);
let data = [sec, min, hour, day, dow, mon, yr];
self.dev.smbus_write_i2c_block_data(0x03, &data).unwrap();
}
}
|
//! [balena] **c**onfiguration **dsl**
//!
//! A crate that provides facilities to:
//!
//! * transform configuration DSL into the JSON Schema & UI Object Schema with custom extensions
//! * parse configuration DSL
//!
//! # Versioning
//!
//! This crate is being actively developed and it does NOT follow [Semantic Versioning] yet.
//! It will follow semantic versioning when it reaches version 1.0.
//!
//! MINOR version changes denotes incompatible API changes and PATCH version changes denotes
//! both new functionality in a backwards-compatible manner and backwards-compatible bug fixes.
//!
//! # Examples
//!
//! ## Generate JSON Schema & UI Object
//!
//! ```
//! use jellyschema::generator::generate_json_ui_schema;
//! use jellyschema::schema::Schema;
//! use serde_yaml;
//!
//! let dsl = r#"
//! version: 1
//! properties:
//! - name:
//! type: string
//! help: You should type your name here
//! "#;
//!
//! let input_schema: Schema = serde_yaml::from_str(dsl).unwrap();
//!
//! let (json_schema, ui_object) = generate_json_ui_schema(&input_schema);
//! ```
//!
//! [balena]: https://www.balena.io
//! [Semantic Versioning]: https://semver.org/
pub(crate) mod deref;
pub mod error;
pub mod filler;
pub mod schema;
pub mod validator;
pub mod generator;
#[cfg(all(target_arch = "wasm32", not(feature = "disable-wasm-bindings")))]
mod wasm;
|
#[cfg(test)]
mod hash_test {
#![feature(map_first_last)]
use std::collections::BTreeMap;
use std::{
fs::File,
io::{BufRead, BufReader},
u64,
};
use crypto::digest::Digest;
use crypto::md5::Md5;
use hash::{Bkdr, Crc32, Hash};
use std::ops::Bound::Included;
#[test]
fn hash_check() {
// 将java生成的随机key及hash,每种size都copy的几条过来,用于日常验证
//let path = "/Users/fishermen/works/weibo/git/java/api-commons/";
let path = "./records/";
let bkdr10 = format!("{}{}", path, "bkdr_10.log");
let bkdr15 = format!("{}{}", path, "bkdr_15.log");
let bkdr20 = format!("{}{}", path, "bkdr_20.log");
let bkdr50 = format!("{}{}", path, "bkdr_50.log");
bkdr_check(&bkdr10);
bkdr_check(&bkdr15);
bkdr_check(&bkdr20);
bkdr_check(&bkdr50);
let crc10 = format!("{}{}", path, "crc32_10.log");
let crc15 = format!("{}{}", path, "crc32_15.log");
let crc20 = format!("{}{}", path, "crc32_20.log");
let crc50 = format!("{}{}", path, "crc32_50.log");
crc32_check(&crc10);
crc32_check(&crc15);
crc32_check(&crc20);
crc32_check(&crc50);
let consis10 = format!("{}{}", path, "consistent_10.log");
// let consis15 = format!("{}{}", path, "consistent_15.log");
// let consis20 = format!("{}{}", path, "consistent_20.log");
// let consis50 = format!("{}{}", path, "consistent_50.log");
consistent_check(&consis10);
// consistent_check(&consis15);
// consistent_check(&consis20);
// consistent_check(&consis50);
let key = " 653017.hqfy";
md5(&key);
}
#[test]
fn layer_test() {
let mut layer_readers = Vec::new();
layer_readers.push(vec![vec!["1", "2", "3"], vec!["4", "5"], vec!["6", "7"]]);
layer_readers.push(vec![vec!["1", "2", "3"], vec!["6", "7"]]);
layer_readers.push(vec![vec!["7", "8"], vec!["4", "5"]]);
let mut readers = Vec::new();
for layer in &layer_readers {
if layer.len() == 1 {
let r = &layer[0];
if !readers.contains(r) {
readers.push(r.clone());
}
} else if layer.len() > 1 {
for r in layer {
if !readers.contains(r) {
readers.push(r.clone())
}
}
}
}
debug_assert!(readers.len() == 4);
println!("readers: {:?}", readers);
}
fn bkdr_check(path: &str) {
let file = File::open(path).unwrap();
let mut reader = BufReader::new(file);
let mut num = 0;
loop {
let mut line = String::new();
match reader.read_line(&mut line) {
Ok(len) => {
num += 1;
if len == 0 {
println!("file processed copleted! all lines: {}", num);
break;
}
let props = line.split(" ").collect::<Vec<&str>>();
debug_assert!(props.len() == 2);
let key = props[0].trim();
let hash_in_java = props[1].trim();
// println!(
// "{} line: key: {}, hash: {}, hash-len:{}",
// num,
// key,
// hash_in_java,
// hash_in_java.len(),
// );
let hash = Bkdr {}.hash(key.as_bytes());
let hash_in_java_u64 = hash_in_java.parse::<u64>().unwrap();
if hash != hash_in_java_u64 {
println!(
"bkdr found error - line in java: {}, rust hash: {}",
line, hash
);
panic!("bkdr found error in bkdr");
}
// println!("hash in rust: {}, in java:{}", hash, hash_in_java);
}
Err(e) => {
println!("Stop read for err: {}", e);
break;
}
}
}
println!("check bkdr hash from file: {}", path);
}
fn crc32_check(path: &str) {
let file = File::open(path).unwrap();
let mut reader = BufReader::new(file);
let mut num = 0;
loop {
let mut line = String::new();
match reader.read_line(&mut line) {
Ok(len) => {
num += 1;
if len == 0 {
println!("file processed copleted! all lines: {}", num);
break;
}
let props = line.split(" ").collect::<Vec<&str>>();
debug_assert!(props.len() == 2);
let key = props[0].trim();
let hash_in_java = props[1].trim();
let hash = Crc32 {}.hash(key.as_bytes());
let hash_in_java_u64 = hash_in_java.parse::<u64>().unwrap();
if hash != hash_in_java_u64 {
println!(
"crc32 found error - line in java: {}, rust hash: {}",
line, hash
);
panic!("bkdr found error in crc32");
}
// println!(
// "crc32 succeed - key: {}, rust: {}, java: {}",
// key, hash_in_java, hash
// );
}
Err(e) => println!("Stop read for err: {}", e),
}
}
println!("check crc32 hash from file: {}", path);
}
fn consistent_check(path: &str) {
let file = File::open(path).unwrap();
let mut reader = BufReader::new(file);
let mut num = 0;
let shards = vec![
"127.0.0.1",
"127.0.0.2",
"127.0.0.3",
"127.0.0.4",
"127.0.0.5",
];
let mut instance = ConsistentHashInstance::from(shards);
loop {
let mut line = String::new();
match reader.read_line(&mut line) {
Ok(len) => {
num += 1;
if len == 0 {
println!("file processed copleted! all lines: {}", num);
break;
}
let props = line.split(" ").collect::<Vec<&str>>();
debug_assert!(props.len() == 3);
let key = props[0].trim();
let hash_in_java = props[1].trim();
let server_in_java = props[2].trim();
let hash_in_java_u64 = hash_in_java.parse::<i64>().unwrap();
let (hash, server) = instance.get_hash_server(key);
if hash != hash_in_java_u64 {
println!(
"consistent found error - line in java: {}, rust hash: {}",
line, hash
);
panic!("bkdr found error in crc32");
}
// println!(
// "crc32 succeed - key: {}, rust: {}, java: {}",
// key, hash_in_java, hash
// );
}
Err(e) => println!("Stop read for err: {}", e),
}
}
println!("check consistent hash from file: {}", path);
}
struct ConsistentHashInstance {
consistent_map: BTreeMap<i64, usize>,
shards: Vec<&'static str>,
}
impl ConsistentHashInstance {
fn from(shards: Vec<&'static str>) -> Self {
let mut consistent_map = BTreeMap::new();
for idx in 0..shards.len() {
let factor = 40;
for i in 0..factor {
let mut md5 = Md5::new();
let data: String = shards[idx].to_string() + "-" + &i.to_string();
let data_str = data.as_str();
md5.input_str(data_str);
let mut digest_bytes = [0u8; 16];
md5.result(&mut digest_bytes);
for j in 0..4 {
let hash = (((digest_bytes[3 + j * 4] & 0xFF) as i64) << 24)
| (((digest_bytes[2 + j * 4] & 0xFF) as i64) << 16)
| (((digest_bytes[1 + j * 4] & 0xFF) as i64) << 8)
| ((digest_bytes[0 + j * 4] & 0xFF) as i64);
let mut hash = hash.wrapping_rem(i32::MAX as i64);
if hash < 0 {
hash = hash.wrapping_mul(-1);
}
consistent_map.insert(hash, idx);
//println!("+++++++ {} - {}", hash, shards[idx]);
}
}
}
//println!("map: {:?}", consistent_map);
Self {
shards,
consistent_map,
}
}
fn get_hash_server(&self, key: &str) -> (i64, String) {
// 一致性hash,选择hash环的第一个节点,不支持漂移,避免脏数据 fishermen
let mut bk = Bkdr {};
let h = bk.hash(key.as_bytes()) as usize;
let idxs = self
.consistent_map
.range((Included(h as i64), Included(i64::MAX)));
for (hash, idx) in idxs {
//println!("chose idx/{} with hash/{} for key/{}", idx, hash, key);
let s = self.shards[*idx].to_string();
return (*hash, s);
}
//if let Some(mut entry) = self.consistent_map.first_entry() {
for (h, i) in &self.consistent_map {
let s = self.shards[*i];
return (*h, s.to_string());
}
return (0, "unavailable".to_string());
}
}
fn md5(key: &str) {
let mut md5 = Md5::new();
md5.input_str(key);
// let digest_str = md5.result_str();
let mut out = [0u8; 16];
md5.result(&mut out);
// println!("key={}, md5={:?}", key, &out);
// let digest_bytes = digest_str.as_bytes();
for j in 0..4 {
let hash = (((out[3 + j * 4] & 0xFF) as i64) << 24)
| (((out[2 + j * 4] & 0xFF) as i64) << 16)
| (((out[1 + j * 4] & 0xFF) as i64) << 8)
| ((out[0 + j * 4] & 0xFF) as i64);
let mut hash = hash.wrapping_rem(i32::MAX as i64);
if hash < 0 {
hash = hash.wrapping_mul(-1);
}
// let hash_little = LittleEndian::read_i32(&out[j * 4..]) as i64;
// let hash_big = BigEndian::read_i32(&out[j * 4..]) as i64;
// println!("raw: {} {} {}", hash, hash_little, hash_big);
// let hash = hash.wrapping_abs() as u64;
//println!("+++++++ {} - {}", hash, j);
}
}
}
|
use super::{Allocator, Layout};
use core::{ffi::c_void, ptr::NonNull};
use win32::kernel32;
#[derive(Clone, Copy, Default)]
pub struct Win32HeapAllocator;
impl Allocator for Win32HeapAllocator
{
unsafe fn alloc(&mut self, layout: Layout) -> Option<NonNull<c_void>>
{
let ptr = kernel32::HeapAlloc(kernel32::GetProcessHeap(), 0, layout.size);
NonNull::new(ptr)
}
unsafe fn dealloc(&mut self, ptr: *mut c_void)
{
kernel32::HeapFree(kernel32::GetProcessHeap(), 0, ptr);
}
}
#[cfg(test)]
mod tests
{
use super::*;
#[test]
fn allocator()
{
unsafe {
let mut alloc = Win32HeapAllocator::default();
let ptr = alloc.alloc(Layout::new(128));
assert!(ptr.is_some());
alloc.dealloc(ptr.unwrap().as_ptr());
}
}
struct Container<A: Allocator>
{
alloc: A,
}
impl<A: Allocator> Container<A>
{
fn new(alloc: A) -> Self
{
Self { alloc }
}
fn do_alloc(&mut self, size: usize)
{
unsafe {
self.alloc.alloc(Layout::new(size));
}
}
}
#[test]
fn multiple_refs()
{
let alloc = Win32HeapAllocator::default();
let mut c1 = Container::new(alloc);
let mut c2 = Container::new(alloc);
c1.do_alloc(128);
c2.do_alloc(64);
c1.do_alloc(128);
c2.do_alloc(64);
}
}
|
use std::sync::{Arc, Mutex, atomic::{AtomicUsize, Ordering}};
use crate::{LobbyEvent, LobbyManager, MatchLogEvent, LobbyData, StrippedPlayer};
use futures::{StreamExt, future};
use futures::FutureExt;
use mozaic_core::Token;
use serde::{Serialize, Deserialize};
use tokio::sync::mpsc;
use tokio_stream::wrappers::UnboundedReceiverStream;
use warp::ws::WebSocket;
pub struct WsConnection {
#[warn(dead_code)]
_conn_id: usize,
tx: mpsc::UnboundedSender<String>,
}
impl WsConnection {
pub fn send(&mut self, msg: String) -> Result<(), ()> {
self.tx.send(msg).map_err(|_| ())
}
}
#[derive(Serialize, Deserialize)]
#[serde(tag = "type")]
#[serde(rename_all="camelCase")]
enum WsClientMessage {
AuthenticatePlayer(AuthenticatePlayer),
SubscribeToLobby(SubscribeToLobby),
SubscribeToMatch(SubscribeToMatch),
}
#[derive(Serialize, Deserialize)]
#[serde(rename_all="camelCase")]
struct AuthenticatePlayer {
lobby_id: String,
#[serde(with = "hex")]
token: Token,
}
#[derive(Serialize, Deserialize)]
#[serde(rename_all="camelCase")]
struct SubscribeToLobby {
lobby_id: String,
}
#[derive(Serialize, Deserialize)]
#[serde(rename_all="camelCase")]
struct SubscribeToMatch {
match_id: String,
stream_id: usize,
}
struct ConnectionHandler {
conn_id: usize,
mgr: Arc<Mutex<LobbyManager>>,
// (lobby_id, player_id)
authenticated_players: Vec<(String, usize)>,
tx: mpsc::UnboundedSender<String>,
}
impl ConnectionHandler {
fn handle_message(&mut self, msg: WsClientMessage) {
match msg {
WsClientMessage::AuthenticatePlayer(req) => self.authenticate(req),
WsClientMessage::SubscribeToLobby(req) => self.subscribe_to_lobby(req),
WsClientMessage::SubscribeToMatch(req) => self.subscribe_to_match(req),
}
}
fn subscribe_to_lobby(&mut self, req: SubscribeToLobby) {
let mut lobby_mgr = self.mgr.lock().unwrap();
let lobby_data = {
// TODO: log, error, ANYTHING
let lobby = match lobby_mgr.lobbies.get_mut(&req.lobby_id) {
None => return,
Some(lobby) => lobby,
};
LobbyData::from(lobby.clone())
};
// update current state to prevent desync
let resp = serde_json::to_string(&LobbyEvent::LobbyState(lobby_data)).unwrap();
self.tx.send(resp).unwrap();
// add connection to connection pool
lobby_mgr.websocket_connections
.entry(req.lobby_id)
.or_insert_with(|| Vec::new())
.push(WsConnection {
_conn_id: self.conn_id,
tx: self.tx.clone(),
});
}
fn subscribe_to_match(&mut self, req: SubscribeToMatch) {
let lobby_mgr = self.mgr.lock().unwrap();
let game_mgr = lobby_mgr.game_manager.lock().unwrap();
if let Some(match_data) = game_mgr.get_match_data(&req.match_id) {
let tx = self.tx.clone();
let task = match_data.log.reader().for_each(move |log_entry| {
let event= LobbyEvent::MatchLogEvent(MatchLogEvent {
stream_id: req.stream_id,
event: log_entry.as_ref().clone(),
});
let serialized = serde_json::to_string(&event).unwrap();
// just carry on if things are broken, for now.
// TODO: have some decency
let _result = tx.send(serialized);
future::ready(())
});
tokio::spawn(task);
}
}
fn authenticate(&mut self, req: AuthenticatePlayer) {
let mut lobby_mgr = self.mgr.lock().unwrap();
let player_data = {
// TODO: log, error, ANYTHING
let lobby = match lobby_mgr.lobbies.get_mut(&req.lobby_id) {
None => return,
Some(lobby) => lobby,
};
// TODO: log, error, ANYTHING
match lobby.token_player.get(&req.token) {
None => return,
Some(&player_id) => {
self.authenticated_players.push((req.lobby_id.clone(), player_id));
let player = lobby.players.get_mut(&player_id).unwrap();
player.connection_count += 1;
if player.connection_count == 1 {
// update required
Some(StrippedPlayer::from(player.clone()))
} else {
None
}
}
}
};
if let Some(data) = player_data {
lobby_mgr.send_update(&req.lobby_id, LobbyEvent::PlayerData(data));
}
}
fn disconnect(&mut self) {
let mut lobby_mgr = self.mgr.lock().unwrap();
for (lobby_id, player_id) in self.authenticated_players.iter() {
let update = match lobby_mgr.lobbies.get_mut(lobby_id) {
None => continue,
Some(lobby) => {
lobby.players.get_mut(&player_id).and_then(|player| {
player.connection_count -= 1;
if player.connection_count == 0 {
// update required
Some(StrippedPlayer::from(player.clone()))
} else {
None
}
})
}
};
if let Some(player_data) = update {
lobby_mgr.send_update(&lobby_id, LobbyEvent::PlayerData(player_data));
}
}
}
}
static NEXT_CONNECTION_ID: AtomicUsize = AtomicUsize::new(1);
pub async fn handle_websocket(
ws: WebSocket,
mgr: Arc<Mutex<LobbyManager>>
)
{
let conn_id = NEXT_CONNECTION_ID.fetch_add(1, Ordering::Relaxed);
let (tx, rx) = mpsc::unbounded_channel();
let (ws_tx, mut ws_rx) = ws.split();
let mut handler = ConnectionHandler {
conn_id,
mgr,
tx,
authenticated_players: Vec::new(),
};
let messages = UnboundedReceiverStream::new(rx).map(|text| {
Ok(warp::ws::Message::text(text))
});
tokio::task::spawn(messages.forward(ws_tx).map(|res| {
if let Err(e) = res {
eprintln!("websocket send error: {}", e);
}
}));
while let Some(res) = ws_rx.next().await {
let ws_msg = match res {
Ok(ws_msg) => ws_msg,
Err(e) => {
eprintln!("websocket error(uid={}): {}", conn_id, e);
break;
}
};
// TODO: UGLY UGh
let client_msg: WsClientMessage = match ws_msg.to_str() {
Ok(text) => match serde_json::from_str(text) {
Ok(req) => req,
Err(err) => {
eprintln!("{}", err);
continue
}
}
Err(()) => continue,
};
handler.handle_message(client_msg);
}
// connection done, disconnect!
handler.disconnect();
} |
use crate::ret_none_if;
use crate::name::NamePtr;
use crate::expr::{ Expr, ExprsPtr, ExprPtr, Expr::* };
use crate::level::LevelsPtr;
use crate::env::{ Declar, Declar::* };
use crate::utils::{ List::*, Tc, IsCtx };
use crate::tc::eq::ShortCircuit::*;
use crate::tc::infer::InferFlag::*;
impl<'t, 'l : 't, 'e : 'l> ExprPtr<'l> {
pub fn whnf_core(mut self, tc : &mut Tc<'t, 'l, 'e>) -> Self {
loop {
let (fun, args) = self.unfold_apps(tc);
match (fun.read(tc), args.read(tc)) {
(Sort { level }, _) => return level.simplify(tc).new_sort(tc),
(Lambda {..}, Cons(..)) => { self = fun.whnf_lambda(args, tc); },
(Let { val, body, .. }, _) => { self = body.inst1(val, tc).foldl_apps(args, tc) },
(Const { name, levels }, _)=> {
if let Some(reduced) = reduce_quot(name, args, tc).or_else(|| reduce_ind_rec(name, levels, args, tc)) {
self = reduced;
} else {
return self
}
},
_ => return self
}
}
}
pub fn whnf_lambda(mut self, mut args : ExprsPtr<'l>, tc : &mut Tc<'t, 'l, 'e>) -> Self {
let mut acc = Nil::<Expr>.alloc(tc);
while let (Lambda { body, .. }, Cons(hd, tl)) = (self.read(tc), args.read(tc)) {
acc = Cons(hd, acc).alloc(tc);
args = tl;
self = body;
}
self.inst(acc, tc).foldl_apps(args, tc)
}
pub fn whnf(self, tc : &mut Tc<'t, 'l, 'e>) -> Self {
if let Some(cached) = tc.cache.whnf_cache.get(&self).copied() {
cached
} else {
let mut cursor = self;
loop {
let whnfd = cursor.whnf_core(tc);
if let Some(next_term) = whnfd.unfold_def(tc) {
cursor = next_term;
} else {
tc.cache.whnf_cache.insert(self, whnfd);
return whnfd
}
}
}
}
pub fn is_delta(self, tc : &mut Tc<'t, 'l, 'e>) -> Option<Declar<'l>> {
let (fun, _) = self.unfold_apps(tc);
let (c_name, _) = fun.try_const_info(tc)?;
match tc.get_declar(&c_name) {
Some(d @ Definition {..}) => Some(d),
_ => None
}
}
pub fn unfold_def(self, tc : &mut Tc<'t, 'l, 'e>) -> Option<Self> {
let (fun, args) = self.unfold_apps(tc);
let (c_name, c_levels) = fun.try_const_info(tc)?;
match tc.get_declar(&c_name)? {
Definition { uparams, val, .. }
if c_levels.len(tc) == uparams.len(tc) => {
let def_val = val.subst(uparams, c_levels, tc);
Some(def_val.foldl_apps(args, tc))
},
_ => None
}
}
fn mk_nullary_cnstr(self, num_params : u16, tc : &mut Tc<'t, 'l, 'e>) -> Option<Self> {
let (fun, args) = self.unfold_apps(tc);
let (c_name, c_levels) = fun.try_const_info(tc)?;
let cnstr_name = match tc.get_declar(&c_name)? {
Inductive { all_cnstr_names, .. } => all_cnstr_names.get(0, tc),
_ => None
}?;
let new_const = <ExprPtr>::new_const(cnstr_name, c_levels, tc);
Some(new_const.foldl_apps(args.take(num_params as usize, tc), tc))
}
fn to_cnstr_when_k(
self,
rec_name : NamePtr<'l>,
rec_is_k : bool,
rec_num_params : u16,
tc : &mut Tc<'t, 'l, 'e>
) -> Option<Self> {
ret_none_if! { !rec_is_k };
let app_type = self.infer(InferOnly, tc).whnf(tc);
ret_none_if! { app_type.unfold_apps_fun(tc).try_const_info(tc)?.0 != rec_name.get_prefix(tc) };
let new_cnstr_app = app_type.mk_nullary_cnstr(rec_num_params, tc)?;
let new_type = new_cnstr_app.infer(InferOnly, tc);
if let EqShort = app_type.def_eq(new_type, tc) {
Some(new_cnstr_app)
} else {
None
}
}
}
fn reduce_quot<'t, 'l : 't, 'e : 'l>(
c_name : NamePtr<'l>,
args : ExprsPtr<'l>,
tc : &mut Tc<'t, 'l, 'e>
) -> Option<ExprPtr<'l>> {
let (qmk_n, qlift_n, qind_n) = tc.quot_names()?;
let (qmk, f, rest) = if c_name == qlift_n {
(args.get(5, tc)?.whnf(tc), args.get(3, tc)?, args.skip(6, tc))
} else if c_name == qind_n {
(args.get(4, tc)?.whnf(tc), args.get(3, tc)?, args.skip(5, tc))
} else {
return None
};
ret_none_if! { qmk_n != qmk.unfold_apps_fun(tc).try_const_info(tc)?.0 };
let appd = match qmk.read(tc) {
App { arg, .. } => f.new_app(arg, tc),
_ => unreachable!("bad quot_rec app")
};
Some(appd.foldl_apps(rest, tc))
}
fn reduce_ind_rec<'t, 'l : 't, 'e : 'l>(
c_name : NamePtr<'l>,
c_levels : LevelsPtr<'l>,
args : ExprsPtr<'l>,
tc : &mut Tc<'t, 'l, 'e>
) -> Option<ExprPtr<'l>> {
let recursor = match tc.get_declar(&c_name)? {
r @ Recursor {..} => r,
_ => return None
};
let take_size = recursor.rec_num_params()?
+ recursor.rec_num_motives()?
+ recursor.rec_num_minors()?;
ret_none_if! { recursor.rec_major_idx()? as usize >= args.len(tc) };
ret_none_if! { c_levels.len(tc) != recursor.uparams().len(tc) };
let major = args.get(recursor.rec_major_idx()? as usize, tc)?;
let major = major.to_cnstr_when_k(
recursor.name(),
recursor.rec_is_k()?,
recursor.rec_num_params()?,
tc
).unwrap_or(major);
let major = major.whnf(tc);
let (_, major_args) = major.unfold_apps(tc);
let rule = recursor.get_rec_rule(major, tc)?.read(tc);
let num_params = major_args.len(tc).checked_sub(rule.num_fields as usize)?;
let end_apps = major_args.skip(num_params, tc).take(rule.num_fields as usize, tc);
let r = rule.val
.subst(recursor.uparams(), c_levels, tc)
.foldl_apps(args.take(take_size as usize, tc), tc)
.foldl_apps(end_apps, tc)
.foldl_apps(args.skip((recursor.rec_major_idx()? + 1) as usize, tc), tc);
Some(r)
} |
//! This example demonstrates how [`CompactTable`] is limited to single
//! line rows.
//!
//! * Note how the multiline data is accepted, but then truncated in the display.
use tabled::{settings::Style, tables::CompactTable};
fn main() {
let data = [
["De\nbi\nan", "1.1.1.1", "true"],
["Arch", "127.1.1.1", "true"],
["Manjaro", "A\nr\nc\nh", "true"],
];
let _table = CompactTable::from(data).with(Style::psql());
#[cfg(feature = "std")]
println!("{}", _table.to_string());
}
|
extern crate mio;
use std::net::{SocketAddr};
use std::collections::HashMap;
use mio::{Events, Poll, Ready, PollOpt, Token};
use mio::net::{TcpListener, TcpStream};
struct WebSocketServer {
socket: TcpListener,
clients: HashMap<Token, TcpStream>,
token_counter: usize
}
// Setup some tokens to allow us to identify which event is
// for which socket.
const SERVER: Token = Token(0);
const CLIENT: Token = Token(1);
fn main() {
// Setup the server socket
let addr = "127.0.0.1:13265".parse::<SocketAddr>().unwrap();
let server = TcpListener::bind(&addr).unwrap();
// Poll + registration
let poll = Poll::new().unwrap();
poll.register(
&server,
SERVER,
Ready::readable(),
PollOpt::edge()
).unwrap();
// Define events
let mut events = Events::with_capacity(1024);
println!("Starting the loop");
loop {
// Why does everything get called with unwrap?
// Poll subscribes to Event stream
poll.poll(&mut events, None).unwrap();
for event in events.iter() {
match event.token() {
SERVER => {
// Accept and drop the socket immediately, this will close
// the socket and notify the client of the EOF.
let _ = server.accept();
}
CLIENT => {
// The server just shuts down the socket
// exit from our event loop.
return;
}
_ => unreachable!(),
}
}
}
} |
use reqwest::header::CONTENT_TYPE;
use std::fmt::Debug;
use telegram_types::bot::methods::{ChatTarget, GetUpdates, Method, SendDocument, TelegramResult};
use telegram_types::bot::types::{FileToSend, InputFile, Message, Update};
async fn make_request<T: Method + Debug>(data: &T) -> TelegramResult<T::Item> {
let token = std::env::var("BOT_TOKEN").unwrap();
let client = reqwest::Client::new();
let res = client
.post(T::url(&*token))
.header(CONTENT_TYPE, "application/json")
.body(serde_json::to_string(data).unwrap())
.send()
.await
.unwrap();
let res = res.text().await.unwrap();
serde_json::from_str(&res).unwrap()
}
async fn upload(chat_id: ChatTarget<'_>) -> TelegramResult<Message> {
let file_field = "document";
let action = SendDocument::new(chat_id, FileToSend::InputFile(InputFile::new(file_field)));
let token = std::env::var("BOT_TOKEN").unwrap();
let client = reqwest::Client::new();
let url = format!(
"{}?{}",
SendDocument::url(&*token),
serde_urlencoded::to_string(action).unwrap()
);
let part = reqwest::multipart::Part::text("hello, world")
.file_name("hello.txt")
.mime_str("text/plain")
.unwrap();
let form = reqwest::multipart::Form::new().part(file_field, part);
let res = client
.post(url)
.header(CONTENT_TYPE, "multipart/form-data")
.multipart(form)
.send()
.await
.unwrap();
serde_json::from_slice(&*res.bytes().await.unwrap()).unwrap()
}
#[tokio::main]
async fn main() {
use telegram_types::bot::types::UpdateContent as Content;
let mut get_update = GetUpdates::new();
loop {
let updates: Vec<Update> = make_request(&get_update).await.result.unwrap();
for update in updates {
// workaround for: https://github.com/serde-rs/serde/issues/1626
let content = update.content.unwrap_or_default();
match content {
Content::Message(message) => {
if let Some(text) = message.text.as_ref() {
let chat_id = ChatTarget::Id(message.chat.id);
if text.contains("file") {
let sent = upload(chat_id).await;
dbg!(sent);
}
}
}
_ => {}
}
get_update.offset(update.update_id + 1);
}
}
}
|
use std::sync::Arc;
use async_graphql::{Context, EmptySubscription, Object, Result, Schema};
use crate::{domains::counter::Counter, port::CounterRepository};
pub struct QueryRoot;
#[Object]
impl QueryRoot {
async fn find_counter(&self, ctx: &Context<'_>, name: String) -> Result<CounterResolver> {
let counter_repo = ctx.data::<Arc<dyn CounterRepository>>()?;
let counter = counter_repo.find_by_name(name).await?;
Ok(CounterResolver { fetched: counter })
}
}
struct CounterResolver {
fetched: Counter,
}
#[Object]
impl CounterResolver {
async fn count(&self) -> i32 {
self.fetched.count
}
async fn name(&self) -> &str {
&self.fetched.name
}
}
pub struct MutationRoot;
#[Object]
impl MutationRoot {
async fn mutate_count(&self, ctx: &Context<'_>, name: String, count: i32) -> Result<bool> {
let counter_repo = ctx.data::<Arc<dyn CounterRepository>>()?;
Ok(counter_repo.mutate_count(name, count).await.is_ok())
}
}
pub fn build_schema(
counter_repo: Arc<dyn CounterRepository>,
) -> Schema<QueryRoot, MutationRoot, EmptySubscription> {
Schema::build(QueryRoot, MutationRoot, EmptySubscription)
.data(counter_repo)
.finish()
}
|
#[macro_use] extern crate lazy_static;
use std::num::NonZeroU32;
use std::convert::TryInto;
#[derive(Eq, PartialEq, Hash, Copy, Clone, Debug)]
pub enum Encoding {
Unicode,
AdobeStandard,
AdobeExpert,
AdobeSymbol,
AdobeZdingbat,
WinAnsiEncoding,
}
pub enum Transcoder {
Id,
Forward(&'static ForwardMap), // X to to unicode
Reverse(&'static ReverseMap), // unicode to X
Both(&'static ForwardMap, &'static ReverseMap) // X to unicode to Y
}
impl Transcoder {
pub fn translate(&self, codepoint: u32) -> Option<u32> {
match self {
Transcoder::Id => Some(codepoint),
Transcoder::Forward(forward) => {
codepoint.try_into().ok()
.and_then(|b| forward.get(b))
.map(|c| c as u32)
}
Transcoder::Reverse(reverse) => reverse.get(codepoint).map(|b| b as u32),
Transcoder::Both(forward, reverse) => {
codepoint.try_into().ok()
.and_then(|b| forward.get(b))
.and_then(|c| reverse.get(c as u32))
.map(|b| b as u32)
}
}
}
}
impl Encoding {
pub fn forward_map(self) -> Option<&'static ForwardMap> {
match self {
Encoding::AdobeStandard => Some(&STANDARD),
Encoding::AdobeSymbol => Some(&SYMBOL),
Encoding::AdobeZdingbat => Some(&ZDINGBAT),
Encoding::WinAnsiEncoding => Some(&WINANSI),
_ => None
}
}
pub fn reverse_map(self) -> Option<&'static ReverseMap> {
match self {
Encoding::AdobeStandard => Some(&UNICODE_TO_STANDARD),
Encoding::AdobeSymbol => Some(&UNICODE_TO_SYMBOL),
Encoding::AdobeZdingbat => Some(&UNICODE_TO_ZDINGBAT),
Encoding::WinAnsiEncoding => Some(&UNICODE_TO_WINANSI),
_ => None
}
}
pub fn to(self, dest: Encoding) -> Option<Transcoder> {
match (self, dest) {
(source, dest) if source == dest => Some(Transcoder::Id),
(source, Encoding::Unicode) => source.forward_map().map(|map| Transcoder::Forward(map)),
(Encoding::Unicode, dest) => dest.reverse_map().map(|map| Transcoder::Reverse(map)),
(source, dest) => source.forward_map()
.and_then(|forward|
dest.reverse_map().map(|reverse| Transcoder::Both(forward, reverse))
)
}
}
}
pub struct ForwardMap([Option<Entry>; 256]);
impl ForwardMap {
pub fn get(&self, codepoint: u8) -> Option<char> {
self.0[codepoint as usize].map(|e| e.as_char())
}
}
pub struct ReverseMap {
chars: Vec<(u32, u8)>
}
impl ReverseMap {
fn new(forward: &ForwardMap) -> ReverseMap {
let mut chars: Vec<_> = forward.0.iter().enumerate()
.filter_map(|(i, e)| e.map(|e| (e.as_u32(), i as u8)))
.collect();
chars.sort();
ReverseMap { chars }
}
pub fn get(&self, c: u32) -> Option<u8> {
self.chars.binary_search_by_key(&c, |&(c, _)| c).ok().map(|idx| self.chars[idx].1)
}
}
lazy_static! {
static ref UNICODE_TO_STANDARD: ReverseMap = ReverseMap::new(&STANDARD);
static ref UNICODE_TO_SYMBOL: ReverseMap = ReverseMap::new(&SYMBOL);
static ref UNICODE_TO_ZDINGBAT: ReverseMap = ReverseMap::new(&ZDINGBAT);
static ref UNICODE_TO_WINANSI: ReverseMap = ReverseMap::new(&WINANSI);
}
#[derive(Copy, Clone)]
pub struct Entry(NonZeroU32);
impl Entry {
const fn new(c: char) -> Entry {
Entry(
unsafe {
NonZeroU32::new_unchecked(c as u32)
}
)
}
pub fn as_char(&self) -> char {
std::char::from_u32(self.0.get()).unwrap()
}
pub fn as_u32(&self) -> u32 {
self.0.get()
}
}
// we rely on the encoding not producing '\0'.
const fn c(c: char) -> Option<Entry> {
Some(Entry::new(c))
}
pub static STANDARD: ForwardMap = ForwardMap(include!("stdenc.rs"));
pub static SYMBOL: ForwardMap = ForwardMap(include!("symbol.rs"));
pub static ZDINGBAT: ForwardMap = ForwardMap(include!("zdingbat.rs"));
pub static WINANSI: ForwardMap = ForwardMap(include!("cp1252.rs"));
#[test]
fn test_forward() {
assert_eq!(STANDARD.get(0xD0), Some('\u{2014}'));
}
#[test]
fn test_reverse() {
assert_eq!(UNICODE_TO_STANDARD.get(0x2014), Some(0xD0));
}
|
use super::*;
#[test]
fn select_1() {
assert_eq!(
Query::select()
.columns(vec![Char::Character, Char::SizeW, Char::SizeH])
.from(Char::Table)
.limit(10)
.offset(100)
.to_string(PostgresQueryBuilder),
r#"SELECT "character", "size_w", "size_h" FROM "character" LIMIT 10 OFFSET 100"#
);
}
#[test]
fn select_2() {
assert_eq!(
Query::select()
.columns(vec![Char::Character, Char::SizeW, Char::SizeH])
.from(Char::Table)
.and_where(Expr::col(Char::SizeW).eq(3))
.to_string(PostgresQueryBuilder),
r#"SELECT "character", "size_w", "size_h" FROM "character" WHERE "size_w" = 3"#
);
}
#[test]
fn select_3() {
assert_eq!(
Query::select()
.columns(vec![Char::Character, Char::SizeW, Char::SizeH])
.from(Char::Table)
.and_where(Expr::col(Char::SizeW).eq(3))
.and_where(Expr::col(Char::SizeH).eq(4))
.to_string(PostgresQueryBuilder),
r#"SELECT "character", "size_w", "size_h" FROM "character" WHERE "size_w" = 3 AND "size_h" = 4"#
);
}
#[test]
fn select_4() {
assert_eq!(
Query::select()
.columns(vec![Glyph::Aspect])
.from_subquery(
Query::select()
.columns(vec![Glyph::Image, Glyph::Aspect])
.from(Glyph::Table)
.take(),
Alias::new("subglyph")
)
.to_string(PostgresQueryBuilder),
r#"SELECT "aspect" FROM (SELECT "image", "aspect" FROM "glyph") AS "subglyph""#
);
}
#[test]
fn select_5() {
assert_eq!(
Query::select()
.column((Glyph::Table, Glyph::Image))
.from(Glyph::Table)
.and_where(Expr::tbl(Glyph::Table, Glyph::Aspect).is_in(vec![3, 4]))
.to_string(PostgresQueryBuilder),
r#"SELECT "glyph"."image" FROM "glyph" WHERE "glyph"."aspect" IN (3, 4)"#
);
}
#[test]
fn select_6() {
assert_eq!(
Query::select()
.columns(vec![Glyph::Aspect,])
.exprs(vec![Expr::col(Glyph::Image).max(),])
.from(Glyph::Table)
.group_by_columns(vec![Glyph::Aspect,])
.and_having(Expr::col(Glyph::Aspect).gt(2))
.to_string(PostgresQueryBuilder),
r#"SELECT "aspect", MAX("image") FROM "glyph" GROUP BY "aspect" HAVING "aspect" > 2"#
);
}
#[test]
fn select_7() {
assert_eq!(
Query::select()
.columns(vec![Glyph::Aspect,])
.from(Glyph::Table)
.and_where(Expr::expr(Expr::col(Glyph::Aspect).if_null(0)).gt(2))
.to_string(PostgresQueryBuilder),
r#"SELECT "aspect" FROM "glyph" WHERE COALESCE("aspect", 0) > 2"#
);
}
#[test]
fn select_8() {
assert_eq!(
Query::select()
.columns(vec![Char::Character,])
.from(Char::Table)
.left_join(
Font::Table,
Expr::tbl(Char::Table, Char::FontId).equals(Font::Table, Font::Id)
)
.to_string(PostgresQueryBuilder),
r#"SELECT "character" FROM "character" LEFT JOIN "font" ON "character"."font_id" = "font"."id""#
);
}
#[test]
fn select_9() {
assert_eq!(
Query::select()
.columns(vec![Char::Character,])
.from(Char::Table)
.left_join(
Font::Table,
Expr::tbl(Char::Table, Char::FontId).equals(Font::Table, Font::Id)
)
.inner_join(
Glyph::Table,
Expr::tbl(Char::Table, Char::Character).equals(Glyph::Table, Glyph::Image)
)
.to_string(PostgresQueryBuilder),
r#"SELECT "character" FROM "character" LEFT JOIN "font" ON "character"."font_id" = "font"."id" INNER JOIN "glyph" ON "character"."character" = "glyph"."image""#
);
}
#[test]
fn select_10() {
assert_eq!(
Query::select()
.columns(vec![Char::Character,])
.from(Char::Table)
.left_join(
Font::Table,
Expr::tbl(Char::Table, Char::FontId)
.equals(Font::Table, Font::Id)
.and(Expr::tbl(Char::Table, Char::FontId).equals(Font::Table, Font::Id))
)
.to_string(PostgresQueryBuilder),
r#"SELECT "character" FROM "character" LEFT JOIN "font" ON ("character"."font_id" = "font"."id") AND ("character"."font_id" = "font"."id")"#
);
}
#[test]
fn select_11() {
assert_eq!(
Query::select()
.columns(vec![Glyph::Aspect,])
.from(Glyph::Table)
.and_where(Expr::expr(Expr::col(Glyph::Aspect).if_null(0)).gt(2))
.order_by(Glyph::Image, Order::Desc)
.order_by((Glyph::Table, Glyph::Aspect), Order::Asc)
.to_string(PostgresQueryBuilder),
r#"SELECT "aspect" FROM "glyph" WHERE COALESCE("aspect", 0) > 2 ORDER BY "image" DESC, "glyph"."aspect" ASC"#
);
}
#[test]
fn select_12() {
assert_eq!(
Query::select()
.columns(vec![Glyph::Aspect,])
.from(Glyph::Table)
.and_where(Expr::expr(Expr::col(Glyph::Aspect).if_null(0)).gt(2))
.order_by_columns(vec![(Glyph::Id, Order::Asc), (Glyph::Aspect, Order::Desc),])
.to_string(PostgresQueryBuilder),
r#"SELECT "aspect" FROM "glyph" WHERE COALESCE("aspect", 0) > 2 ORDER BY "id" ASC, "aspect" DESC"#
);
}
#[test]
fn select_13() {
assert_eq!(
Query::select()
.columns(vec![Glyph::Aspect,])
.from(Glyph::Table)
.and_where(Expr::expr(Expr::col(Glyph::Aspect).if_null(0)).gt(2))
.order_by_columns(vec![
((Glyph::Table, Glyph::Id), Order::Asc),
((Glyph::Table, Glyph::Aspect), Order::Desc),
])
.to_string(PostgresQueryBuilder),
r#"SELECT "aspect" FROM "glyph" WHERE COALESCE("aspect", 0) > 2 ORDER BY "glyph"."id" ASC, "glyph"."aspect" DESC"#
);
}
#[test]
fn select_14() {
assert_eq!(
Query::select()
.columns(vec![Glyph::Id, Glyph::Aspect,])
.expr(Expr::col(Glyph::Image).max())
.from(Glyph::Table)
.group_by_columns(vec![
(Glyph::Table, Glyph::Id),
(Glyph::Table, Glyph::Aspect),
])
.and_having(Expr::col(Glyph::Aspect).gt(2))
.to_string(PostgresQueryBuilder),
r#"SELECT "id", "aspect", MAX("image") FROM "glyph" GROUP BY "glyph"."id", "glyph"."aspect" HAVING "aspect" > 2"#
);
}
#[test]
fn select_15() {
assert_eq!(
Query::select()
.columns(vec![Char::Character])
.from(Char::Table)
.and_where(Expr::col(Char::FontId).is_null())
.to_string(PostgresQueryBuilder),
r#"SELECT "character" FROM "character" WHERE "font_id" IS NULL"#
);
}
#[test]
fn select_16() {
assert_eq!(
Query::select()
.columns(vec![Char::Character])
.from(Char::Table)
.and_where(Expr::col(Char::FontId).is_null())
.and_where(Expr::col(Char::Character).is_not_null())
.to_string(PostgresQueryBuilder),
r#"SELECT "character" FROM "character" WHERE "font_id" IS NULL AND "character" IS NOT NULL"#
);
}
#[test]
fn select_17() {
assert_eq!(
Query::select()
.columns(vec![(Glyph::Table, Glyph::Image),])
.from(Glyph::Table)
.and_where(Expr::tbl(Glyph::Table, Glyph::Aspect).between(3, 5))
.to_string(PostgresQueryBuilder),
r#"SELECT "glyph"."image" FROM "glyph" WHERE "glyph"."aspect" BETWEEN 3 AND 5"#
);
}
#[test]
fn select_18() {
assert_eq!(
Query::select()
.columns(vec![Glyph::Aspect,])
.from(Glyph::Table)
.and_where(Expr::col(Glyph::Aspect).between(3, 5))
.and_where(Expr::col(Glyph::Aspect).not_between(8, 10))
.to_string(PostgresQueryBuilder),
r#"SELECT "aspect" FROM "glyph" WHERE ("aspect" BETWEEN 3 AND 5) AND ("aspect" NOT BETWEEN 8 AND 10)"#
);
}
#[test]
fn select_19() {
assert_eq!(
Query::select()
.columns(vec![Char::Character])
.from(Char::Table)
.and_where(Expr::col(Char::Character).eq("A"))
.to_string(PostgresQueryBuilder),
r#"SELECT "character" FROM "character" WHERE "character" = 'A'"#
);
}
#[test]
fn select_20() {
assert_eq!(
Query::select()
.column(Char::Character)
.from(Char::Table)
.and_where(Expr::col(Char::Character).like("A"))
.to_string(PostgresQueryBuilder),
r#"SELECT "character" FROM "character" WHERE "character" LIKE 'A'"#
);
}
#[test]
fn select_21() {
assert_eq!(
Query::select()
.columns(vec![Char::Character])
.from(Char::Table)
.or_where(Expr::col(Char::Character).like("A%"))
.or_where(Expr::col(Char::Character).like("%B"))
.or_where(Expr::col(Char::Character).like("%C%"))
.to_string(PostgresQueryBuilder),
r#"SELECT "character" FROM "character" WHERE "character" LIKE 'A%' OR "character" LIKE '%B' OR "character" LIKE '%C%'"#
);
}
#[test]
fn select_22() {
assert_eq!(
Query::select()
.column(Char::Character)
.from(Char::Table)
.cond_where(
Cond::all()
.add(
Cond::any().add(Expr::col(Char::Character).like("C")).add(
Expr::col(Char::Character)
.like("D")
.and(Expr::col(Char::Character).like("E"))
)
)
.add(
Expr::col(Char::Character)
.like("F")
.or(Expr::col(Char::Character).like("G"))
)
)
.to_string(PostgresQueryBuilder),
r#"SELECT "character" FROM "character" WHERE ("character" LIKE 'C' OR (("character" LIKE 'D') AND ("character" LIKE 'E'))) AND (("character" LIKE 'F') OR ("character" LIKE 'G'))"#
);
}
#[test]
fn select_23() {
assert_eq!(
Query::select()
.column(Char::Character)
.from(Char::Table)
.and_where_option(None)
.to_string(PostgresQueryBuilder),
r#"SELECT "character" FROM "character""#
);
}
#[test]
fn select_24() {
assert_eq!(
Query::select()
.column(Char::Character)
.from(Char::Table)
.conditions(
true,
|x| {
x.and_where(Expr::col(Char::FontId).eq(5));
},
|_| ()
)
.to_string(PostgresQueryBuilder),
r#"SELECT "character" FROM "character" WHERE "font_id" = 5"#
);
}
#[test]
fn select_25() {
assert_eq!(
Query::select()
.column(Char::Character)
.from(Char::Table)
.and_where(
Expr::col(Char::SizeW)
.mul(2)
.equals(Expr::col(Char::SizeH).div(2))
)
.to_string(PostgresQueryBuilder),
r#"SELECT "character" FROM "character" WHERE "size_w" * 2 = "size_h" / 2"#
);
}
#[test]
fn select_26() {
assert_eq!(
Query::select()
.column(Char::Character)
.from(Char::Table)
.and_where(
Expr::expr(Expr::col(Char::SizeW).add(1))
.mul(2)
.equals(Expr::expr(Expr::col(Char::SizeH).div(2)).sub(1))
)
.to_string(PostgresQueryBuilder),
r#"SELECT "character" FROM "character" WHERE ("size_w" + 1) * 2 = ("size_h" / 2) - 1"#
);
}
#[test]
fn select_27() {
assert_eq!(
Query::select()
.columns(vec![Char::Character, Char::SizeW, Char::SizeH])
.from(Char::Table)
.and_where(Expr::col(Char::SizeW).eq(3))
.and_where(Expr::col(Char::SizeH).eq(4))
.and_where(Expr::col(Char::SizeH).eq(5))
.to_string(PostgresQueryBuilder),
r#"SELECT "character", "size_w", "size_h" FROM "character" WHERE "size_w" = 3 AND "size_h" = 4 AND "size_h" = 5"#
);
}
#[test]
fn select_28() {
assert_eq!(
Query::select()
.columns(vec![Char::Character, Char::SizeW, Char::SizeH])
.from(Char::Table)
.or_where(Expr::col(Char::SizeW).eq(3))
.or_where(Expr::col(Char::SizeH).eq(4))
.or_where(Expr::col(Char::SizeH).eq(5))
.to_string(PostgresQueryBuilder),
r#"SELECT "character", "size_w", "size_h" FROM "character" WHERE "size_w" = 3 OR "size_h" = 4 OR "size_h" = 5"#
);
}
#[test]
#[should_panic]
fn select_29() {
assert_eq!(
Query::select()
.columns(vec![Char::Character, Char::SizeW, Char::SizeH])
.from(Char::Table)
.and_where(Expr::col(Char::SizeW).eq(3))
.or_where(Expr::col(Char::SizeH).eq(4))
.and_where(Expr::col(Char::SizeH).eq(5))
.to_string(PostgresQueryBuilder),
r#"SELECT "character", "size_w", "size_h" FROM "character" WHERE "size_w" = 3 OR "size_h" = 4 AND "size_h" = 5"#
);
}
#[test]
fn select_30() {
assert_eq!(
Query::select()
.columns(vec![Char::Character, Char::SizeW, Char::SizeH])
.from(Char::Table)
.and_where(
Expr::col(Char::SizeW)
.mul(2)
.add(Expr::col(Char::SizeH).div(3))
.equals(Expr::value(4))
)
.to_string(PostgresQueryBuilder),
r#"SELECT "character", "size_w", "size_h" FROM "character" WHERE ("size_w" * 2) + ("size_h" / 3) = 4"#
);
}
#[test]
fn select_31() {
assert_eq!(
Query::select()
.expr((1..10_i32).fold(Expr::value(0), |expr, i| { expr.add(Expr::value(i)) }))
.to_string(PostgresQueryBuilder),
r#"SELECT 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9"#
);
}
#[test]
fn select_32() {
assert_eq!(
Query::select()
.expr_as(Expr::col(Char::Character), Alias::new("C"))
.from(Char::Table)
.to_string(PostgresQueryBuilder),
r#"SELECT "character" AS "C" FROM "character""#
);
}
#[test]
fn select_33() {
assert_eq!(
Query::select()
.column(Glyph::Image)
.from(Glyph::Table)
.and_where(
Expr::col(Glyph::Aspect)
.in_subquery(Query::select().expr(Expr::cust("3 + 2 * 2")).take())
)
.to_string(PostgresQueryBuilder),
r#"SELECT "image" FROM "glyph" WHERE "aspect" IN (SELECT 3 + 2 * 2)"#
);
}
#[test]
fn select_34a() {
assert_eq!(
Query::select()
.column(Glyph::Aspect)
.expr(Expr::col(Glyph::Image).max())
.from(Glyph::Table)
.group_by_columns(vec![Glyph::Aspect,])
.or_having(
Expr::col(Glyph::Aspect)
.gt(2)
.or(Expr::col(Glyph::Aspect).lt(8))
)
.or_having(
Expr::col(Glyph::Aspect)
.gt(12)
.and(Expr::col(Glyph::Aspect).lt(18))
)
.or_having(Expr::col(Glyph::Aspect).gt(32))
.to_string(PostgresQueryBuilder),
vec![
r#"SELECT "aspect", MAX("image") FROM "glyph" GROUP BY "aspect""#,
r#"HAVING (("aspect" > 2) OR ("aspect" < 8))"#,
r#"OR (("aspect" > 12) AND ("aspect" < 18))"#,
r#"OR "aspect" > 32"#,
]
.join(" ")
);
}
#[test]
#[should_panic]
fn select_34b() {
assert_eq!(
Query::select()
.column(Glyph::Aspect)
.expr(Expr::col(Glyph::Image).max())
.from(Glyph::Table)
.group_by_columns(vec![Glyph::Aspect,])
.or_having(
Expr::col(Glyph::Aspect)
.gt(2)
.or(Expr::col(Glyph::Aspect).lt(8))
)
.and_having(
Expr::col(Glyph::Aspect)
.gt(22)
.or(Expr::col(Glyph::Aspect).lt(28))
)
.to_string(PostgresQueryBuilder),
vec![
r#"SELECT "aspect", MAX("image") FROM "glyph" GROUP BY "aspect""#,
r#"HAVING (("aspect" > 2) OR ("aspect" < 8))"#,
r#"AND (("aspect" > 22) OR ("aspect" < 28))"#,
]
.join(" ")
);
}
#[test]
fn select_35() {
let (statement, values) = sea_query::Query::select()
.column(Glyph::Id)
.from(Glyph::Table)
.and_where(Expr::col(Glyph::Aspect).is_null())
.build(sea_query::PostgresQueryBuilder);
assert_eq!(
statement,
r#"SELECT "id" FROM "glyph" WHERE "aspect" IS NULL"#
);
assert_eq!(values.0, vec![]);
}
#[test]
fn select_36() {
let (statement, values) = sea_query::Query::select()
.column(Glyph::Id)
.from(Glyph::Table)
.cond_where(Cond::any().add(Expr::col(Glyph::Aspect).is_null()))
.build(sea_query::PostgresQueryBuilder);
assert_eq!(
statement,
r#"SELECT "id" FROM "glyph" WHERE "aspect" IS NULL"#
);
assert_eq!(values.0, vec![]);
}
#[test]
fn select_37() {
let (statement, values) = sea_query::Query::select()
.column(Glyph::Id)
.from(Glyph::Table)
.cond_where(Cond::any().add(Cond::all()).add(Cond::any()))
.build(sea_query::PostgresQueryBuilder);
assert_eq!(statement, r#"SELECT "id" FROM "glyph""#);
assert_eq!(values.0, vec![]);
}
#[test]
fn select_38() {
let (statement, values) = sea_query::Query::select()
.column(Glyph::Id)
.from(Glyph::Table)
.cond_where(
Cond::any()
.add(Expr::col(Glyph::Aspect).is_null())
.add(Expr::col(Glyph::Aspect).is_not_null()),
)
.build(sea_query::PostgresQueryBuilder);
assert_eq!(
statement,
r#"SELECT "id" FROM "glyph" WHERE "aspect" IS NULL OR "aspect" IS NOT NULL"#
);
assert_eq!(values.0, vec![]);
}
#[test]
fn select_39() {
let (statement, values) = sea_query::Query::select()
.column(Glyph::Id)
.from(Glyph::Table)
.cond_where(
Cond::all()
.add(Expr::col(Glyph::Aspect).is_null())
.add(Expr::col(Glyph::Aspect).is_not_null()),
)
.build(sea_query::PostgresQueryBuilder);
assert_eq!(
statement,
r#"SELECT "id" FROM "glyph" WHERE "aspect" IS NULL AND "aspect" IS NOT NULL"#
);
assert_eq!(values.0, vec![]);
}
#[test]
fn select_40() {
let statement = sea_query::Query::select()
.column(Glyph::Id)
.from(Glyph::Table)
.cond_where(any![
Expr::col(Glyph::Aspect).is_null(),
all![
Expr::col(Glyph::Aspect).is_not_null(),
Expr::col(Glyph::Aspect).lt(8)
]
])
.to_string(sea_query::PostgresQueryBuilder);
assert_eq!(
statement,
r#"SELECT "id" FROM "glyph" WHERE "aspect" IS NULL OR ("aspect" IS NOT NULL AND "aspect" < 8)"#
);
}
#[test]
fn select_41() {
assert_eq!(
Query::select()
.columns(vec![Glyph::Aspect])
.exprs(vec![Expr::col(Glyph::Image).max()])
.from(Glyph::Table)
.group_by_columns(vec![Glyph::Aspect])
.cond_having(any![Expr::col(Glyph::Aspect).gt(2)])
.to_string(PostgresQueryBuilder),
r#"SELECT "aspect", MAX("image") FROM "glyph" GROUP BY "aspect" HAVING "aspect" > 2"#
);
}
#[test]
fn select_42() {
let statement = sea_query::Query::select()
.column(Glyph::Id)
.from(Glyph::Table)
.cond_where(
Cond::all()
.add_option(Some(Expr::col(Glyph::Aspect).lt(8)))
.add(Expr::col(Glyph::Aspect).is_not_null()),
)
.to_string(PostgresQueryBuilder);
assert_eq!(
statement,
r#"SELECT "id" FROM "glyph" WHERE "aspect" < 8 AND "aspect" IS NOT NULL"#
);
}
#[test]
fn select_43() {
let statement = sea_query::Query::select()
.column(Glyph::Id)
.from(Glyph::Table)
.cond_where(Cond::all().add_option::<SimpleExpr>(None))
.to_string(PostgresQueryBuilder);
assert_eq!(statement, r#"SELECT "id" FROM "glyph""#);
}
#[test]
#[allow(clippy::approx_constant)]
#[cfg(feature = "with-json")]
fn insert_1() {
assert_eq!(
Query::insert()
.into_table(Glyph::Table)
.json(json!({
"image": "24B0E11951B03B07F8300FD003983F03F0780060",
"aspect": 2.1345,
}))
.to_string(PostgresQueryBuilder),
r#"INSERT INTO "glyph" ("aspect", "image") VALUES (2.1345, '24B0E11951B03B07F8300FD003983F03F0780060')"#
);
}
#[test]
#[allow(clippy::approx_constant)]
fn insert_2() {
assert_eq!(
Query::insert()
.into_table(Glyph::Table)
.columns(vec![Glyph::Image, Glyph::Aspect,])
.values_panic(vec![
"04108048005887010020060000204E0180400400".into(),
3.1415.into(),
])
.to_string(PostgresQueryBuilder),
r#"INSERT INTO "glyph" ("image", "aspect") VALUES ('04108048005887010020060000204E0180400400', 3.1415)"#
);
}
#[test]
#[allow(clippy::approx_constant)]
fn insert_3() {
assert_eq!(
Query::insert()
.into_table(Glyph::Table)
.columns(vec![Glyph::Image, Glyph::Aspect,])
.values_panic(vec![
"04108048005887010020060000204E0180400400".into(),
3.1415.into(),
])
.values_panic(vec![Value::Null, 2.1345.into(),])
.to_string(PostgresQueryBuilder),
r#"INSERT INTO "glyph" ("image", "aspect") VALUES ('04108048005887010020060000204E0180400400', 3.1415), (NULL, 2.1345)"#
);
}
#[test]
#[cfg(feature = "with-chrono")]
fn insert_4() {
assert_eq!(
Query::insert()
.into_table(Glyph::Table)
.columns(vec![Glyph::Image])
.values_panic(vec![chrono::NaiveDateTime::from_timestamp(0, 0).into()])
.to_string(PostgresQueryBuilder),
"INSERT INTO \"glyph\" (\"image\") VALUES ('1970-01-01 00:00:00')"
);
}
#[test]
#[cfg(feature = "with-uuid")]
fn insert_5() {
assert_eq!(
Query::insert()
.into_table(Glyph::Table)
.columns(vec![Glyph::Image])
.values_panic(vec![uuid::Uuid::nil().into()])
.to_string(PostgresQueryBuilder),
"INSERT INTO \"glyph\" (\"image\") VALUES ('00000000-0000-0000-0000-000000000000')"
);
}
#[test]
fn update_1() {
assert_eq!(
Query::update()
.table(Glyph::Table)
.values(vec![
(Glyph::Aspect, 2.1345.into()),
(
Glyph::Image,
"24B0E11951B03B07F8300FD003983F03F0780060".into()
),
])
.and_where(Expr::col(Glyph::Id).eq(1))
.to_string(PostgresQueryBuilder),
r#"UPDATE "glyph" SET "aspect" = 2.1345, "image" = '24B0E11951B03B07F8300FD003983F03F0780060' WHERE "id" = 1"#
);
}
#[test]
#[cfg(feature = "with-json")]
fn update_2() {
assert_eq!(
Query::update()
.table(Glyph::Table)
.json(json!({
"aspect": 2.1345,
"image": "24B0E11951B03B07F8300FD003983F03F0780060",
}))
.and_where(Expr::col(Glyph::Id).eq(1))
.to_string(PostgresQueryBuilder),
r#"UPDATE "glyph" SET "aspect" = 2.1345, "image" = '24B0E11951B03B07F8300FD003983F03F0780060' WHERE "id" = 1"#
);
}
#[test]
fn update_3() {
assert_eq!(
Query::update()
.table(Glyph::Table)
.value_expr(Glyph::Aspect, Expr::cust("60 * 24 * 24"))
.values(vec![(
Glyph::Image,
"24B0E11951B03B07F8300FD003983F03F0780060".into()
),])
.and_where(Expr::col(Glyph::Id).eq(1))
.to_string(PostgresQueryBuilder),
r#"UPDATE "glyph" SET "aspect" = 60 * 24 * 24, "image" = '24B0E11951B03B07F8300FD003983F03F0780060' WHERE "id" = 1"#
);
}
#[test]
fn delete_1() {
assert_eq!(
Query::delete()
.from_table(Glyph::Table)
.and_where(Expr::col(Glyph::Id).eq(1))
.to_string(PostgresQueryBuilder),
r#"DELETE FROM "glyph" WHERE "id" = 1"#
);
}
|
use std::mem::size_of;
use std::thread::sleep;
use libc::c_uchar;
use libc::{c_int, c_void};
#[repr(C)]
#[warn(improper_ctypes)]
struct VideoParam {
width: u32,
height: u32,
fps: u32,
file_or_stream_flag: u32,
file_or_stream_url: String,
}
#[repr(C)]
#[warn(improper_ctypes)]
struct Video;
extern "C" {
fn video_malloc(x: &mut *mut Video) -> c_int;
fn video_init(x: *mut Video, video_param: *mut VideoParam) -> c_int;
fn rgb_to_yuv(x: *mut Video, rgb_buf: *mut c_uchar) -> c_int;
fn generate_rgb(x: *mut Video, rgb_buf: *mut c_uchar) -> c_void;
fn write_trail(x: *mut Video) -> c_int;
fn video_free(x: &mut *mut Video) -> c_int;
}
fn main() {
//let mut video_param_ptr: *mut VideoParam = std::ptr::null_mut();
let mut video_ptr: *mut Video = std::ptr::null_mut();
let mut video_param = VideoParam {
width: 1820,
height: 720,
fps: 25,
file_or_stream_flag: 1,
file_or_stream_url: String::from("rtmp://192.168.31.66:1935/live/demo.flv"),
};
unsafe {
let _c = video_malloc(&mut video_ptr);
video_init(video_ptr, &mut video_param);
}
let mut rgb: Vec<u8> = Vec::with_capacity(3 * size_of::<u8>() * 1820 * 720);
let d = std::time::Duration::from_micros(50);
unsafe {
for _x in 0..50000 {
sleep(d);
generate_rgb(video_ptr, rgb.as_mut_ptr());
rgb_to_yuv(video_ptr, rgb.as_mut_ptr());
}
write_trail(video_ptr);
}
unsafe {
let _c = video_free(&mut video_ptr);
}
}
|
use axum::{
http::{header, HeaderValue, Request},
middleware::Next,
response::IntoResponse,
};
use blake3::Hasher;
/// Functions related to caching and cache busting.
use cached::proc_macro::cached;
use std::{fs::File, io};
/// Generate the blake3 hash of the file at the given path.
/// Returns the hash as a string.
fn hash_file_no_cache(path: &str) -> String {
let Ok(mut file) = File::open(path) else {
panic!("Could not open static file at path: {path}")
};
let mut hasher = Hasher::new();
let Ok(_) = io::copy(&mut file, &mut hasher) else {
panic!("Could not hash static file at path: {path}")
};
hasher.finalize().to_hex().to_string()
}
/// Cached version that is only computed once.
/// The cache is only invalidated when the server is restarted.
/// This is the behavior we want for staging and production.
#[cached]
fn hash_file_with_cache(path: String) -> String {
hash_file_no_cache(&path)
}
/// Get the hash of the file at the given path.
/// For local development, pass is use_cache = false.
pub fn hash_file(path: &str, use_cache: bool) -> String {
if use_cache {
hash_file_with_cache(path.to_owned())
} else {
hash_file_no_cache(path)
}
}
/// This middleware adds a cache control header to all responses which were
/// requested for /a/* or /js/*.
/// The request must also contain a query parameter "hash" for the cache control
/// to be applied. It is then valid for one year and public.
pub async fn caching_middleware_fn<B>(request: Request<B>, next: Next<B>) -> impl IntoResponse {
let path = request.uri().path();
let is_static_file = path.starts_with("/a/") || path.starts_with("/js/");
let is_cache_busted = is_static_file
&& request
.uri()
.query()
.map_or(false, |query| query.contains("hash"));
let mut response = next.run(request).await;
if is_static_file && is_cache_busted {
response.headers_mut().insert(
header::CACHE_CONTROL,
HeaderValue::from_static("public, max-age=31536000"),
);
}
response
}
|
use std::collections::HashMap;
use std::thread;
use std::str;
use std::ops::Deref;
use std::sync::{mpsc, Arc, Mutex};
use websocket::{self, server, stream, sender, Sender, Receiver, Message};
use rustc_serialize::json;
const WS_ADDR: &'static str = "0.0.0.0:1981";
#[derive(Debug, Clone)]
#[derive(RustcDecodable, RustcEncodable)]
/// Represents a single, atomic action taken by a chat member.
///
/// DO NOT MODIFY: the JavaScript relies on this!
enum ChatAction {
Connect { addr: String },
Disconnect { addr: String },
Msg { user: String, text: String },
}
/// Spawn a WebSocket listener thread.
pub fn start() {
thread::spawn(listen);
}
type WebSocketClients = Arc<Mutex<HashMap<String, sender::Sender<stream::WebSocketStream>>>>;
type WebSocketConnection = server::Connection<stream::WebSocketStream, stream::WebSocketStream>;
/// Create the relay MPSC (multi-producer/single-consumer) channel, spawn the
/// relay thread, then listen for WebSocket clients and spawn their threads.
fn listen() {
let (sender, receiver) = mpsc::channel::<ChatAction>();
// ws_senders collects all clients' websocket senders, so relayer can broadcast all relay
// message.
let ws_senders: WebSocketClients = Arc::new(Mutex::new(HashMap::new()));
{
let ws_senders = ws_senders.clone();
thread::spawn(move || {
relay_thread(receiver, ws_senders);
});
}
let server = websocket::Server::bind(WS_ADDR).unwrap();
for connection in server {
let ws_senders = ws_senders.clone();
let sender = sender.clone();
thread::spawn(move || {
client_thread(sender, connection.unwrap(), ws_senders);
});
}
}
/// The relay thread handles all `ChatAction`s received on its MPSC channel
/// by sending them out to all of the currently connected clients.
fn relay_thread(channel: mpsc::Receiver<ChatAction>, ws_clients: WebSocketClients) {
while let Ok(action) = channel.recv() {
for (client_addr, mut ws_client) in &mut *ws_clients.lock().unwrap() {
if let ChatAction::Connect { ref addr } = action {
if addr == client_addr {
// Avoid receiving connected message for coresponding client.
continue;
}
}
json::encode(&action).map(|json| {
ws_client.send_message(&Message::text(json));
});
}
}
}
/// Each client thread waits for input (or disconnects) from its respective clients
/// and relays the appropriate messages via the relay MPSC channel.
///
/// The messages received-from and sent-to the client should be JSON objects with the same
/// form as rustc_serialize's serialization of the `ChatAction` type.
///
/// * If the client connects, a `ChatAction::Connect` will be relayed with their IP address.
///
/// * If the client disconnects, a `ChatAction::Disconnect` will be relayed with their IP address.
///
/// * If the client sends any other message (i.e. `ChatAction::Msg`), it will be relayed verbatim.
/// (But you should still deserialize and reserialize the `ChatAction` to make sure it is valid!)
fn client_thread(channel: mpsc::Sender<ChatAction>,
connection: WebSocketConnection,
ws_clients: WebSocketClients) {
let request = connection.read_request().unwrap();
// Validate the request.
request.validate().unwrap();
let response = request.accept();
let mut client = response.send().unwrap();
// Relay a connection with client's IP address.
let addr: String = client.get_mut_sender().get_mut().peer_addr().unwrap().to_string();
channel.send(ChatAction::Connect { addr: addr.clone() }).unwrap();
// Split the client, this allows the Sender and Receiver to be sent to different threads.
let (sender, mut receiver) = client.split();
// Push sender into sharing vector.
ws_clients.lock().unwrap().insert(addr.clone(), sender);
// Handle incoming message from websocket clients.
for message in receiver.incoming_messages() {
// TODO: Kill all unwrap()s.
let message: Message = message.unwrap();
let json: &str = str::from_utf8(message.payload.deref()).unwrap();
match json::decode(json) {
Ok(chat_action) => channel.send(chat_action).unwrap(),
_ => break,
}
}
// Remove sender from sharing vector.
ws_clients.lock().unwrap().remove(&addr);
channel.send(ChatAction::Disconnect { addr: addr }).unwrap();
}
|
use math::*;
use ray::Ray;
use super::geometry::Geometry;
use super::intersection::Intersection;
pub struct Sphere {
pub position: Vector3,
pub radius: f32,
}
impl Geometry for Sphere {
fn intersect(&self, ray: &Ray) -> Option<Intersection> {
let po = ray.origin - self.position;
let b = ray.direction.dot(po);
let c = po.sqr_norm() - self.radius * self.radius;
// 判別式 Δ = b^2 - a*c
let det = b * b - c;
// 交差しない
if det < 0.0 {
return None;
}
let t1 = -b - det.sqrt();
let t2 = -b + det.sqrt();
// 出射方向と反対側で交差
if t2 < EPS {
return None;
}
// 近い方が正の場合はそれを採用
// それ以外(球体内部からの交差の場合)は正の方を採用
let distance = if t1 > EPS { t1 } else { t2 };
// r = o + t * d
let position = ray.origin + ray.direction * distance;
// 法線は球体中心から外向き
let normal = (position - self.position).normalize();
Some(Intersection {
position: position,
normal: normal,
distance: distance,
})
}
}
|
use std::cmp::*;
use std::collections::*;
use std::io::*;
use std::str::FromStr;
fn read<T: FromStr>() -> T {
let stdin = stdin();
let stdin = stdin.lock();
let token: String = stdin
.bytes()
.map(|c| c.expect("failed to read char") as char)
.skip_while(|c| c.is_whitespace())
.take_while(|c| !c.is_whitespace())
.collect();
token.parse().ok().expect("failed to parse token")
}
fn gcd(mut x:i64,mut y:i64) -> i64 {
let mut r = 1;
if x < y{
std::mem::swap(&mut x,&mut y);
}
while r != 0 {
r = x % y;
x = y;
y = r;
}
x
}
fn lcm(x:i64,y:i64) -> i64{
let div = gcd(x,y);
x / div * y
}
fn main(){
let a:i64 = read();
let b:i64 = read();
println!("{} {}" gcd(a,b),lcm(a,b));
} |
use crate::enums::{Event, Font, FrameType, Key, Mode, Shortcut};
use crate::prelude::*;
use crate::utils::FlString;
use crate::window::Window;
use fltk_sys::fl;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::{
any, cmp,
ffi::{CStr, CString},
marker, mem,
os::raw,
panic, path, ptr,
sync::{
atomic::{AtomicBool, Ordering},
Mutex,
},
thread, time,
};
/// Alias Widget ptr
pub type WidgetPtr = *mut fltk_sys::widget::Fl_Widget;
/// Alias Window ptr
pub type WindowPtr = *mut fltk_sys::window::Fl_Window;
lazy_static! {
/// The currently chosen font
static ref CURRENT_FONT: Mutex<i32> = Mutex::new(0);
/// The currently chosen frame type
static ref CURRENT_FRAME: Mutex<i32> = Mutex::new(2);
/// Currently loaded fonts
static ref LOADED_FONT: Option<&'static str> = None;
/// Basically a check for global locking
static ref IS_INIT: AtomicBool = AtomicBool::new(false);
/// The fonts associated with the application
pub(crate) static ref FONTS: Mutex<Vec<String>> = Mutex::new(Vec::new());
}
/// Runs the event loop
/// # Errors
/// Returns `FailedToRun`, this is fatal to the app
pub fn run() -> Result<(), FltkError> {
unsafe {
if !IS_INIT.load(Ordering::Relaxed) {
init_all();
}
match fl::Fl_run() {
0 => Ok(()),
_ => Err(FltkError::Internal(FltkErrorKind::FailedToRun)),
}
}
}
/// Locks the main UI thread
/// # Errors
/// Returns `FailedToLock` if locking is unsopported. This is fatal to the app
pub fn lock() -> Result<(), FltkError> {
unsafe {
match fl::Fl_lock() {
0 => Ok(()),
_ => Err(FltkError::Internal(FltkErrorKind::FailedToLock)),
}
}
}
/// Set the app scheme
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum Scheme {
/// Base fltk scheming
Base,
/// inspired by the Aqua user interface on Mac OS X
Plastic,
/// inspired by the GTK+ theme
Gtk,
/// inspired by the Clearlooks Glossy scheme
Gleam,
}
/// sets the scheme of the application
pub fn set_scheme(scheme: Scheme) {
let name_str = match scheme {
Scheme::Base => "base",
Scheme::Gtk => "gtk+",
Scheme::Gleam => "gleam",
Scheme::Plastic => "plastic",
};
let name_str = CString::safe_new(name_str);
unsafe { fl::Fl_set_scheme(name_str.as_ptr()) }
}
/// Gets the scheme of the application
pub fn scheme() -> Scheme {
unsafe {
use Scheme::{Base, Gleam, Gtk, Plastic};
match fl::Fl_scheme() {
0 => Base,
1 => Gtk,
2 => Gleam,
3 => Plastic,
_ => unreachable!(),
}
}
}
/// Alias Scheme to `AppScheme`
pub type AppScheme = Scheme;
/// Unlocks the main UI thread
pub fn unlock() {
unsafe {
fl::Fl_unlock();
}
}
/// Registers a function that will be called by the main thread during the next message handling cycle
pub fn awake_callback<F: FnMut() + 'static>(cb: F) {
unsafe {
unsafe extern "C" fn shim(data: *mut raw::c_void) {
let a: *mut Box<dyn FnMut()> = data as *mut Box<dyn FnMut()>;
let f: &mut (dyn FnMut()) = &mut **a;
let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| f()));
}
let a: *mut Box<dyn FnMut()> = Box::into_raw(Box::new(Box::new(cb)));
let data: *mut raw::c_void = a as *mut raw::c_void;
let callback: fl::Fl_Awake_Handler = Some(shim);
fl::Fl_awake_callback(callback, data);
}
}
/// Trigger event loop handling in the main thread
pub fn awake() {
unsafe { fl::Fl_awake() }
}
/// Basic Application struct, used to instatiate, set the scheme and run the event loop
#[derive(Debug, Copy, Clone)]
pub struct App {}
impl App {
/// Instantiates an App type
pub fn default() -> App {
init_all();
App {}
}
/// Sets the scheme of the application
pub fn set_scheme(&mut self, scheme: Scheme) {
set_scheme(scheme);
}
/// Sets the scheme of the application
pub fn with_scheme(self, scheme: Scheme) -> App {
set_scheme(scheme);
self
}
/// Gets the scheme of the application
pub fn scheme(self) -> Scheme {
scheme()
}
/// Runs the event loop
/// # Errors
/// Can error on failure to run the application
pub fn run(self) -> Result<(), FltkError> {
run()
}
/// Wait for incoming messages.
/// Calls to redraw within wait require an explicit sleep
pub fn wait(self) -> bool {
wait()
}
/// Loads system fonts
pub fn load_system_fonts(self) -> Self {
*FONTS.lock().unwrap() = get_font_names();
self
}
/**
Loads a font from a path.
On success, returns a String with the ttf Font Family name. The font's index is always 16.
As such only one font can be loaded at a time.
The font name can be used with `Font::by_name`, and index with `Font::by_index`.
# Examples
```rust,no_run
use fltk::{prelude::*, *};
let app = app::App::default();
let font = app.load_font("font.ttf").unwrap();
let mut frame = frame::Frame::new(0, 0, 400, 100, "Hello");
frame.set_label_font(enums::Font::by_name(&font));
```
# Errors
Returns `ResourceNotFound` if the Font file was not found
*/
pub fn load_font<P: AsRef<path::Path>>(self, path: P) -> Result<String, FltkError> {
Self::load_font_(path.as_ref())
}
fn load_font_(path: &path::Path) -> Result<String, FltkError> {
if !path.exists() {
return Err::<String, FltkError>(FltkError::Internal(FltkErrorKind::ResourceNotFound));
}
if let Some(p) = path.to_str() {
let name = load_font(p)?;
Ok(name)
} else {
Err(FltkError::Internal(FltkErrorKind::ResourceNotFound))
}
}
/// Set the visual of the application
/// # Errors
/// Returns `FailedOperation` if FLTK failed to set the visual mode
pub fn set_visual(self, mode: Mode) -> Result<(), FltkError> {
set_visual(mode)
}
/// Redraws the app
pub fn redraw(self) {
redraw()
}
/// Quit the application
pub fn quit(self) {
quit()
}
}
/// Set the application's scrollbar size
pub fn set_scrollbar_size(sz: i32) {
unsafe { fl::Fl_set_scrollbar_size(sz as i32) }
}
/// Get the app's scrollbar size
pub fn scrollbar_size() -> i32 {
unsafe { fl::Fl_scrollbar_size() as i32 }
}
/// Get the grabbed window
pub fn grab() -> Option<impl WindowExt> {
unsafe {
let ptr = fl::Fl_grab();
if ptr.is_null() {
None
} else {
Some(crate::window::Window::from_widget_ptr(ptr as *mut _))
}
}
}
/// Set the current grab
pub fn set_grab<W: WindowExt>(win: Option<W>) {
unsafe {
win.map_or_else(
|| fl::Fl_set_grab(ptr::null_mut()),
|w| fl::Fl_set_grab(w.as_widget_ptr() as *mut _),
)
}
}
/// Returns the latest captured event
pub fn event() -> Event {
unsafe {
mem::transmute(fl::Fl_event())
}
}
/// Returns the presed key
pub fn event_key() -> Key {
unsafe {
mem::transmute(fl::Fl_event_key())
}
}
/// Returns the original key
pub fn event_original_key() -> Key {
unsafe {
mem::transmute(fl::Fl_event_original_key())
}
}
/// Returns whether the key is pressed or held down during the last event
pub fn event_key_down(key: Key) -> bool {
unsafe { fl::Fl_event_key_down(mem::transmute(key)) != 0 }
}
/// Returns a textual representation of the latest event
pub fn event_text() -> String {
unsafe {
let text = fl::Fl_event_text();
if text.is_null() {
String::from("")
} else {
CStr::from_ptr(text as *mut raw::c_char)
.to_string_lossy()
.to_string()
}
}
}
/// Returns the captured button event.
/// 1 for left key, 2 for middle, 3 for right
pub fn event_button() -> i32 {
unsafe { fl::Fl_event_button() }
}
/// Defines Mouse buttons
#[repr(i32)]
#[derive(Debug, Copy, Clone, PartialEq)]
#[non_exhaustive]
pub enum MouseButton {
/// Left mouse button
Left = 1,
/// Middle mouse button
Middle = 2,
/// Right mouse button
Right = 3,
}
/// Returns the captured button event
pub fn event_mouse_button() -> MouseButton {
unsafe { mem::transmute(fl::Fl_event_button()) }
}
/// Returns the number of clicks
pub fn event_clicks() -> bool {
unsafe { fl::Fl_event_clicks() != 0 }
}
/// Gets the x coordinate of the mouse in the window
pub fn event_x() -> i32 {
unsafe { fl::Fl_event_x() }
}
/// Gets the y coordinate of the mouse in the window
pub fn event_y() -> i32 {
unsafe { fl::Fl_event_y() }
}
/// Gets the x coordinate of the mouse in the screen
pub fn event_x_root() -> i32 {
unsafe { fl::Fl_event_x_root() }
}
/// Gets the y coordinate of the mouse in the screen
pub fn event_y_root() -> i32 {
unsafe { fl::Fl_event_y_root() }
}
/// Event direction with Mousewheel event
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum MouseWheel {
/// No movement
None,
/// Right movement
Right,
/// Left movement
Left,
/// Up movement
Up,
/// Down movement
Down,
}
/// Returns the current horizontal mouse scrolling associated with the Mousewheel event.
/// Returns `MouseWheel::None`, `Right` or `Left`
pub fn event_dx() -> MouseWheel {
match 0.cmp(unsafe { &fl::Fl_event_dx() }) {
cmp::Ordering::Greater => MouseWheel::Right,
cmp::Ordering::Equal => MouseWheel::None,
cmp::Ordering::Less => MouseWheel::Left,
}
}
/// Returns the current horizontal mouse scrolling associated with the Mousewheel event.
/// Returns `MouseWheel::None`, `Up` or `Down`.
/// Doesn't indicate scrolling direction which depends on system preferences
pub fn event_dy() -> MouseWheel {
match 0.cmp(unsafe { &fl::Fl_event_dy() }) {
cmp::Ordering::Greater => MouseWheel::Down,
cmp::Ordering::Equal => MouseWheel::None,
cmp::Ordering::Less => MouseWheel::Up,
}
}
/// Gets the mouse coordinates relative to the screen
pub fn get_mouse() -> (i32, i32) {
unsafe {
let mut x: i32 = 0;
let mut y: i32 = 0;
fl::Fl_get_mouse(&mut x, &mut y);
(x, y)
}
}
/// Returns the x and y coordinates of the captured event
pub fn event_coords() -> (i32, i32) {
unsafe { (fl::Fl_event_x(), fl::Fl_event_y()) }
}
/// Determines whether an event was a click
pub fn event_is_click() -> bool {
unsafe { fl::Fl_event_is_click() != 0 }
}
/// Returns the duration of an event
pub fn event_length() -> i32 {
unsafe { fl::Fl_event_length() as i32 }
}
/// Returns the state of the event
pub fn event_state() -> Shortcut {
unsafe { mem::transmute(fl::Fl_event_state()) }
}
/// Returns a pair of the width and height of the screen
pub fn screen_size() -> (f64, f64) {
unsafe { ((fl::Fl_screen_w() as f64), (fl::Fl_screen_h() as f64)) }
}
/// Returns a pair of the x & y coords of the screen
pub fn screen_coords() -> (i32, i32) {
unsafe { (fl::Fl_screen_x(), fl::Fl_screen_y()) }
}
/// Types of Clipboard contents
#[derive(Debug, Clone, Copy)]
pub enum ClipboardContent {
/// Textual content
Text,
/// Image content
Image,
}
/// Check the contents of the clipboard
pub fn clipboard_contains(content: ClipboardContent) -> bool {
use ClipboardContent::*;
let txt = match content {
Text => "text/plain",
Image => "image",
};
let txt = CString::new(txt).unwrap();
unsafe { fl::Fl_clipboard_contains(txt.as_ptr()) != 0 }
}
/// Pastes content from the clipboard
pub fn paste<T>(widget: &T)
where
T: WidgetExt,
{
assert!(!widget.was_deleted());
if clipboard_contains(ClipboardContent::Text) {
paste_text(widget)
} else if clipboard_contains(ClipboardContent::Image) {
paste_image(widget)
} else {
// Do nothing!
}
}
/// Pastes textual content from the clipboard
pub fn paste_text<T>(widget: &T)
where
T: WidgetExt,
{
assert!(!widget.was_deleted());
unsafe {
fl::Fl_paste_text(widget.as_widget_ptr() as *mut fltk_sys::fl::Fl_Widget, 1);
}
}
/// Pastes image content from the clipboard
pub fn paste_image<T>(widget: &T)
where
T: WidgetExt,
{
assert!(!widget.was_deleted());
unsafe {
fl::Fl_paste_image(widget.as_widget_ptr() as *mut fltk_sys::fl::Fl_Widget, 1);
}
}
/// Sets the callback of a widget
pub fn set_callback<F, W>(widget: &mut W, cb: F)
where
F: FnMut(&mut dyn WidgetExt),
W: WidgetExt,
{
assert!(!widget.was_deleted());
unsafe {
unsafe extern "C" fn shim(wid: *mut fltk_sys::widget::Fl_Widget, data: *mut raw::c_void) {
let a: *mut Box<dyn FnMut(&mut dyn WidgetExt)> =
data as *mut Box<dyn FnMut(&mut dyn WidgetExt)>;
let f: &mut (dyn FnMut(&mut dyn WidgetExt)) = &mut **a;
let mut wid = crate::widget::Widget::from_widget_ptr(wid);
let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| f(&mut wid)));
}
let _old_data = widget.user_data();
let a: *mut Box<dyn FnMut(&mut dyn WidgetExt)> = Box::into_raw(Box::new(Box::new(cb)));
let data: *mut raw::c_void = a as *mut raw::c_void;
let callback: fltk_sys::widget::Fl_Callback = Some(shim);
fltk_sys::widget::Fl_Widget_set_callback(widget.as_widget_ptr(), callback, data);
}
}
#[allow(clippy::missing_safety_doc)]
/**
Set a widget callback using a C style API
```rust,no_run
use fltk::{prelude::*, *};
use std::os::raw::*;
// data can be anything, even a different widget
fn cb(w: app::WidgetPtr, data: *mut c_void) {
// To access the button
let mut btn = unsafe { button::Button::from_widget_ptr(w) }; // Gets a Widget
btn.set_label("Works!");
// To access the frame
let mut frm = unsafe { widget::Widget::from_widget_ptr(data as app::WidgetPtr) };
frm.set_label("Works!");
}
let mut but = button::Button::default();
let mut frame = frame::Frame::default();
unsafe {
// If no data needs to be passed, you can pass 0 as *mut _
app::set_raw_callback(&mut but, frame.as_widget_ptr() as *mut _, Some(cb));
// Using a closure also works
app::set_raw_callback(&mut but, frame.as_widget_ptr() as *mut _, Some(|_ , _| { println!("Also works!")}));
}
```
# Safety
The function involves dereferencing externally provided raw pointers
*/
pub unsafe fn set_raw_callback<W>(
widget: &mut W,
data: *mut raw::c_void,
cb: Option<fn(WidgetPtr, *mut raw::c_void)>,
) where
W: WidgetExt,
{
assert!(!widget.was_deleted());
let cb: Option<unsafe extern "C" fn(WidgetPtr, *mut raw::c_void)> = mem::transmute(cb);
fltk_sys::widget::Fl_Widget_set_callback(widget.as_widget_ptr(), cb, data);
}
/// Return whether visible focus is shown
pub fn visible_focus() -> bool {
unsafe { fl::Fl_visible_focus() != 0 }
}
/// Show focus around widgets
pub fn set_visible_focus(flag: bool) {
unsafe { fl::Fl_set_visible_focus(flag as i32) }
}
/// Set the app's default frame type
pub fn set_frame_type(new_frame: FrameType) {
unsafe {
let new_frame = new_frame as i32;
let mut curr = CURRENT_FRAME.lock().unwrap();
fl::Fl_set_box_type(*curr, new_frame);
*curr = new_frame;
}
}
/// Get the app's frame type
pub fn frame_type() -> FrameType {
let curr = CURRENT_FRAME.lock().unwrap();
FrameType::by_index(*curr as _)
}
/// Swap the default frame type with a new frame type
pub fn swap_frame_type(new_frame: FrameType) {
unsafe {
let new_frame = new_frame as i32;
let mut curr = CURRENT_FRAME.lock().unwrap();
fl::Fl_set_box_type(56, *curr);
fl::Fl_set_box_type(*curr, new_frame);
fl::Fl_set_box_type(new_frame, 56);
*curr = new_frame;
}
}
/// Set the app's font
pub fn set_font(new_font: Font) {
unsafe {
let new_font = new_font.bits() as i32;
let mut f = CURRENT_FONT.lock().unwrap();
fl::Fl_set_font(15, *f);
fl::Fl_set_font(0, new_font);
fl::Fl_set_font(new_font, *f);
*f = new_font;
}
}
/// Set the app's font size
pub fn set_font_size(sz: u8) {
unsafe { fl::Fl_set_font_size(sz as i32) }
}
/// Get the font's name
pub fn get_font(font: Font) -> String {
unsafe {
CStr::from_ptr(fl::Fl_get_font(font.bits() as i32))
.to_string_lossy()
.to_string()
}
}
/// Initializes loaded fonts of a certain pattern `name`
pub fn set_fonts(name: &str) -> u8 {
let name = CString::safe_new(name);
unsafe { fl::Fl_set_fonts(name.as_ptr() as *mut raw::c_char) as u8 }
}
/// Gets the name of a font through its index
pub fn font_name(idx: usize) -> Option<String> {
let f = FONTS.lock().unwrap();
Some(f[idx].clone())
}
/// Returns a list of available fonts to the application
pub fn get_font_names() -> Vec<String> {
let mut vec: Vec<String> = vec![];
let cnt = set_fonts("*") as usize;
for i in 0..cnt {
let temp = unsafe {
CStr::from_ptr(fl::Fl_get_font(i as i32))
.to_string_lossy()
.to_string()
};
vec.push(temp);
}
vec
}
/// Finds the index of a font through its name
pub fn font_index(name: &str) -> Option<usize> {
let f = FONTS.lock().unwrap();
f.iter().position(|i| i == name)
}
/// Gets the number of loaded fonts
pub fn font_count() -> usize {
(*FONTS.lock().unwrap()).len()
}
/// Gets a Vector<String> of loaded fonts
pub fn fonts() -> Vec<String> {
(*FONTS.lock().unwrap()).clone()
}
/// Adds a custom handler for unhandled events
pub fn add_handler(cb: fn(Event) -> bool) {
unsafe {
let callback: Option<unsafe extern "C" fn(ev: raw::c_int) -> raw::c_int> =
Some(mem::transmute(move |ev| {
let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| cb(ev) as i32));
}));
fl::Fl_add_handler(callback);
}
}
/// Starts waiting for events.
/// Calls to redraw within wait require an explicit sleep
pub fn wait() -> bool {
unsafe {
if !IS_INIT.load(Ordering::Relaxed) {
init_all();
}
fl::Fl_wait() != 0
}
}
/// Put the thread to sleep for `dur` seconds
pub fn sleep(dur: f64) {
let dur = dur * 1000.;
thread::sleep(time::Duration::from_millis(dur as u64));
}
/// Add an idle callback to run within the event loop.
/// Calls to `WidgetExt::redraw` within the callback require an explicit sleep
pub fn add_idle<F: FnMut() + 'static>(cb: F) {
unsafe {
unsafe extern "C" fn shim(data: *mut raw::c_void) {
let a: *mut Box<dyn FnMut()> = data as *mut Box<dyn FnMut()>;
let f: &mut (dyn FnMut()) = &mut **a;
let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| f()));
}
let a: *mut Box<dyn FnMut()> = Box::into_raw(Box::new(Box::new(cb)));
let data: *mut raw::c_void = a as *mut raw::c_void;
let callback: Option<unsafe extern "C" fn(arg1: *mut raw::c_void)> = Some(shim);
fl::Fl_add_idle(callback, data);
}
}
/// Remove an idle function
pub fn remove_idle<F: FnMut() + 'static>(cb: F) {
unsafe {
unsafe extern "C" fn shim(data: *mut raw::c_void) {
let a: *mut Box<dyn FnMut()> = data as *mut Box<dyn FnMut()>;
let f: &mut (dyn FnMut()) = &mut **a;
let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| f()));
}
let a: *mut Box<dyn FnMut()> = Box::into_raw(Box::new(Box::new(cb)));
let data: *mut raw::c_void = a as *mut raw::c_void;
let callback: Option<unsafe extern "C" fn(arg1: *mut raw::c_void)> = Some(shim);
fl::Fl_remove_idle(callback, data);
}
}
/// Checks whether an idle function is installed
pub fn has_idle<F: FnMut() + 'static>(cb: F) -> bool {
unsafe {
unsafe extern "C" fn shim(data: *mut raw::c_void) {
let a: *mut Box<dyn FnMut()> = data as *mut Box<dyn FnMut()>;
let f: &mut (dyn FnMut()) = &mut **a;
let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| f()));
}
let a: *mut Box<dyn FnMut()> = Box::into_raw(Box::new(Box::new(cb)));
let data: *mut raw::c_void = a as *mut raw::c_void;
let callback: Option<unsafe extern "C" fn(arg1: *mut raw::c_void)> = Some(shim);
fl::Fl_has_idle(callback, data) != 0
}
}
/// Waits a maximum of `dur` seconds or until "something happens".
/// Returns true if an event happened (always true on windows).
/// Returns false if nothing happened.
/// # Errors
/// Can error out on X11 system if interrupted by a signal
pub fn wait_for(dur: f64) -> Result<bool, FltkError> {
unsafe {
if !IS_INIT.load(Ordering::Relaxed) {
init_all();
}
match fl::Fl_wait_for(dur) as i32 {
0 => Ok(false),
1 => Ok(true),
_ => Err(FltkError::Unknown(String::from(
"An unknown error occured!",
))),
}
}
}
/// Sends a custom message
/// # Safety
/// The type must be Send and Sync safe
pub unsafe fn awake_msg<T>(msg: T) {
fl::Fl_awake_msg(Box::into_raw(Box::from(msg)) as *mut raw::c_void);
}
#[allow(clippy::missing_safety_doc)]
/**
Receives a custom message
```rust,no_run
use fltk::{prelude::*, *};
if let Some(msg) = unsafe { app::thread_msg::<i32>() } { /* do something */ }
```
# Safety
The type must correspond to the received message
*/
pub unsafe fn thread_msg<T>() -> Option<T> {
let msg = fl::Fl_thread_msg();
if msg.is_null() {
None
} else {
let msg = Box::from_raw(msg as *const _ as *mut T);
Some(*msg)
}
}
#[repr(C)]
struct Message<T: Send + Sync> {
hash: u64,
sz: usize,
msg: T,
}
/// Creates a sender struct
#[derive(Debug, Clone, Copy)]
pub struct Sender<T: Send + Sync> {
data: marker::PhantomData<T>,
hash: u64,
sz: usize,
}
impl<T: Send + Sync> Sender<T> {
/// Sends a message
pub fn send(&self, val: T) {
let msg = Message {
hash: self.hash,
sz: self.sz,
msg: val,
};
unsafe { awake_msg(msg) }
}
}
/// Creates a receiver struct
#[derive(Debug, Clone, Copy)]
pub struct Receiver<T: Send + Sync> {
data: marker::PhantomData<T>,
hash: u64,
sz: usize,
}
impl<T: Send + Sync> Receiver<T> {
/// Receives a message
pub fn recv(&self) -> Option<T> {
let data: Option<Message<T>> = unsafe { thread_msg() };
data.and_then(|data| {
if data.sz == self.sz && data.hash == self.hash {
Some(data.msg)
} else {
None
}
})
}
}
/// Creates a channel returning a Sender and Receiver structs (mpsc)
// The implementation could really use generic statics
pub fn channel<T: Send + Sync>() -> (Sender<T>, Receiver<T>) {
let msg_sz = mem::size_of::<T>();
let type_name = any::type_name::<T>();
let mut hasher = DefaultHasher::new();
type_name.hash(&mut hasher);
let type_hash = hasher.finish();
let s = Sender {
data: marker::PhantomData,
hash: type_hash,
sz: msg_sz,
};
let r = Receiver {
data: marker::PhantomData,
hash: type_hash,
sz: msg_sz,
};
(s, r)
}
/// Returns the first window of the application
pub fn first_window() -> Option<impl WindowExt> {
unsafe {
let x = fl::Fl_first_window();
if x.is_null() {
None
} else {
let x = Window::from_widget_ptr(x as *mut fltk_sys::widget::Fl_Widget);
Some(x)
}
}
}
/// Returns the next window in order
pub fn next_window<W: WindowExt>(w: &W) -> Option<impl WindowExt> {
unsafe {
let x = fl::Fl_next_window(w.as_widget_ptr() as *const raw::c_void);
if x.is_null() {
None
} else {
let x = Window::from_widget_ptr(x as *mut fltk_sys::widget::Fl_Widget);
Some(x)
}
}
}
/// Quit the app
pub fn quit() {
if let Some(loaded_font) = *LOADED_FONT {
// Shouldn't fail
unload_font(loaded_font).unwrap_or(());
}
if let Some(wins) = windows() {
for mut i in wins {
if i.shown() {
i.hide();
}
}
}
}
/**
Adds a one-shot timeout callback. The timeout duration `tm` is indicated in seconds
Example:
```rust,no_run
use fltk::{prelude::*, *};
fn callback() {
println!("TICK");
app::repeat_timeout(1.0, callback);
}
fn main() {
let app = app::App::default();
let mut wind = window::Window::new(100, 100, 400, 300, "");
wind.show();
app::add_timeout(1.0, callback);
app.run().unwrap();
}
```
*/
pub fn add_timeout<F: FnMut() + 'static>(tm: f64, cb: F) {
unsafe {
unsafe extern "C" fn shim(data: *mut raw::c_void) {
let a: *mut Box<dyn FnMut()> = data as *mut Box<dyn FnMut()>;
let f: &mut (dyn FnMut()) = &mut **a;
let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| f()));
}
let a: *mut Box<dyn FnMut()> = Box::into_raw(Box::new(Box::new(cb)));
let data: *mut raw::c_void = a as *mut raw::c_void;
let callback: Option<unsafe extern "C" fn(arg1: *mut raw::c_void)> = Some(shim);
fltk_sys::fl::Fl_add_timeout(tm, callback, data);
}
}
/**
Repeats a timeout callback from the expiration of the previous timeout.
You may only call this method inside a timeout callback.
The timeout duration `tm` is indicated in seconds
Example:
```rust,no_run
use fltk::{prelude::*, *};
fn callback() {
println!("TICK");
app::repeat_timeout(1.0, callback);
}
fn main() {
let app = app::App::default();
let mut wind = window::Window::new(100, 100, 400, 300, "");
wind.show();
app::add_timeout(1.0, callback);
app.run().unwrap();
}
```
*/
pub fn repeat_timeout<F: FnMut() + 'static>(tm: f64, cb: F) {
unsafe {
unsafe extern "C" fn shim(data: *mut raw::c_void) {
let a: *mut Box<dyn FnMut()> = data as *mut Box<dyn FnMut()>;
let f: &mut (dyn FnMut()) = &mut **a;
let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| f()));
}
let a: *mut Box<dyn FnMut()> = Box::into_raw(Box::new(Box::new(cb)));
let data: *mut raw::c_void = a as *mut raw::c_void;
let callback: Option<unsafe extern "C" fn(arg1: *mut raw::c_void)> = Some(shim);
fltk_sys::fl::Fl_repeat_timeout(tm, callback, data);
}
}
/// Removes a timeout callback
pub fn remove_timeout<F: FnMut() + 'static>(cb: F) {
unsafe {
unsafe extern "C" fn shim(data: *mut raw::c_void) {
let a: *mut Box<dyn FnMut()> = data as *mut Box<dyn FnMut()>;
let f: &mut (dyn FnMut()) = &mut **a;
let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| f()));
}
let a: *mut Box<dyn FnMut()> = Box::into_raw(Box::new(Box::new(cb)));
let data: *mut raw::c_void = a as *mut raw::c_void;
let callback: Option<unsafe extern "C" fn(arg1: *mut raw::c_void)> = Some(shim);
fltk_sys::fl::Fl_remove_timeout(callback, data);
}
}
/// Check whether a timeout is installed
pub fn has_timeout<F: FnMut() + 'static>(cb: F) -> bool {
unsafe {
unsafe extern "C" fn shim(data: *mut raw::c_void) {
let a: *mut Box<dyn FnMut()> = data as *mut Box<dyn FnMut()>;
let f: &mut (dyn FnMut()) = &mut **a;
let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| f()));
}
let a: *mut Box<dyn FnMut()> = Box::into_raw(Box::new(Box::new(cb)));
let data: *mut raw::c_void = a as *mut raw::c_void;
let callback: Option<unsafe extern "C" fn(arg1: *mut raw::c_void)> = Some(shim);
fltk_sys::fl::Fl_has_timeout(callback, data) != 0
}
}
/// Returns whether a quit signal was sent
pub fn should_program_quit() -> bool {
unsafe { fl::Fl_should_program_quit() != 0 }
}
/// Determines whether a program should quit
pub fn program_should_quit(flag: bool) {
unsafe { fl::Fl_program_should_quit(flag as i32) }
}
/// Returns whether an event occured within a widget
pub fn event_inside_widget<Wid: WidgetExt>(wid: &Wid) -> bool {
assert!(!wid.was_deleted());
let x = wid.x();
let y = wid.y();
let w = wid.width();
let h = wid.height();
unsafe { fl::Fl_event_inside(x, y, w, h) != 0 }
}
/// Returns whether an event occured within a region
pub fn event_inside(x: i32, y: i32, w: i32, h: i32) -> bool {
unsafe { fl::Fl_event_inside(x, y, w, h) != 0 }
}
/**
Gets the widget that is below the mouse cursor.
This returns an Option<impl WidgetExt> which can be specified in the function call
```rust,no_run
use fltk::app;
use fltk::widget;
let w = app::belowmouse::<widget::Widget>(); // or by specifying a more concrete type
```
*/
pub fn belowmouse<Wid: WidgetExt>() -> Option<impl WidgetExt> {
unsafe {
let x = fl::Fl_belowmouse() as *mut fltk_sys::fl::Fl_Widget;
if x.is_null() {
None
} else {
Some(crate::widget::Widget::from_widget_ptr(
x as *mut fltk_sys::widget::Fl_Widget,
))
}
}
}
/// Deletes widgets and their children.
pub fn delete_widget<Wid: WidgetBase>(wid: Wid) {
assert!(!wid.was_deleted());
WidgetBase::delete(wid)
}
/// Registers all images supported by `SharedImage`
pub fn register_images() {
unsafe { fltk_sys::image::Fl_register_images() }
}
/// Inits all styles, fonts and images available to FLTK.
/// Also initializes global locking
/// # Panics
/// If the current environment lacks threading support. Practically this should never happen!
pub fn init_all() {
unsafe {
fltk_sys::fl::Fl_init_all();
lock().expect("fltk-rs requires threading support!");
register_images();
// This should never appear!
*FONTS.lock().unwrap() = vec![
"Helvetica".to_owned(),
"HelveticaBold".to_owned(),
"HelveticaItalic".to_owned(),
"HelveticaBoldItalic".to_owned(),
"Courier".to_owned(),
"CourierBold".to_owned(),
"CourierItalic".to_owned(),
"CourierBoldItalic".to_owned(),
"Times".to_owned(),
"TimesBold".to_owned(),
"TimesItalic".to_owned(),
"TimesBoldItalic".to_owned(),
"Symbol".to_owned(),
"Screen".to_owned(),
"ScreenBold".to_owned(),
"Zapfdingbats".to_owned(),
];
#[cfg(feature = "enable-glwindow")]
{
gl_loader::init_gl();
}
if !IS_INIT.load(Ordering::Relaxed) {
IS_INIT.store(true, Ordering::Relaxed);
}
}
}
/// Redraws everything
pub fn redraw() {
unsafe { fl::Fl_redraw() }
}
/// Returns whether the event is a shift press
pub fn is_event_shift() -> bool {
unsafe { fl::Fl_event_shift() != 0 }
}
/// Returns whether the event is a control key press
pub fn is_event_ctrl() -> bool {
unsafe { fl::Fl_event_ctrl() != 0 }
}
/// Returns whether the event is a command key press
pub fn is_event_command() -> bool {
unsafe { fl::Fl_event_command() != 0 }
}
/// Returns whether the event is a alt key press
pub fn is_event_alt() -> bool {
unsafe { fl::Fl_event_alt() != 0 }
}
/// Sets the damage to true or false, illiciting a redraw by the application
pub fn set_damage(flag: bool) {
unsafe { fl::Fl_set_damage(flag as i32) }
}
/// Returns whether any of the widgets were damaged
pub fn damage() -> bool {
unsafe { fl::Fl_damage() != 0 }
}
/// Sets the visual mode of the application
/// # Errors
/// Returns Err(FailedOperation) if FLTK failed to set the visual mode
pub fn set_visual(mode: Mode) -> Result<(), FltkError> {
unsafe {
match fl::Fl_visual(mode.bits() as i32) {
0 => Err(FltkError::Internal(FltkErrorKind::FailedOperation)),
_ => Ok(()),
}
}
}
/// Makes FLTK use its own colormap. This may make FLTK display better
pub fn own_colormap() {
unsafe { fl::Fl_own_colormap() }
}
/// Gets the widget which was pushed
pub fn pushed() -> Option<impl WidgetExt> {
unsafe {
let ptr = fl::Fl_pushed();
if ptr.is_null() {
None
} else {
Some(crate::widget::Widget::from_widget_ptr(ptr as *mut _))
}
}
}
/// Gets the widget which has focus
pub fn focus() -> Option<impl WidgetExt> {
unsafe {
let ptr = fl::Fl_focus();
if ptr.is_null() {
None
} else {
Some(crate::widget::Widget::from_widget_ptr(
ptr as *mut fltk_sys::widget::Fl_Widget,
))
}
}
}
/// Sets the widget which has focus
pub fn set_focus<W: WidgetExt>(wid: &W) {
unsafe { fl::Fl_set_focus(wid.as_widget_ptr() as *mut raw::c_void) }
}
/// Gets FLTK version
pub fn version() -> f64 {
unsafe { fl::Fl_version() }
}
/// Gets FLTK API version
pub fn api_version() -> i32 {
unsafe { fl::Fl_api_version() }
}
/// Gets FLTK ABI version
pub fn abi_version() -> i32 {
unsafe { fl::Fl_abi_version() }
}
/// Gets FLTK crate version
pub fn crate_version() -> &'static str {
env!("CARGO_PKG_VERSION")
}
/// The current graphics context of the app, `fl_gc`.
/// `*mut c_void` to `HDC` on Windows, `CGContextRef` on macOS, `_XGC` on X11
pub type GraphicsContext = *mut raw::c_void;
/// Get the graphics context, `fl_gc`
pub fn graphics_context() -> GraphicsContext {
unsafe {
let ctx = fltk_sys::window::Fl_gc();
assert!(!ctx.is_null());
ctx
}
}
/// The display global variable, `fl_display`.
/// `_XDisplay` on X11, `HINSTANCE` on Windows.
pub type Display = *mut raw::c_void;
/// Gets the display global variable, `fl_display`.
/// `_XDisplay` on X11, `HINSTANCE` on Windows.
pub fn display() -> Display {
unsafe {
let disp = fltk_sys::window::Fl_display();
assert!(!disp.is_null());
disp
}
}
/// Initiate dnd action
pub fn dnd() {
unsafe {
fl::Fl_dnd();
}
}
/// Load a font from a file
fn load_font(path: &str) -> Result<String, FltkError> {
unsafe {
let path = CString::new(path)?;
if let Some(load_font) = *LOADED_FONT {
unload_font(load_font)?;
}
let ptr = fl::Fl_load_font(path.as_ptr());
if ptr.is_null() {
Err::<String, FltkError>(FltkError::Internal(FltkErrorKind::FailedOperation))
} else {
let name = CStr::from_ptr(ptr as *mut _).to_string_lossy().to_string();
let mut f = FONTS.lock().unwrap();
if f.len() < 17 {
f.push(name.clone());
} else {
f[16] = name.clone();
}
fl::Fl_set_font2(16, ptr);
Ok(name)
}
}
}
/// Unload a loaded font
fn unload_font(path: &str) -> Result<(), FltkError> {
unsafe {
let check = path::Path::new(path);
if !check.exists() {
return Err::<(), FltkError>(FltkError::Internal(FltkErrorKind::ResourceNotFound));
}
let path = CString::new(path)?;
fl::Fl_unload_font(path.as_ptr());
Ok(())
}
}
/// Returns the apps windows.
pub fn windows() -> Option<Vec<impl WindowExt>> {
let mut v: Vec<Window> = vec![];
if let Some(first) = first_window() {
let first: Window = unsafe { first.into_widget() };
v.push(first.clone());
let mut win = first;
while let Some(wind) = next_window(&win) {
let w = unsafe { wind.into_widget::<Window>() };
v.push(w.clone());
win = w;
}
Some(v)
} else {
None
}
}
/// Set the foreground color
pub fn foreground(r: u8, g: u8, b: u8) {
unsafe { fl::Fl_foreground(r, g, b) }
}
/// Set the background color
pub fn background(r: u8, g: u8, b: u8) {
unsafe { fl::Fl_background(r, g, b) }
}
/// Set the background color for input and text widgets
pub fn background2(r: u8, g: u8, b: u8) {
unsafe { fl::Fl_background2(r, g, b) }
}
/// Sets the app's default selection color
pub fn set_selection_color(r: u8, g: u8, b: u8) {
unsafe { fl::Fl_selection_color(r, g, b) }
}
/// Sets the app's default selection color
pub fn set_inactive_color(r: u8, g: u8, b: u8) {
unsafe { fl::Fl_inactive_color(r, g, b) }
}
/// Gets the system colors
pub fn get_system_colors() {
unsafe { fl::Fl_get_system_colors() }
}
/**
Send a signal to a window.
Integral values from 0 to 30 are reserved.
Returns Ok(true) if the event was handled.
Returns Ok(false) if the event was not handled.
Returns Err on error or in use of one of the reserved values.
```rust,no_run
use fltk::{prelude::*, *};
const CHANGE_FRAME: i32 = 100;
let mut wind = window::Window::default();
let mut but = button::Button::default();
let mut frame = frame::Frame::default();
but.set_callback(move |_| {
let _ = app::handle(CHANGE_FRAME, &wind).unwrap();
});
frame.handle(move |f, ev| {
if ev == CHANGE_FRAME.into() {
f.set_label("Hello world");
true
} else {
false
}
});
```
# Errors
Returns Err on error or in use of one of the reserved values.
*/
pub fn handle<I: Into<i32> + Copy + PartialEq + PartialOrd, W: WindowExt>(
msg: I,
w: &W,
) -> Result<bool, FltkError> {
let val = msg.into();
if val >= 0 && val <= 30 {
Err(FltkError::Internal(FltkErrorKind::FailedOperation))
} else {
let ret = unsafe { fl::Fl_handle(val, w.as_widget_ptr() as _) != 0 };
Ok(ret)
}
}
/**
Send a signal to the main window.
Integral values from 0 to 30 are reserved.
Returns Ok(true) if the event was handled.
Returns Ok(false) if the event was not handled.
```rust,no_run
use fltk::{prelude::*, *};
const CHANGE_FRAME: i32 = 100;
let mut wind = window::Window::default();
let mut but = button::Button::default();
let mut frame = frame::Frame::default();
but.set_callback(move |_| {
let _ = app::handle_main(CHANGE_FRAME).unwrap();
});
frame.handle(move |f, ev| {
if ev == CHANGE_FRAME.into() {
f.set_label("Hello world");
true
} else {
false
}
});
```
# Errors
Returns Err on error or in use of one of the reserved values.
*/
pub fn handle_main<I: Into<i32> + Copy + PartialEq + PartialOrd>(
msg: I,
) -> Result<bool, FltkError> {
let val = msg.into();
if val >= 0 && val <= 30 {
Err(FltkError::Internal(FltkErrorKind::FailedOperation))
} else {
first_window().map_or(
Err(FltkError::Internal(FltkErrorKind::FailedOperation)),
|win| {
let ret = unsafe { fl::Fl_handle(val, win.as_widget_ptr() as _) != 0 };
Ok(ret)
},
)
}
}
/// Flush the main window
pub fn flush() {
unsafe { fl::Fl_flush() }
}
/// Set the screen scale
pub fn set_screen_scale(n: i32, factor: f32) {
unsafe { fl::Fl_set_screen_scale(n as i32, factor) }
}
/// Get the screen scale
pub fn screen_scale(n: i32) -> f32 {
unsafe { fl::Fl_screen_scale(n as i32) }
}
/// Return whether scaling the screen is supported
pub fn screen_scaling_supported() -> bool {
unsafe { fl::Fl_screen_scaling_supported() != 0 }
}
/// Get the screen count
pub fn screen_count() -> i32 {
unsafe { fl::Fl_screen_count() as i32 }
}
/// Get the screen number based on its coordinates
pub fn screen_num(x: i32, y: i32) -> i32 {
unsafe { fl::Fl_screen_num(x, y) }
}
/// Get a screen's dpi resolution
/// # Returns
/// (vertical, horizontal) resolutions
pub fn screen_dpi(screen_num: i32) -> (f32, f32) {
let mut h: f32 = 0.;
let mut v: f32 = 0.;
unsafe {
fl::Fl_screen_dpi(&mut h, &mut v, screen_num);
}
(h, v)
}
/// Get a screen's xywh
pub fn screen_xywh(screen_num: i32) -> (i32, i32, i32, i32) {
let mut x = 0;
let mut y = 0;
let mut w = 0;
let mut h = 0;
unsafe {
fl::Fl_screen_xywh(&mut x, &mut y, &mut w, &mut h, screen_num);
}
(x, y, w, h)
}
/// Get a screen's working area
pub fn screen_work_area(screen_num: i32) -> (i32, i32, i32, i32) {
let mut x = 0;
let mut y = 0;
let mut w = 0;
let mut h = 0;
unsafe {
fl::Fl_screen_work_area(&mut x, &mut y, &mut w, &mut h, screen_num);
}
(x, y, w, h)
}
/// Open the current display
/// # Safety
/// A correct visual must be set prior to opening the display
pub unsafe fn open_display() {
fl::Fl_open_display()
}
/// Close the current display
/// # Safety
/// The display shouldn't be closed while a window is shown
pub unsafe fn close_display() {
fl::Fl_close_display()
}
/// Get the clipboard content if it's an image
pub fn event_clipboard_image() -> Option<crate::image::RgbImage> {
unsafe {
let image = fl::Fl_event_clipboard();
if image.is_null() {
None
} else {
use std::sync::atomic::AtomicUsize;
Some(crate::image::RgbImage {
inner: image as _,
refcount: AtomicUsize::new(1),
})
}
}
}
/// The event clipboard type
#[derive(Debug, Clone)]
pub enum ClipboardEvent {
/// Text paste event
Text(String),
/// image paste event
Image(Option<crate::image::RgbImage>),
}
/// Get the clipboard content type
pub fn event_clipboard() -> Option<ClipboardEvent> {
unsafe {
let txt = fl::Fl_event_clipboard_type();
let txt = CStr::from_ptr(txt).to_string_lossy().to_string();
if txt == "text/plain" {
Some(ClipboardEvent::Text(event_text()))
} else if txt == "image" {
Some(ClipboardEvent::Image(event_clipboard_image()))
} else {
None
}
}
}
#[allow(clippy::missing_safety_doc)]
/**
Send a signal to a window pointer from event_dispatch.
Returns true if the event was handled.
Returns false if the event was not handled or ignored.
```rust,no_run
use fltk::{prelude::*, *};
const CHANGE_FRAME: i32 = 100;
let mut wind = window::Window::default();
let mut but = button::Button::default();
let mut frame = frame::Frame::default();
wind.end();
wind.show();
but.set_callback(move |_| {
let _ = app::handle_main(CHANGE_FRAME).unwrap();
});
frame.handle(move |f, ev| {
if ev == CHANGE_FRAME.into() {
f.set_label("Hello world");
true
} else {
false
}
});
unsafe {
app::event_dispatch(|ev, winptr| {
if ev == CHANGE_FRAME.into() {
false // ignore CHANGE_FRAME event
} else {
app::handle_raw(ev, winptr)
}
});
}
```
# Safety
The window pointer must be valid
*/
pub unsafe fn handle_raw(
event: Event,
w: WindowPtr,
) -> bool {
fl::Fl_handle_(event.bits(), w as _) != 0
}
#[allow(clippy::missing_safety_doc)]
/**
The event dispatch function is called after native events are converted to
FLTK events, but before they are handled by FLTK. If the dispatch function
handler is set, it is up to the dispatch function to call
`app::handle2(Event, WindowPtr)` or to ignore the event.
The dispatch function itself must return false if it ignored the event,
or true if it used the event. If you call `app::handle2()`, then
this will return the correct value.
# Safety
The window pointer must not be invalidated
*/
pub unsafe fn event_dispatch(f: fn(Event, WindowPtr) -> bool) {
fl::Fl_event_dispatch(mem::transmute(f));
}
|
#[doc = "Reader of register RCC_MP_APB3ENCLRR"]
pub type R = crate::R<u32, super::RCC_MP_APB3ENCLRR>;
#[doc = "Writer for register RCC_MP_APB3ENCLRR"]
pub type W = crate::W<u32, super::RCC_MP_APB3ENCLRR>;
#[doc = "Register RCC_MP_APB3ENCLRR `reset()`'s with value 0"]
impl crate::ResetValue for super::RCC_MP_APB3ENCLRR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "LPTIM2EN\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum LPTIM2EN_A {
#[doc = "0: Writing has no effect, reading means\r\n that the peripheral clocks are\r\n disabled"]
B_0X0 = 0,
#[doc = "1: Writing disables the peripheral\r\n clocks, reading means that the peripheral clocks\r\n are enabled"]
B_0X1 = 1,
}
impl From<LPTIM2EN_A> for bool {
#[inline(always)]
fn from(variant: LPTIM2EN_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `LPTIM2EN`"]
pub type LPTIM2EN_R = crate::R<bool, LPTIM2EN_A>;
impl LPTIM2EN_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> LPTIM2EN_A {
match self.bits {
false => LPTIM2EN_A::B_0X0,
true => LPTIM2EN_A::B_0X1,
}
}
#[doc = "Checks if the value of the field is `B_0X0`"]
#[inline(always)]
pub fn is_b_0x0(&self) -> bool {
*self == LPTIM2EN_A::B_0X0
}
#[doc = "Checks if the value of the field is `B_0X1`"]
#[inline(always)]
pub fn is_b_0x1(&self) -> bool {
*self == LPTIM2EN_A::B_0X1
}
}
#[doc = "Write proxy for field `LPTIM2EN`"]
pub struct LPTIM2EN_W<'a> {
w: &'a mut W,
}
impl<'a> LPTIM2EN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: LPTIM2EN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Writing has no effect, reading means that the peripheral clocks are disabled"]
#[inline(always)]
pub fn b_0x0(self) -> &'a mut W {
self.variant(LPTIM2EN_A::B_0X0)
}
#[doc = "Writing disables the peripheral clocks, reading means that the peripheral clocks are enabled"]
#[inline(always)]
pub fn b_0x1(self) -> &'a mut W {
self.variant(LPTIM2EN_A::B_0X1)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "LPTIM3EN\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum LPTIM3EN_A {
#[doc = "0: Writing has no effect, reading means\r\n that the peripheral clocks are\r\n disabled"]
B_0X0 = 0,
#[doc = "1: Writing disables the peripheral\r\n clocks, reading means that the peripheral clocks\r\n are enabled"]
B_0X1 = 1,
}
impl From<LPTIM3EN_A> for bool {
#[inline(always)]
fn from(variant: LPTIM3EN_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `LPTIM3EN`"]
pub type LPTIM3EN_R = crate::R<bool, LPTIM3EN_A>;
impl LPTIM3EN_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> LPTIM3EN_A {
match self.bits {
false => LPTIM3EN_A::B_0X0,
true => LPTIM3EN_A::B_0X1,
}
}
#[doc = "Checks if the value of the field is `B_0X0`"]
#[inline(always)]
pub fn is_b_0x0(&self) -> bool {
*self == LPTIM3EN_A::B_0X0
}
#[doc = "Checks if the value of the field is `B_0X1`"]
#[inline(always)]
pub fn is_b_0x1(&self) -> bool {
*self == LPTIM3EN_A::B_0X1
}
}
#[doc = "Write proxy for field `LPTIM3EN`"]
pub struct LPTIM3EN_W<'a> {
w: &'a mut W,
}
impl<'a> LPTIM3EN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: LPTIM3EN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Writing has no effect, reading means that the peripheral clocks are disabled"]
#[inline(always)]
pub fn b_0x0(self) -> &'a mut W {
self.variant(LPTIM3EN_A::B_0X0)
}
#[doc = "Writing disables the peripheral clocks, reading means that the peripheral clocks are enabled"]
#[inline(always)]
pub fn b_0x1(self) -> &'a mut W {
self.variant(LPTIM3EN_A::B_0X1)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "LPTIM4EN\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum LPTIM4EN_A {
#[doc = "0: Writing has no effect, reading means\r\n that the peripheral clocks are\r\n disabled"]
B_0X0 = 0,
#[doc = "1: Writing disables the peripheral\r\n clocks, reading means that the peripheral clocks\r\n are enabled"]
B_0X1 = 1,
}
impl From<LPTIM4EN_A> for bool {
#[inline(always)]
fn from(variant: LPTIM4EN_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `LPTIM4EN`"]
pub type LPTIM4EN_R = crate::R<bool, LPTIM4EN_A>;
impl LPTIM4EN_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> LPTIM4EN_A {
match self.bits {
false => LPTIM4EN_A::B_0X0,
true => LPTIM4EN_A::B_0X1,
}
}
#[doc = "Checks if the value of the field is `B_0X0`"]
#[inline(always)]
pub fn is_b_0x0(&self) -> bool {
*self == LPTIM4EN_A::B_0X0
}
#[doc = "Checks if the value of the field is `B_0X1`"]
#[inline(always)]
pub fn is_b_0x1(&self) -> bool {
*self == LPTIM4EN_A::B_0X1
}
}
#[doc = "Write proxy for field `LPTIM4EN`"]
pub struct LPTIM4EN_W<'a> {
w: &'a mut W,
}
impl<'a> LPTIM4EN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: LPTIM4EN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Writing has no effect, reading means that the peripheral clocks are disabled"]
#[inline(always)]
pub fn b_0x0(self) -> &'a mut W {
self.variant(LPTIM4EN_A::B_0X0)
}
#[doc = "Writing disables the peripheral clocks, reading means that the peripheral clocks are enabled"]
#[inline(always)]
pub fn b_0x1(self) -> &'a mut W {
self.variant(LPTIM4EN_A::B_0X1)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "LPTIM5EN\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum LPTIM5EN_A {
#[doc = "0: Writing has no effect, reading means\r\n that the peripheral clocks are\r\n disabled"]
B_0X0 = 0,
#[doc = "1: Writing disables the peripheral\r\n clocks, reading means that the peripheral clocks\r\n are enabled"]
B_0X1 = 1,
}
impl From<LPTIM5EN_A> for bool {
#[inline(always)]
fn from(variant: LPTIM5EN_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `LPTIM5EN`"]
pub type LPTIM5EN_R = crate::R<bool, LPTIM5EN_A>;
impl LPTIM5EN_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> LPTIM5EN_A {
match self.bits {
false => LPTIM5EN_A::B_0X0,
true => LPTIM5EN_A::B_0X1,
}
}
#[doc = "Checks if the value of the field is `B_0X0`"]
#[inline(always)]
pub fn is_b_0x0(&self) -> bool {
*self == LPTIM5EN_A::B_0X0
}
#[doc = "Checks if the value of the field is `B_0X1`"]
#[inline(always)]
pub fn is_b_0x1(&self) -> bool {
*self == LPTIM5EN_A::B_0X1
}
}
#[doc = "Write proxy for field `LPTIM5EN`"]
pub struct LPTIM5EN_W<'a> {
w: &'a mut W,
}
impl<'a> LPTIM5EN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: LPTIM5EN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Writing has no effect, reading means that the peripheral clocks are disabled"]
#[inline(always)]
pub fn b_0x0(self) -> &'a mut W {
self.variant(LPTIM5EN_A::B_0X0)
}
#[doc = "Writing disables the peripheral clocks, reading means that the peripheral clocks are enabled"]
#[inline(always)]
pub fn b_0x1(self) -> &'a mut W {
self.variant(LPTIM5EN_A::B_0X1)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3);
self.w
}
}
#[doc = "SAI4EN\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SAI4EN_A {
#[doc = "0: Writing has no effect, reading means\r\n that the peripheral clocks are\r\n disabled"]
B_0X0 = 0,
#[doc = "1: Writing disables the peripheral\r\n clocks, reading means that the peripheral clocks\r\n are enabled"]
B_0X1 = 1,
}
impl From<SAI4EN_A> for bool {
#[inline(always)]
fn from(variant: SAI4EN_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `SAI4EN`"]
pub type SAI4EN_R = crate::R<bool, SAI4EN_A>;
impl SAI4EN_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> SAI4EN_A {
match self.bits {
false => SAI4EN_A::B_0X0,
true => SAI4EN_A::B_0X1,
}
}
#[doc = "Checks if the value of the field is `B_0X0`"]
#[inline(always)]
pub fn is_b_0x0(&self) -> bool {
*self == SAI4EN_A::B_0X0
}
#[doc = "Checks if the value of the field is `B_0X1`"]
#[inline(always)]
pub fn is_b_0x1(&self) -> bool {
*self == SAI4EN_A::B_0X1
}
}
#[doc = "Write proxy for field `SAI4EN`"]
pub struct SAI4EN_W<'a> {
w: &'a mut W,
}
impl<'a> SAI4EN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SAI4EN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Writing has no effect, reading means that the peripheral clocks are disabled"]
#[inline(always)]
pub fn b_0x0(self) -> &'a mut W {
self.variant(SAI4EN_A::B_0X0)
}
#[doc = "Writing disables the peripheral clocks, reading means that the peripheral clocks are enabled"]
#[inline(always)]
pub fn b_0x1(self) -> &'a mut W {
self.variant(SAI4EN_A::B_0X1)
}
#[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 = "SYSCFGEN\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SYSCFGEN_A {
#[doc = "0: Writing has no effect, reading means\r\n that the peripheral clocks are\r\n disabled"]
B_0X0 = 0,
#[doc = "1: Writing disables the peripheral\r\n clocks, reading means that the peripheral clocks\r\n are enabled"]
B_0X1 = 1,
}
impl From<SYSCFGEN_A> for bool {
#[inline(always)]
fn from(variant: SYSCFGEN_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `SYSCFGEN`"]
pub type SYSCFGEN_R = crate::R<bool, SYSCFGEN_A>;
impl SYSCFGEN_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> SYSCFGEN_A {
match self.bits {
false => SYSCFGEN_A::B_0X0,
true => SYSCFGEN_A::B_0X1,
}
}
#[doc = "Checks if the value of the field is `B_0X0`"]
#[inline(always)]
pub fn is_b_0x0(&self) -> bool {
*self == SYSCFGEN_A::B_0X0
}
#[doc = "Checks if the value of the field is `B_0X1`"]
#[inline(always)]
pub fn is_b_0x1(&self) -> bool {
*self == SYSCFGEN_A::B_0X1
}
}
#[doc = "Write proxy for field `SYSCFGEN`"]
pub struct SYSCFGEN_W<'a> {
w: &'a mut W,
}
impl<'a> SYSCFGEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SYSCFGEN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Writing has no effect, reading means that the peripheral clocks are disabled"]
#[inline(always)]
pub fn b_0x0(self) -> &'a mut W {
self.variant(SYSCFGEN_A::B_0X0)
}
#[doc = "Writing disables the peripheral clocks, reading means that the peripheral clocks are enabled"]
#[inline(always)]
pub fn b_0x1(self) -> &'a mut W {
self.variant(SYSCFGEN_A::B_0X1)
}
#[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 << 11)) | (((value as u32) & 0x01) << 11);
self.w
}
}
#[doc = "VREFEN\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum VREFEN_A {
#[doc = "0: Writing has no effect, reading means\r\n that the peripheral clocks are\r\n disabled"]
B_0X0 = 0,
#[doc = "1: Writing disables the peripheral\r\n clocks, reading means that the peripheral clocks\r\n are enabled"]
B_0X1 = 1,
}
impl From<VREFEN_A> for bool {
#[inline(always)]
fn from(variant: VREFEN_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `VREFEN`"]
pub type VREFEN_R = crate::R<bool, VREFEN_A>;
impl VREFEN_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> VREFEN_A {
match self.bits {
false => VREFEN_A::B_0X0,
true => VREFEN_A::B_0X1,
}
}
#[doc = "Checks if the value of the field is `B_0X0`"]
#[inline(always)]
pub fn is_b_0x0(&self) -> bool {
*self == VREFEN_A::B_0X0
}
#[doc = "Checks if the value of the field is `B_0X1`"]
#[inline(always)]
pub fn is_b_0x1(&self) -> bool {
*self == VREFEN_A::B_0X1
}
}
#[doc = "Write proxy for field `VREFEN`"]
pub struct VREFEN_W<'a> {
w: &'a mut W,
}
impl<'a> VREFEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: VREFEN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Writing has no effect, reading means that the peripheral clocks are disabled"]
#[inline(always)]
pub fn b_0x0(self) -> &'a mut W {
self.variant(VREFEN_A::B_0X0)
}
#[doc = "Writing disables the peripheral clocks, reading means that the peripheral clocks are enabled"]
#[inline(always)]
pub fn b_0x1(self) -> &'a mut W {
self.variant(VREFEN_A::B_0X1)
}
#[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 = "TMPSENSEN\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMPSENSEN_A {
#[doc = "0: Writing has no effect, reading means\r\n that the peripheral clocks are\r\n disabled"]
B_0X0 = 0,
#[doc = "1: Writing disables the peripheral\r\n clocks, reading means that the peripheral clocks\r\n are enabled"]
B_0X1 = 1,
}
impl From<TMPSENSEN_A> for bool {
#[inline(always)]
fn from(variant: TMPSENSEN_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `TMPSENSEN`"]
pub type TMPSENSEN_R = crate::R<bool, TMPSENSEN_A>;
impl TMPSENSEN_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TMPSENSEN_A {
match self.bits {
false => TMPSENSEN_A::B_0X0,
true => TMPSENSEN_A::B_0X1,
}
}
#[doc = "Checks if the value of the field is `B_0X0`"]
#[inline(always)]
pub fn is_b_0x0(&self) -> bool {
*self == TMPSENSEN_A::B_0X0
}
#[doc = "Checks if the value of the field is `B_0X1`"]
#[inline(always)]
pub fn is_b_0x1(&self) -> bool {
*self == TMPSENSEN_A::B_0X1
}
}
#[doc = "Write proxy for field `TMPSENSEN`"]
pub struct TMPSENSEN_W<'a> {
w: &'a mut W,
}
impl<'a> TMPSENSEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TMPSENSEN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Writing has no effect, reading means that the peripheral clocks are disabled"]
#[inline(always)]
pub fn b_0x0(self) -> &'a mut W {
self.variant(TMPSENSEN_A::B_0X0)
}
#[doc = "Writing disables the peripheral clocks, reading means that the peripheral clocks are enabled"]
#[inline(always)]
pub fn b_0x1(self) -> &'a mut W {
self.variant(TMPSENSEN_A::B_0X1)
}
#[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 = "PMBCTRLEN\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PMBCTRLEN_A {
#[doc = "0: Writing has no effect, reading means\r\n that the peripheral clocks are\r\n disabled"]
B_0X0 = 0,
#[doc = "1: Writing disables the peripheral\r\n clocks, reading means that the peripheral clocks\r\n are enabled"]
B_0X1 = 1,
}
impl From<PMBCTRLEN_A> for bool {
#[inline(always)]
fn from(variant: PMBCTRLEN_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `PMBCTRLEN`"]
pub type PMBCTRLEN_R = crate::R<bool, PMBCTRLEN_A>;
impl PMBCTRLEN_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> PMBCTRLEN_A {
match self.bits {
false => PMBCTRLEN_A::B_0X0,
true => PMBCTRLEN_A::B_0X1,
}
}
#[doc = "Checks if the value of the field is `B_0X0`"]
#[inline(always)]
pub fn is_b_0x0(&self) -> bool {
*self == PMBCTRLEN_A::B_0X0
}
#[doc = "Checks if the value of the field is `B_0X1`"]
#[inline(always)]
pub fn is_b_0x1(&self) -> bool {
*self == PMBCTRLEN_A::B_0X1
}
}
#[doc = "Write proxy for field `PMBCTRLEN`"]
pub struct PMBCTRLEN_W<'a> {
w: &'a mut W,
}
impl<'a> PMBCTRLEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: PMBCTRLEN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Writing has no effect, reading means that the peripheral clocks are disabled"]
#[inline(always)]
pub fn b_0x0(self) -> &'a mut W {
self.variant(PMBCTRLEN_A::B_0X0)
}
#[doc = "Writing disables the peripheral clocks, reading means that the peripheral clocks are enabled"]
#[inline(always)]
pub fn b_0x1(self) -> &'a mut W {
self.variant(PMBCTRLEN_A::B_0X1)
}
#[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 = "HDPEN\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum HDPEN_A {
#[doc = "0: Writing has no effect, reading means\r\n that the peripheral clocks are\r\n disabled"]
B_0X0 = 0,
#[doc = "1: Writing disables the peripheral\r\n clocks, reading means that the peripheral clocks\r\n are enabled"]
B_0X1 = 1,
}
impl From<HDPEN_A> for bool {
#[inline(always)]
fn from(variant: HDPEN_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `HDPEN`"]
pub type HDPEN_R = crate::R<bool, HDPEN_A>;
impl HDPEN_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> HDPEN_A {
match self.bits {
false => HDPEN_A::B_0X0,
true => HDPEN_A::B_0X1,
}
}
#[doc = "Checks if the value of the field is `B_0X0`"]
#[inline(always)]
pub fn is_b_0x0(&self) -> bool {
*self == HDPEN_A::B_0X0
}
#[doc = "Checks if the value of the field is `B_0X1`"]
#[inline(always)]
pub fn is_b_0x1(&self) -> bool {
*self == HDPEN_A::B_0X1
}
}
#[doc = "Write proxy for field `HDPEN`"]
pub struct HDPEN_W<'a> {
w: &'a mut W,
}
impl<'a> HDPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: HDPEN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Writing has no effect, reading means that the peripheral clocks are disabled"]
#[inline(always)]
pub fn b_0x0(self) -> &'a mut W {
self.variant(HDPEN_A::B_0X0)
}
#[doc = "Writing disables the peripheral clocks, reading means that the peripheral clocks are enabled"]
#[inline(always)]
pub fn b_0x1(self) -> &'a mut W {
self.variant(HDPEN_A::B_0X1)
}
#[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 << 20)) | (((value as u32) & 0x01) << 20);
self.w
}
}
impl R {
#[doc = "Bit 0 - LPTIM2EN"]
#[inline(always)]
pub fn lptim2en(&self) -> LPTIM2EN_R {
LPTIM2EN_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - LPTIM3EN"]
#[inline(always)]
pub fn lptim3en(&self) -> LPTIM3EN_R {
LPTIM3EN_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - LPTIM4EN"]
#[inline(always)]
pub fn lptim4en(&self) -> LPTIM4EN_R {
LPTIM4EN_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - LPTIM5EN"]
#[inline(always)]
pub fn lptim5en(&self) -> LPTIM5EN_R {
LPTIM5EN_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 8 - SAI4EN"]
#[inline(always)]
pub fn sai4en(&self) -> SAI4EN_R {
SAI4EN_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 11 - SYSCFGEN"]
#[inline(always)]
pub fn syscfgen(&self) -> SYSCFGEN_R {
SYSCFGEN_R::new(((self.bits >> 11) & 0x01) != 0)
}
#[doc = "Bit 13 - VREFEN"]
#[inline(always)]
pub fn vrefen(&self) -> VREFEN_R {
VREFEN_R::new(((self.bits >> 13) & 0x01) != 0)
}
#[doc = "Bit 16 - TMPSENSEN"]
#[inline(always)]
pub fn tmpsensen(&self) -> TMPSENSEN_R {
TMPSENSEN_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bit 17 - PMBCTRLEN"]
#[inline(always)]
pub fn pmbctrlen(&self) -> PMBCTRLEN_R {
PMBCTRLEN_R::new(((self.bits >> 17) & 0x01) != 0)
}
#[doc = "Bit 20 - HDPEN"]
#[inline(always)]
pub fn hdpen(&self) -> HDPEN_R {
HDPEN_R::new(((self.bits >> 20) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - LPTIM2EN"]
#[inline(always)]
pub fn lptim2en(&mut self) -> LPTIM2EN_W {
LPTIM2EN_W { w: self }
}
#[doc = "Bit 1 - LPTIM3EN"]
#[inline(always)]
pub fn lptim3en(&mut self) -> LPTIM3EN_W {
LPTIM3EN_W { w: self }
}
#[doc = "Bit 2 - LPTIM4EN"]
#[inline(always)]
pub fn lptim4en(&mut self) -> LPTIM4EN_W {
LPTIM4EN_W { w: self }
}
#[doc = "Bit 3 - LPTIM5EN"]
#[inline(always)]
pub fn lptim5en(&mut self) -> LPTIM5EN_W {
LPTIM5EN_W { w: self }
}
#[doc = "Bit 8 - SAI4EN"]
#[inline(always)]
pub fn sai4en(&mut self) -> SAI4EN_W {
SAI4EN_W { w: self }
}
#[doc = "Bit 11 - SYSCFGEN"]
#[inline(always)]
pub fn syscfgen(&mut self) -> SYSCFGEN_W {
SYSCFGEN_W { w: self }
}
#[doc = "Bit 13 - VREFEN"]
#[inline(always)]
pub fn vrefen(&mut self) -> VREFEN_W {
VREFEN_W { w: self }
}
#[doc = "Bit 16 - TMPSENSEN"]
#[inline(always)]
pub fn tmpsensen(&mut self) -> TMPSENSEN_W {
TMPSENSEN_W { w: self }
}
#[doc = "Bit 17 - PMBCTRLEN"]
#[inline(always)]
pub fn pmbctrlen(&mut self) -> PMBCTRLEN_W {
PMBCTRLEN_W { w: self }
}
#[doc = "Bit 20 - HDPEN"]
#[inline(always)]
pub fn hdpen(&mut self) -> HDPEN_W {
HDPEN_W { w: self }
}
}
|
use wasm_bindgen::prelude::*;
use super::Object3D;
#[wasm_bindgen(module = "three")]
extern "C" {
#[wasm_bindgen(extends = Object3D)]
pub type Camera;
#[wasm_bindgen(constructor)]
pub fn new() -> Camera;
}
#[wasm_bindgen(module = "three")]
extern "C" {
#[wasm_bindgen(extends = Camera)]
pub type PerspectiveCamera;
#[wasm_bindgen(constructor)]
pub fn new(fov: f64, aspect: f64, near: f64, far: f64) -> PerspectiveCamera;
#[wasm_bindgen(method, js_name = "updateProjectionMatrix")]
pub fn update_projection_matrix(this: &PerspectiveCamera);
#[wasm_bindgen(method, setter, js_name = "aspect")]
pub fn set_aspect(this: &PerspectiveCamera, aspect: f64);
}
#[wasm_bindgen(module = "three")]
extern "C" {
#[wasm_bindgen(extends = Camera)]
pub type OrthographicCamera;
#[wasm_bindgen(constructor)]
pub fn new(
left: f64,
right: f64,
top: f64,
bottom: f64,
near: f64,
far: f64,
) -> OrthographicCamera;
#[wasm_bindgen(method, js_name = "updateProjectionMatrix")]
pub fn update_projection_matrix(this: &OrthographicCamera);
#[wasm_bindgen(method, setter, js_name = "top")]
pub fn set_top(this: &OrthographicCamera, top: f64);
#[wasm_bindgen(method, setter, js_name = "left")]
pub fn set_left(this: &OrthographicCamera, left: f64);
#[wasm_bindgen(method, setter, js_name = "bottom")]
pub fn set_bottom(this: &OrthographicCamera, bottom: f64);
#[wasm_bindgen(method, setter, js_name = "right")]
pub fn set_right(this: &OrthographicCamera, right: f64);
}
|
use super::Point;
use super::Translate;
/// Standard pixel size
pub const SIZE: u32 = 10;
/// A simple text object
#[derive(Debug, Clone, PartialEq, Hash)]
pub struct Text {
/// Position of the text
pub point: Point,
/// The actual text string
pub text: String,
/// The font size,
pub size: u32
}
impl Text {
pub fn new<P, I>(point: P, text: I) -> Self
where P: Into<Point>, I: Into<String>
{
Self {
point: point.into(),
text: text.into(),
size: SIZE
}
}
}
impl Translate for Text {
fn point(&self) -> &Point
{
&self.point
}
fn point_mut(&mut self) -> &mut Point
{
&mut self.point
}
}
#[cfg(test)]
mod tests {
#![allow(unused_variables)]
use super::*;
#[test]
fn text()
{
let t = Text::new((1, 1), "hello world");
}
}
|
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorResponse {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<ErrorResponseBody>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorResponseBody {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub details: Vec<ErrorResponseBody>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Resource {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ManagedResource {
#[serde(flatten)]
pub resource: Resource,
pub location: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Scope {
#[serde(rename = "scopeType", default, skip_serializing_if = "Option::is_none")]
pub scope_type: Option<scope::ScopeType>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub values: Vec<String>,
}
pub mod scope {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ScopeType {
ResourceGroup,
Resource,
Subscription,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Condition {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub operator: Option<condition::Operator>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub values: Vec<String>,
}
pub mod condition {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Operator {
Equals,
NotEquals,
Contains,
DoesNotContain,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Conditions {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub severity: Option<Condition>,
#[serde(rename = "monitorService", default, skip_serializing_if = "Option::is_none")]
pub monitor_service: Option<Condition>,
#[serde(rename = "monitorCondition", default, skip_serializing_if = "Option::is_none")]
pub monitor_condition: Option<Condition>,
#[serde(rename = "targetResourceType", default, skip_serializing_if = "Option::is_none")]
pub target_resource_type: Option<Condition>,
#[serde(rename = "alertRuleId", default, skip_serializing_if = "Option::is_none")]
pub alert_rule_id: Option<Condition>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<Condition>,
#[serde(rename = "alertContext", default, skip_serializing_if = "Option::is_none")]
pub alert_context: Option<Condition>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SuppressionConfig {
#[serde(rename = "recurrenceType")]
pub recurrence_type: suppression_config::RecurrenceType,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub schedule: Option<SuppressionSchedule>,
}
pub mod suppression_config {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum RecurrenceType {
Always,
Once,
Daily,
Weekly,
Monthly,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SuppressionSchedule {
#[serde(rename = "startDate", default, skip_serializing_if = "Option::is_none")]
pub start_date: Option<String>,
#[serde(rename = "endDate", default, skip_serializing_if = "Option::is_none")]
pub end_date: Option<String>,
#[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")]
pub start_time: Option<String>,
#[serde(rename = "endTime", default, skip_serializing_if = "Option::is_none")]
pub end_time: Option<String>,
#[serde(rename = "recurrenceValues", default, skip_serializing_if = "Vec::is_empty")]
pub recurrence_values: Vec<i64>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ActionRule {
#[serde(flatten)]
pub managed_resource: ManagedResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<ActionRuleProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ActionRuleProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub scope: Option<Scope>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub conditions: Option<Conditions>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(rename = "createdAt", default, skip_serializing_if = "Option::is_none")]
pub created_at: Option<String>,
#[serde(rename = "lastModifiedAt", default, skip_serializing_if = "Option::is_none")]
pub last_modified_at: Option<String>,
#[serde(rename = "createdBy", default, skip_serializing_if = "Option::is_none")]
pub created_by: Option<String>,
#[serde(rename = "lastModifiedBy", default, skip_serializing_if = "Option::is_none")]
pub last_modified_by: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<action_rule_properties::Status>,
#[serde(rename = "type")]
pub type_: action_rule_properties::Type,
}
pub mod action_rule_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Status {
Enabled,
Disabled,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Type {
Suppression,
ActionGroup,
Diagnostics,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Suppression {
#[serde(flatten)]
pub action_rule_properties: ActionRuleProperties,
#[serde(flatten)]
pub serde_json_value: serde_json::Value,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ActionGroup {
#[serde(flatten)]
pub action_rule_properties: ActionRuleProperties,
#[serde(flatten)]
pub serde_json_value: serde_json::Value,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Diagnostics {
#[serde(flatten)]
pub action_rule_properties: ActionRuleProperties,
#[serde(flatten)]
pub serde_json_value: serde_json::Value,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ActionRulesList {
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<ActionRule>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PatchProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<patch_properties::Status>,
}
pub mod patch_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Status {
Enabled,
Disabled,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PatchObject {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<PatchProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Operation {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display: Option<operation::Display>,
}
pub mod operation {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Display {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub provider: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resource: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub operation: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OperationsList {
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
pub value: Vec<Operation>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Alert {
#[serde(flatten)]
pub resource: Resource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<AlertProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AlertsList {
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Alert>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AlertProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub essentials: Option<Essentials>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub context: Option<AlertContext>,
#[serde(rename = "egressConfig", default, skip_serializing_if = "Option::is_none")]
pub egress_config: Option<EgressConfig>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EgressConfig {}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AlertContext {}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Essentials {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub severity: Option<essentials::Severity>,
#[serde(rename = "signalType", default, skip_serializing_if = "Option::is_none")]
pub signal_type: Option<essentials::SignalType>,
#[serde(rename = "alertState", default, skip_serializing_if = "Option::is_none")]
pub alert_state: Option<essentials::AlertState>,
#[serde(rename = "monitorCondition", default, skip_serializing_if = "Option::is_none")]
pub monitor_condition: Option<essentials::MonitorCondition>,
#[serde(rename = "targetResource", default, skip_serializing_if = "Option::is_none")]
pub target_resource: Option<String>,
#[serde(rename = "targetResourceName", default, skip_serializing_if = "Option::is_none")]
pub target_resource_name: Option<String>,
#[serde(rename = "targetResourceGroup", default, skip_serializing_if = "Option::is_none")]
pub target_resource_group: Option<String>,
#[serde(rename = "targetResourceType", default, skip_serializing_if = "Option::is_none")]
pub target_resource_type: Option<String>,
#[serde(rename = "monitorService", default, skip_serializing_if = "Option::is_none")]
pub monitor_service: Option<essentials::MonitorService>,
#[serde(rename = "alertRule", default, skip_serializing_if = "Option::is_none")]
pub alert_rule: Option<String>,
#[serde(rename = "sourceCreatedId", default, skip_serializing_if = "Option::is_none")]
pub source_created_id: Option<String>,
#[serde(rename = "smartGroupId", default, skip_serializing_if = "Option::is_none")]
pub smart_group_id: Option<String>,
#[serde(rename = "smartGroupingReason", default, skip_serializing_if = "Option::is_none")]
pub smart_grouping_reason: Option<String>,
#[serde(rename = "startDateTime", default, skip_serializing_if = "Option::is_none")]
pub start_date_time: Option<String>,
#[serde(rename = "lastModifiedDateTime", default, skip_serializing_if = "Option::is_none")]
pub last_modified_date_time: Option<String>,
#[serde(rename = "monitorConditionResolvedDateTime", default, skip_serializing_if = "Option::is_none")]
pub monitor_condition_resolved_date_time: Option<String>,
#[serde(rename = "lastModifiedUserName", default, skip_serializing_if = "Option::is_none")]
pub last_modified_user_name: Option<String>,
}
pub mod essentials {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Severity {
Sev0,
Sev1,
Sev2,
Sev3,
Sev4,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum SignalType {
Metric,
Log,
Unknown,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum AlertState {
New,
Acknowledged,
Closed,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum MonitorCondition {
Fired,
Resolved,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum MonitorService {
#[serde(rename = "Application Insights")]
ApplicationInsights,
#[serde(rename = "ActivityLog Administrative")]
ActivityLogAdministrative,
#[serde(rename = "ActivityLog Security")]
ActivityLogSecurity,
#[serde(rename = "ActivityLog Recommendation")]
ActivityLogRecommendation,
#[serde(rename = "ActivityLog Policy")]
ActivityLogPolicy,
#[serde(rename = "ActivityLog Autoscale")]
ActivityLogAutoscale,
#[serde(rename = "Log Analytics")]
LogAnalytics,
Nagios,
Platform,
#[serde(rename = "SCOM")]
Scom,
ServiceHealth,
SmartDetector,
#[serde(rename = "VM Insights")]
VmInsights,
Zabbix,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AlertModification {
#[serde(flatten)]
pub resource: Resource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<AlertModificationProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AlertModificationProperties {
#[serde(rename = "alertId", default, skip_serializing_if = "Option::is_none")]
pub alert_id: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub modifications: Vec<AlertModificationItem>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AlertModificationItem {
#[serde(rename = "modificationEvent", default, skip_serializing_if = "Option::is_none")]
pub modification_event: Option<alert_modification_item::ModificationEvent>,
#[serde(rename = "oldValue", default, skip_serializing_if = "Option::is_none")]
pub old_value: Option<String>,
#[serde(rename = "newValue", default, skip_serializing_if = "Option::is_none")]
pub new_value: Option<String>,
#[serde(rename = "modifiedAt", default, skip_serializing_if = "Option::is_none")]
pub modified_at: Option<String>,
#[serde(rename = "modifiedBy", default, skip_serializing_if = "Option::is_none")]
pub modified_by: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub comments: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
pub mod alert_modification_item {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ModificationEvent {
AlertCreated,
StateChange,
MonitorConditionChange,
SeverityChange,
ActionRuleTriggered,
ActionRuleSuppressed,
ActionsTriggered,
ActionsSuppressed,
ActionsFailed,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AlertsSummary {
#[serde(flatten)]
pub resource: Resource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<AlertsSummaryGroup>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AlertsSummaryGroup {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub total: Option<i64>,
#[serde(rename = "smartGroupsCount", default, skip_serializing_if = "Option::is_none")]
pub smart_groups_count: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub groupedby: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub values: Vec<AlertsSummaryGroupItem>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AlertsSummaryGroupItem {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub count: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub groupedby: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub values: Vec<AlertsSummaryGroupItem>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AlertsMetaData {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<AlertsMetaDataProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AlertsMetaDataProperties {
#[serde(rename = "metadataIdentifier")]
pub metadata_identifier: alerts_meta_data_properties::MetadataIdentifier,
}
pub mod alerts_meta_data_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum MetadataIdentifier {
MonitorServiceList,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MonitorServiceList {
#[serde(flatten)]
pub alerts_meta_data_properties: AlertsMetaDataProperties,
#[serde(flatten)]
pub serde_json_value: serde_json::Value,
pub data: Vec<MonitorServiceDetails>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MonitorServiceDetails {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SmartGroupModification {
#[serde(flatten)]
pub resource: Resource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<SmartGroupModificationProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SmartGroupModificationProperties {
#[serde(rename = "smartGroupId", default, skip_serializing_if = "Option::is_none")]
pub smart_group_id: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub modifications: Vec<SmartGroupModificationItem>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SmartGroupModificationItem {
#[serde(rename = "modificationEvent", default, skip_serializing_if = "Option::is_none")]
pub modification_event: Option<smart_group_modification_item::ModificationEvent>,
#[serde(rename = "oldValue", default, skip_serializing_if = "Option::is_none")]
pub old_value: Option<String>,
#[serde(rename = "newValue", default, skip_serializing_if = "Option::is_none")]
pub new_value: Option<String>,
#[serde(rename = "modifiedAt", default, skip_serializing_if = "Option::is_none")]
pub modified_at: Option<String>,
#[serde(rename = "modifiedBy", default, skip_serializing_if = "Option::is_none")]
pub modified_by: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub comments: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
pub mod smart_group_modification_item {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ModificationEvent {
SmartGroupCreated,
StateChange,
AlertAdded,
AlertRemoved,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SmartGroupsList {
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<SmartGroup>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SmartGroup {
#[serde(flatten)]
pub resource: Resource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<SmartGroupProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SmartGroupProperties {
#[serde(rename = "alertsCount", default, skip_serializing_if = "Option::is_none")]
pub alerts_count: Option<i64>,
#[serde(rename = "smartGroupState", default, skip_serializing_if = "Option::is_none")]
pub smart_group_state: Option<smart_group_properties::SmartGroupState>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub severity: Option<smart_group_properties::Severity>,
#[serde(rename = "startDateTime", default, skip_serializing_if = "Option::is_none")]
pub start_date_time: Option<String>,
#[serde(rename = "lastModifiedDateTime", default, skip_serializing_if = "Option::is_none")]
pub last_modified_date_time: Option<String>,
#[serde(rename = "lastModifiedUserName", default, skip_serializing_if = "Option::is_none")]
pub last_modified_user_name: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub resources: Vec<SmartGroupAggregatedProperty>,
#[serde(rename = "resourceTypes", default, skip_serializing_if = "Vec::is_empty")]
pub resource_types: Vec<SmartGroupAggregatedProperty>,
#[serde(rename = "resourceGroups", default, skip_serializing_if = "Vec::is_empty")]
pub resource_groups: Vec<SmartGroupAggregatedProperty>,
#[serde(rename = "monitorServices", default, skip_serializing_if = "Vec::is_empty")]
pub monitor_services: Vec<SmartGroupAggregatedProperty>,
#[serde(rename = "monitorConditions", default, skip_serializing_if = "Vec::is_empty")]
pub monitor_conditions: Vec<SmartGroupAggregatedProperty>,
#[serde(rename = "alertStates", default, skip_serializing_if = "Vec::is_empty")]
pub alert_states: Vec<SmartGroupAggregatedProperty>,
#[serde(rename = "alertSeverities", default, skip_serializing_if = "Vec::is_empty")]
pub alert_severities: Vec<SmartGroupAggregatedProperty>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
pub mod smart_group_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum SmartGroupState {
New,
Acknowledged,
Closed,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Severity {
Sev0,
Sev1,
Sev2,
Sev3,
Sev4,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SmartGroupAggregatedProperty {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub count: Option<i64>,
}
|
use ast;
use ast::AstExpressionNode;
use ast::Block;
use ast::PointerType;
use ast::Expression;
use ast::Function;
use ast::FunctionCall;
use ast::Program;
use ast::Statement;
use ast::VarType;
use code_block::CodeBlock;
use std::collections::VecDeque;
use std::collections::HashMap;
// This function checks that the "owned_pointers"
// are "moved."
// We also insert calls to free() here to destroy the owned_pointers
// who go out of scope/before "return"
// This must be done after type checking
// Problems with this so far:
// Need to disallow stuff like *&*&my_owned_pointer
// Need way of destroying structs who have owned_pointers inside them
// Right now we assume we cannot return owned_pointers
//
// TODO: Rerun the typechecker again after this runs,
// that way we won't have to add in the types which feels hackish
#[derive(Clone, Copy, PartialEq)]
enum OwnedPointerStatus {
// It stores a pointer to something, and we want to free
// it at the end
Alive,
// This pointer has been moved, so it can never be used again
Moved,
}
struct OwnedPointerInfo {
status: OwnedPointerStatus,
target_type: VarType,
}
struct OwnedPointerTransformer {
blocks: Vec<CodeBlock>,
pointer_to_info: HashMap<String, OwnedPointerInfo>,
}
fn get_free_call(varname: &str, typ: &VarType) -> Statement {
let mut arg = AstExpressionNode::new(
Expression::Variable(varname.to_string()));
// FIXME: This feels weird, setting the type manually
// Instead we should try to re-run the type checker after
// this transformation, and it'll do that for us.
arg.typ = Some(typ.clone());
let fn_call = FunctionCall {name: "free".to_string(),
args_exprs: vec![arg]
};
Statement::Call(fn_call)
}
impl OwnedPointerTransformer {
pub fn new() -> OwnedPointerTransformer {
OwnedPointerTransformer {
blocks: Vec::new(),
pointer_to_info: HashMap::new(),
}
}
// Given a statement, return a list of statements to replace it with
fn transform_stmt(&mut self,
stmt: Statement) -> Vec<Statement> {
// FIXME: Do match *&mut stmt instead, to avoid having all the weird returns
match stmt {
Statement::Return(expr) => {
// TODO: Right now we assume no owned_pointer is returned
let mut res = Vec::new();
// We're about to return, so destroy all alive owned pointers
for (name, info) in self.pointer_to_info.iter() {
if info.status == OwnedPointerStatus::Moved {
continue;
}
res.push(get_free_call(name, &info.target_type));
}
res.push(Statement::Return(expr));
res
}
Statement::If(expr, then_block, else_block_opt) => {
vec![Statement::If(expr, then_block, else_block_opt)]
}
Statement::While(expr, block) => {
vec![Statement::While(expr, block)]
}
Statement::Let(name, typ, value_expr) => {
if let VarType::Pointer(PointerType::Owned,
ref to_typ) = *&typ {
// Keep track of which block this owned_pointer was
// declared in
self.blocks.last_mut()
.expect("No current block!")
.declared_variables.insert(name.clone());
// TODO deal with case where we're moving another
// shared pointer
let info = OwnedPointerInfo {
status: OwnedPointerStatus::Alive,
target_type: *(to_typ.clone()),
};
self.pointer_to_info.insert(name.clone(), info);
}
vec![Statement::Let(name, typ, value_expr)]
}
Statement::Assign(left_expr, right_expr) => {
vec![Statement::Assign(left_expr, right_expr)]
}
Statement::Call(fn_call) => {
vec![Statement::Call(fn_call)]
}
Statement::Print(expr) => {
vec![Statement::Print(expr)]
}
}
}
// Free all the pointers who were declared in the current block
// Add the free instructions to the end of the block.
fn free_pointers_in_cur_block(&mut self, block: &mut Block) {
// If the last statement is a return statement, we don't
// need to add free calls after it
if let Some(&Statement::Return(_)) = block.statements.back() {
return;
}
// Else free everything declared in that block
let b = self.blocks.last().expect("No current block!");
for varname in b.declared_variables.iter() {
let var_info = self.pointer_to_info.get(varname)
.expect("var not in pointer_to_info");
let call = get_free_call(&varname, &var_info.target_type);
block.statements.push_back(call);
}
}
fn transform_block(&mut self, block: &mut ast::Block) {
// Clear some data structures here probably
self.blocks.push(CodeBlock::new());
// Analyze each statement, and replace it with whatever the
// transform function tells us to
let mut new_statements = VecDeque::new();
while let Some(stmt) = block.statements.pop_front() {
let replacement = self.transform_stmt(stmt);
new_statements.extend(replacement);
}
block.statements = new_statements;
// If the last statement of the block is not a return, then we need
// to free all of the owned_pointers in that block
self.free_pointers_in_cur_block(block);
let b = self.blocks.pop().expect("No current block!");
for variable in b.declared_variables {
self.pointer_to_info.remove(&variable);
}
}
fn transform_function(&mut self, function: &mut Function) {
self.transform_block(&mut function.statements);
}
pub fn transform_program(&mut self, program: &mut Program) {
for fun in program.functions.iter_mut() {
self.transform_function(fun);
}
}
}
pub fn transform_program(program: &mut Program) {
let mut t = OwnedPointerTransformer::new();
t.transform_program(program);
}
|
#![allow(non_snake_case)]
#![allow(unused_assignments)]
#![allow(dead_code)]
use libc::{c_int,c_uint, c_void};
use super::encode::{UTF82UCS2,UCS2TOUTF8};
use super::types::{MSG};
pub type DWnd = * const c_void;
extern "stdcall"{
//Window Text
pub fn GetWindowTextLengthW(hWnd:DWnd)->c_int;
pub fn GetWindowTextW(hWnd:DWnd,lp:*const u16,cch:u32);
pub fn SetWindowTextW(hwnd:DWnd, text: * const u16);
}
pub trait TWnd
{
// 返回真表示消息没被处理.
// 它负责根据哈希表,找到对应的窗体的事件处理器.
fn processMsg(&self, msg:& MSG)->bool{
true
}
/*
获取窗体文本
*/
fn GetText(&self)->String;
fn SetText(&self, text:&str);
}
impl TWnd for DWnd{
// 返回真表示消息没被处理.
// 它负责根据哈希表,找到对应的窗体的事件处理器.
/*
获取窗体文本
*/
fn GetText(&self)->String{
let sz;
unsafe{
sz = GetWindowTextLengthW(*self);
let mut vec:Vec<u16> = Vec::with_capacity((1 +sz) as uint);
vec.set_len((sz) as uint);
GetWindowTextW(*self,vec.as_ptr(), ((1 +sz) *2) as u32);
vec.push(0);
println!("vec sz={} raw={}",sz, vec);
return UCS2TOUTF8(&vec);
}
"".to_string()
}
fn SetText(&self, text:&str){
unsafe{
SetWindowTextW(*self,UTF82UCS2(text).as_ptr());
}
}
}
|
mod triangle;
mod wall;
use wall::Wall;
fn main() {
let wall = Wall::new(String::from("input.txt"));
println!("Number possible triangles on wall: {}",
wall.possible_triangles_count());
}
|
use std::iter::FromIterator;
use std::collections::HashSet;
//was to lazy to implement my own data structure so I just used one from cargo
//Didn't reuse the dfs implementation from day12
extern crate disjoint_set;
use disjoint_set::DisjointSet;
#[allow(dead_code)]
const TEST_INPUT: &str = "flqrgnkx";
const GRID_ROW_COUNT: usize = 128;
//NOTE: There are many approaches to do Part2. I chose a pretty verbose
//one. I particularily liked this solution:
//https://www.reddit.com/r/adventofcode/comments/7jpelc/2017_day_14_solutions/dr87cn7/
fn main() {
//Part1
let input = "ffayrhll";
//let test_inp = "flqrgnkx";
let sum: usize = (0..GRID_ROW_COUNT).map(|row| {
let row_in = format!("{}-{}", input, row);
let row_hash = knot_hash(&row_in);
let row_bin = convert_hash_to_bits(&row_hash);
row_bin.iter().filter(|&bit| *bit).count()
}).sum();
println!("The number of used bits in the grid is: {}", sum);
//Part2 actually building the grid and doing union-find with it
let input = "ffayrhll";
let grid: Vec<Vec<bool>> = (0..GRID_ROW_COUNT).map(|row| {
let row_in = format!("{}-{}", input, row);
let row_hash = knot_hash(&row_in);
let row_bin = convert_hash_to_bits(&row_hash);
row_bin.into_iter().collect()
}).collect();
//Run through the whole grid once to build up the connected parts
let mut uf = DisjointSet::new();
for y in 0..GRID_ROW_COUNT {
let column = &grid[y];
for x in 0..column.len() {
let elem = column[x];
if elem {
uf.make_set((y, x));
for (ny, nx) in get_neighbour_idxs((y, x)) {
if grid[ny][nx] {
//Try to union them. If the neighbour is not yet in the
//data structure this will error. We don't care though
//since we will never hit that case
uf.union((y, x), (ny, nx)).unwrap();
}
}
}
}
}
//Run through the uf once more to get the data out
//NOTE: Has no convenient way to query the number of connected parts..
let mut set = HashSet::new();
for y in 0..GRID_ROW_COUNT {
for x in 0..grid[y].len() {
if let Some(tag) = uf.find((y, x)) {
set.insert(tag);
}
}
}
println!("Number of connected areas in the grid: {}", set.len());
}
fn get_neighbour_idxs((y, x): (usize, usize)) -> Vec<(usize, usize)> {
let mut res = vec![];
//Give all indices while being carefull not to step outside the grid
//We only have to consider neighbours on the top left from our current
//cause the others will be later in the algorithm and are not yet in our
//union find data structure
if y != 0 {
res.push((y - 1, x));
}
if x != 0 {
res.push((y, x - 1));
}
res
}
fn convert_hash_to_bits(hash: &str) -> Vec<bool> {
let bin_iter = hash.chars().map(|c| {
//convert the hex symbol to a number
let num = c.to_digit(16).unwrap();
//convert it back to binary
format!("{:04b}", num)
});
let mut res = vec![];
for bin_num in bin_iter {
for bit in bin_num.chars() {
if bit == '1' {
res.push(true)
} else {
res.push(false)
}
}
}
debug_assert!(res.len() == 4*hash.len());
res
}
//Everything below here is hoisted from day10 solution for knot_hashes
const APPEND_LENGHTS: [u8; 5] = [17, 31, 73, 47, 23];
const ROPE_LENGTH: u8 = 255;
const ROUNDS: usize = 64;
fn knot_hash(inp: &str) -> String {
let mut input = str_to_bytes(inp);
input.extend_from_slice(&APPEND_LENGHTS);
let mut rope = Vec::from_iter((0..ROPE_LENGTH));
//stupid but range doesn't accept 256 because out of range of u8!
rope.push(ROPE_LENGTH);
//Do the same stuff for 64 rounds
let mut position = 0;
let mut skip = 0;
for _ in 0..ROUNDS {
for inp in input.iter() {
reverse_subrope(position, position + *inp as usize, &mut rope);
position = (position + *inp as usize + skip) % rope.len();
skip += 1;
}
}
let dense_hash = create_dense(&rope);
dense_hash
.iter()
.map(|elem| format!("{:02x}", *elem))
.collect()
}
fn str_to_bytes(inp: &str) -> Vec<u8> {
inp.trim()
.chars()
.map(|c| {
if (c as u32) < 256 {
c as u8
} else {
panic!{"Only expecting ascii symbols"}
}
})
.collect()
}
/*
Reverse the subrope delimited by start and end
end has to be > start but is not limited to the rope and instead
wraps around
start and end inclusive
*/
fn reverse_subrope(start: usize, end: usize, rope: &mut [u8]) {
assert!(end >= start);
assert!((end - start) <= rope.len());
let mut start = start;
let mut end = end - 1;
while start < end {
let len = rope.len();
rope.swap(start % len, end % len);
start += 1;
end -= 1;
}
}
fn create_dense(sparse: &[u8]) -> Vec<u8> {
//move over our input in chunks of 16 items and calculate their XOR
sparse
.chunks(16)
.map(|chunk| {
chunk.iter().fold(0, |acc, &elem| acc ^ elem)
})
.collect()
} |
use std::collections::hash_map::Entry;
use std::collections::{HashMap, HashSet};
use std::error;
use std::fmt;
use std::io;
use std::iter::FromIterator;
use crate::disk::chain::ChainIterator;
use crate::disk::error::DiskError;
use crate::disk::file::FileOps;
use crate::disk::format::DiskFormat;
use crate::disk::DirectoryEntry;
use crate::disk::Disk;
use crate::disk::Location;
use crate::petscii::Petscii;
/// A validation error represents an inconsistency in the disk image found by
/// the validate() function.
#[derive(Clone, Debug, PartialEq)]
pub enum ValidationError {
Unknown,
SystemSectorNotAllocated(Location),
SectorMisallocated(Location),
SectorMisoccupied(Location, Petscii),
SectorOveroccupied(Location, Petscii, Petscii),
FileScanError(DiskError, Petscii),
}
impl error::Error for ValidationError {
/// Provide terse descriptions of the errors.
fn description(&self) -> &str {
self.message()
}
}
impl fmt::Display for ValidationError {
/// Provide human-readable descriptions of the errors.
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use self::ValidationError::*;
match *self {
SystemSectorNotAllocated(l) => write!(f, "System sector not allocated: {}", l),
SectorMisallocated(l) => write!(f, "Sector misallocated: {}", l),
SectorMisoccupied(l, ref filename) => {
write!(f, "Sector {} misoccupied by file: {:?}", l, filename)
}
SectorOveroccupied(location, ref filename1, ref filename2) => write!(
f,
"Sector {} occupied by multiple files, including at least: {:?} {:?}",
location, filename1, filename2
),
FileScanError(ref e, ref filename) => write!(f, "Error scanning {:?}: {}", filename, e),
_ => f.write_str(self.message()),
}
}
}
impl ValidationError {
/// Provide terse descriptions of the errors.
fn message(&self) -> &str {
use self::ValidationError::*;
match *self {
Unknown => "Unknown error",
SystemSectorNotAllocated(_) => "System sector not allocated",
SectorMisallocated(_) => "Sector misallocated",
SectorMisoccupied(_, _) => "Sector misoccupied",
SectorOveroccupied(_, _, _) => "Sector occupied by multiple files",
FileScanError(_, _) => "File scan error",
}
}
}
/// Convert a slice of Locations to a HashSet.
fn hashset_from_locations(data: &[Location]) -> HashSet<Location> {
HashSet::from_iter(data.iter().cloned())
}
/// Given a set of locations, return the inverse -- that is, a set of all of
/// the disk's locations that were not represented in the given set.
fn invert_locations(locations: &HashSet<Location>, format: &DiskFormat) -> HashSet<Location> {
let mut inverse = HashSet::new();
for track in format.first_track..=format.last_track {
for sector in 0..format.tracks[track as usize].sectors {
let location = Location::new(track, sector);
if !locations.contains(&location) {
inverse.insert(location);
}
}
}
inverse
}
/// Open the specified file and return a list of all occupied sectors. This is
/// its own function so we can handle either of two possible error sources as
/// one.
fn scan_file<T: Disk>(disk: &T, entry: &DirectoryEntry) -> io::Result<Vec<Location>>
where
T: ?Sized,
{
disk.open_file_from_entry(entry)?.occupied_sectors()
}
/// Check the consistency of the provided disk. Unlike the "validate" ("v0:")
/// command in CBM DOS, this is a read-only operation and does not attempt any
/// repairs. A list of validation errors is returned.
pub fn validate<T: Disk>(disk: &T) -> io::Result<Vec<ValidationError>>
where
T: ?Sized,
{
static SYSTEM_OWNER: &str = "CBM DOS";
let mut errors: Vec<ValidationError> = vec![];
let format = disk.disk_format()?;
let bam_ref = disk.bam()?;
let bam = bam_ref.borrow_mut();
let system_sectors = hashset_from_locations(&format.system_locations());
let allocated_sectors = hashset_from_locations(&bam.allocated_sectors()?);
let free_sectors = hashset_from_locations(&bam.free_sectors()?);
// Build a list of all occupied sectors and their owners
// 1. System sectors
let mut occupied_sector_map: HashMap<Location, Petscii> = HashMap::new();
for system_sector in system_sectors.iter() {
occupied_sector_map.insert(*system_sector, SYSTEM_OWNER.into());
}
// 2. Add the directory chain as occupied sectors.
let directory_start = Location::new(format.directory_track, format.first_directory_sector);
let mut directory_locations = ChainIterator::new(disk.blocks(), directory_start)
.map(|r| r.map(|cs| cs.location))
.collect::<io::Result<Vec<_>>>()?;
if let Some(ref geos_header) = disk.header()?.geos {
// Add the GEOS border sector if this is a GEOS disk.
directory_locations.push(geos_header.border);
}
for location in directory_locations {
occupied_sector_map.insert(location, SYSTEM_OWNER.into());
}
// 3. All files
for entry in disk.iter() {
let entry = entry?;
let file_occupied_sectors = match scan_file(disk, &entry) {
Ok(file_occupied_sectors) => file_occupied_sectors,
Err(e) => match DiskError::from_io_error(&e) {
Some(e) => {
errors.push(ValidationError::FileScanError(e, entry.filename.clone()));
continue;
}
None => return Err(e),
},
};
for location in file_occupied_sectors.iter() {
match occupied_sector_map.entry(*location) {
Entry::Occupied(owner) => {
errors.push(ValidationError::SectorOveroccupied(
*location,
owner.get().clone(),
entry.filename.clone(),
));
}
Entry::Vacant(v) => {
v.insert(entry.filename.clone());
}
};
}
}
let occupied_sectors = HashSet::from_iter(occupied_sector_map.keys().copied());
let unoccupied_sectors = invert_locations(&occupied_sectors, format);
// Confirm all system sectors are still allocated
for location in system_sectors.iter() {
if !allocated_sectors.contains(location) {
errors.push(ValidationError::SystemSectorNotAllocated(*location));
}
}
// Look for sectors that are allocated but not occupied.
for misallocated_sector in allocated_sectors.intersection(&unoccupied_sectors) {
errors.push(ValidationError::SectorMisallocated(*misallocated_sector));
}
// Look for sectors that are occupied but not allocated.
for misoccupied_sector in free_sectors.intersection(&occupied_sectors) {
if system_sectors.contains(misoccupied_sector) {
// System sector misoccupation was handled with SystemSectorNotAllocated above.
continue;
}
let filename = occupied_sector_map
.get(misoccupied_sector)
.cloned()
.unwrap_or_else(|| "None".into());
errors.push(ValidationError::SectorMisoccupied(
*misoccupied_sector,
filename.clone(),
));
}
Ok(errors)
}
|
use crate::{buffer::Span, Cell, Merge, Settings};
pub use direction::Direction;
pub use fragment::Fragment;
pub use fragment_span::FragmentSpan;
pub use fragment_tree::FragmentTree;
use itertools::Itertools;
use std::{
collections::BTreeMap,
fmt::Write,
ops::{Deref, DerefMut},
};
pub mod direction;
pub mod fragment;
mod fragment_span;
mod fragment_tree;
/// Fragment buffer contains the drawing fragments for each cell
/// Svg can be converted to fragment buffer
/// then from the fragment we can match which characters is best suited for
/// a particular set of fragment contained in a cell and then create a stringbuffer.
/// The stringbuffer becomes the ascii diagrams
/// SVG -> FragmentBuffer -> StringBuffer -> Ascii Diagrams
///
/// We can also create a reverse
/// Ascii Diagrams -> String Buffer -> Fragment Buffer -> SVG
///
/// ```ignore
/// 0 1 2 3 4 B C D
/// 0┌─┬─┬─┬─┐ A┌─┬─┬─┬─┐E
/// 1├─┼─┼─┼─┤ │ │ │ │ │
/// 2├─┼─┼─┼─┤ F├─G─H─I─┤J
/// 3├─┼─┼─┼─┤ │ │ │ │ │
/// 4├─┼─┼─┼─┤ K├─L─M─N─┤O
/// 5├─┼─┼─┼─┤ │ │ │ │ │
/// 6├─┼─┼─┼─┤ P├─Q─R─S─┤T
/// 7├─┼─┼─┼─┤ │ │ │ │ │
/// 8└─┴─┴─┴─┘ U└─┴─┴─┴─┘Y
/// ``` V W X
/// TODO: rename this to FragmentSpan Buffer
#[derive(Debug, Default)]
pub struct FragmentBuffer(BTreeMap<Cell, Vec<FragmentSpan>>);
impl Deref for FragmentBuffer {
type Target = BTreeMap<Cell, Vec<FragmentSpan>>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for FragmentBuffer {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl FragmentBuffer {
pub fn new() -> Self {
FragmentBuffer::default()
}
/// dump for debugging purpose only
/// printling the fragments on this fragment buffer
pub fn dump(&self) -> String {
let mut buff = String::new();
for (cell, shapes) in self.iter() {
write!(buff, "\ncell: {} ", cell);
for shape in shapes {
write!(buff, "\n {}", shape.fragment);
}
}
buff
}
/// sort the fragments content in this cell
fn sort_fragments_in_cell(&mut self, cell: Cell) {
if let Some(fragments) = &mut self.get_mut(&cell) {
(*fragments).sort();
}
}
fn bounds(&self) -> Option<(Cell, Cell)> {
let xlimits =
self.iter().map(|(cell, _)| cell.x).minmax().into_option();
let ylimits =
self.iter().map(|(cell, _)| cell.y).minmax().into_option();
match (xlimits, ylimits) {
(Some((min_x, max_x)), Some((min_y, max_y))) => {
Some((Cell::new(min_x, min_y), Cell::new(max_x, max_y)))
}
_ => None,
}
}
pub fn get_size(&self, settings: &Settings) -> (f32, f32) {
let (_top_left, bottom_right) =
self.bounds().unwrap_or((Cell::new(0, 0), Cell::new(0, 0)));
let w = settings.scale * (bottom_right.x + 2) as f32 * Cell::width();
let h = settings.scale * (bottom_right.y + 2) as f32 * Cell::height();
(w, h)
}
/// Note: Same fragment span can be stored in the same cell
/// as it simplifies the algorithm for mergin marker line (lines with dots, and arrows)
/// Since they will be attached to each other at the cell level
fn add_fragment_span_to_cell(
&mut self,
cell: Cell,
fragment_span: FragmentSpan,
) {
if let Some(existing) = self.get_mut(&cell) {
if !existing.contains(&fragment_span) {
existing.push(fragment_span);
} else {
println!("already contain fragment span..");
}
} else {
self.insert(cell, vec![fragment_span]);
}
self.sort_fragments_in_cell(cell);
}
/// Add a single fragment to this cell
pub fn add_fragment_to_cell(
&mut self,
cell: Cell,
ch: char,
fragment: Fragment,
) {
let fragment_span = FragmentSpan::new(Span::new(cell, ch), fragment);
self.add_fragment_span_to_cell(cell, fragment_span);
}
/// add multiple fragments to cell
pub fn add_fragments_to_cell(
&mut self,
cell: Cell,
ch: char,
fragments: Vec<Fragment>,
) {
let fragment_spans = fragments
.into_iter()
.map(|fragment| FragmentSpan {
span: Span::new(cell, ch),
fragment,
})
.collect();
if let Some(existing) = self.get_mut(&cell) {
existing.extend(fragment_spans);
} else {
self.insert(cell, fragment_spans);
}
self.sort_fragments_in_cell(cell);
}
pub fn merge_fragment_spans(&self) -> Vec<FragmentSpan> {
let fragment_spans = self.abs_fragment_spans();
FragmentSpan::merge_recursive(fragment_spans)
}
/// Collect all the fragment span where all fragment spans of each cell
/// are converted to their absolute position
fn abs_fragment_spans(&self) -> Vec<FragmentSpan> {
self.iter()
.flat_map(|(cell, fragment_spans)| {
fragment_spans
.iter()
.map(|frag_span| frag_span.absolute_position(*cell))
})
.collect()
}
}
|
#[derive(Default)]
struct PizzaConfig {
wants_cheese: bool,
number_of_olives: i32,
special_message: String,
crust_type: CrustType
}
enum CrustType {
Thin,
Thick
}
impl Default for CrustType {
fn default() -> CrustType {
CrustType::Thin
}
}
fn main() {
let foo: i32 = Default::default();
println!("foo = {}", foo);
let pizza: PizzaConfig = Default::default();
println!("want cheese {}", pizza.wants_cheese);
println!("olive {}", pizza.number_of_olives);
println!("messege {}", pizza.special_message);
let crust_type =
match pizza.crust_type {
CrustType::Thin => "Nice and Thin",
CrustType::Thick => "Extra Thick"
};
println!("crust {}", crust_type);
} |
//! These callbacks should be registered in order to be used by the Lua libraries.
//! Only one struct can be used by each interface, but the interfaces can share
//! as many structs as they want. It's recommended you have one struct per
//! interface, though you can just use one struct if you wish.
// Callback modules
pub mod awesome;
pub mod button;
pub mod client;
pub mod drawin;
pub mod drawable;
pub mod keygrabber;
pub mod mousegrabber;
pub mod mouse;
pub mod root;
pub mod screen;
pub mod tag;
pub use self::awesome::Awesome;
pub use self::button::Button;
pub use self::client::Client;
pub use self::drawin::Drawin;
pub use self::drawable::Drawable;
pub use self::keygrabber::Keygrabber;
pub use self::mousegrabber::Mousegrabber;
pub use self::mouse::Mouse;
pub use self::root::Root;
pub use self::screen::Screen;
pub use self::tag::Tag;
|
#[doc = "Register `CSR` reader"]
pub type R = crate::R<CSR_SPEC>;
#[doc = "Register `CSR` writer"]
pub type W = crate::W<CSR_SPEC>;
#[doc = "Field `LSION` reader - LSI oscillator enable"]
pub type LSION_R = crate::BitReader<LSION_A>;
#[doc = "LSI oscillator enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LSION_A {
#[doc = "0: LSI oscillator OFF"]
Disabled = 0,
#[doc = "1: LSI oscillator ON"]
Enabled = 1,
}
impl From<LSION_A> for bool {
#[inline(always)]
fn from(variant: LSION_A) -> Self {
variant as u8 != 0
}
}
impl LSION_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> LSION_A {
match self.bits {
false => LSION_A::Disabled,
true => LSION_A::Enabled,
}
}
#[doc = "LSI oscillator OFF"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == LSION_A::Disabled
}
#[doc = "LSI oscillator ON"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == LSION_A::Enabled
}
}
#[doc = "Field `LSION` writer - LSI oscillator enable"]
pub type LSION_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, LSION_A>;
impl<'a, REG, const O: u8> LSION_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "LSI oscillator OFF"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(LSION_A::Disabled)
}
#[doc = "LSI oscillator ON"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(LSION_A::Enabled)
}
}
#[doc = "Field `LSIRDY` reader - LSI oscillator ready"]
pub type LSIRDY_R = crate::BitReader<LSIRDY_A>;
#[doc = "LSI oscillator ready\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LSIRDY_A {
#[doc = "0: LSI oscillator not ready"]
NotReady = 0,
#[doc = "1: LSI oscillator ready"]
Ready = 1,
}
impl From<LSIRDY_A> for bool {
#[inline(always)]
fn from(variant: LSIRDY_A) -> Self {
variant as u8 != 0
}
}
impl LSIRDY_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> LSIRDY_A {
match self.bits {
false => LSIRDY_A::NotReady,
true => LSIRDY_A::Ready,
}
}
#[doc = "LSI oscillator not ready"]
#[inline(always)]
pub fn is_not_ready(&self) -> bool {
*self == LSIRDY_A::NotReady
}
#[doc = "LSI oscillator ready"]
#[inline(always)]
pub fn is_ready(&self) -> bool {
*self == LSIRDY_A::Ready
}
}
#[doc = "Field `LSIPREDIV` reader - Internal low-speed oscillator predivided by 128"]
pub type LSIPREDIV_R = crate::BitReader<LSIPREDIV_A>;
#[doc = "Internal low-speed oscillator predivided by 128\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LSIPREDIV_A {
#[doc = "0: LSI PREDIV OFF"]
Disabled = 0,
#[doc = "1: LSI PREDIV ON"]
Enabled = 1,
}
impl From<LSIPREDIV_A> for bool {
#[inline(always)]
fn from(variant: LSIPREDIV_A) -> Self {
variant as u8 != 0
}
}
impl LSIPREDIV_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> LSIPREDIV_A {
match self.bits {
false => LSIPREDIV_A::Disabled,
true => LSIPREDIV_A::Enabled,
}
}
#[doc = "LSI PREDIV OFF"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == LSIPREDIV_A::Disabled
}
#[doc = "LSI PREDIV ON"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == LSIPREDIV_A::Enabled
}
}
#[doc = "Field `LSIPREDIV` writer - Internal low-speed oscillator predivided by 128"]
pub type LSIPREDIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, LSIPREDIV_A>;
impl<'a, REG, const O: u8> LSIPREDIV_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "LSI PREDIV OFF"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(LSIPREDIV_A::Disabled)
}
#[doc = "LSI PREDIV ON"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(LSIPREDIV_A::Enabled)
}
}
#[doc = "Field `MSISRANGE` reader - SI range after Standby mode"]
pub type MSISRANGE_R = crate::FieldReader<MSISRANGE_A>;
#[doc = "SI range after Standby mode\n\nValue on reset: 6"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum MSISRANGE_A {
#[doc = "4: range 4 around 1 MHz"]
Range1m = 4,
#[doc = "5: range 5 around 2 MHz"]
Range2m = 5,
#[doc = "6: range 6 around 4 MHz"]
Range4m = 6,
#[doc = "7: range 7 around 8 MHz"]
Range8m = 7,
}
impl From<MSISRANGE_A> for u8 {
#[inline(always)]
fn from(variant: MSISRANGE_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for MSISRANGE_A {
type Ux = u8;
}
impl MSISRANGE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<MSISRANGE_A> {
match self.bits {
4 => Some(MSISRANGE_A::Range1m),
5 => Some(MSISRANGE_A::Range2m),
6 => Some(MSISRANGE_A::Range4m),
7 => Some(MSISRANGE_A::Range8m),
_ => None,
}
}
#[doc = "range 4 around 1 MHz"]
#[inline(always)]
pub fn is_range1m(&self) -> bool {
*self == MSISRANGE_A::Range1m
}
#[doc = "range 5 around 2 MHz"]
#[inline(always)]
pub fn is_range2m(&self) -> bool {
*self == MSISRANGE_A::Range2m
}
#[doc = "range 6 around 4 MHz"]
#[inline(always)]
pub fn is_range4m(&self) -> bool {
*self == MSISRANGE_A::Range4m
}
#[doc = "range 7 around 8 MHz"]
#[inline(always)]
pub fn is_range8m(&self) -> bool {
*self == MSISRANGE_A::Range8m
}
}
#[doc = "Field `MSISRANGE` writer - SI range after Standby mode"]
pub type MSISRANGE_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O, MSISRANGE_A>;
impl<'a, REG, const O: u8> MSISRANGE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "range 4 around 1 MHz"]
#[inline(always)]
pub fn range1m(self) -> &'a mut crate::W<REG> {
self.variant(MSISRANGE_A::Range1m)
}
#[doc = "range 5 around 2 MHz"]
#[inline(always)]
pub fn range2m(self) -> &'a mut crate::W<REG> {
self.variant(MSISRANGE_A::Range2m)
}
#[doc = "range 6 around 4 MHz"]
#[inline(always)]
pub fn range4m(self) -> &'a mut crate::W<REG> {
self.variant(MSISRANGE_A::Range4m)
}
#[doc = "range 7 around 8 MHz"]
#[inline(always)]
pub fn range8m(self) -> &'a mut crate::W<REG> {
self.variant(MSISRANGE_A::Range8m)
}
}
#[doc = "Field `RMVF` reader - Remove reset flag"]
pub type RMVF_R = crate::BitReader<RMVF_A>;
#[doc = "Remove reset flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RMVF_A {
#[doc = "0: No effect"]
NoEffect = 0,
#[doc = "1: Clear the reset flags"]
Clear = 1,
}
impl From<RMVF_A> for bool {
#[inline(always)]
fn from(variant: RMVF_A) -> Self {
variant as u8 != 0
}
}
impl RMVF_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> RMVF_A {
match self.bits {
false => RMVF_A::NoEffect,
true => RMVF_A::Clear,
}
}
#[doc = "No effect"]
#[inline(always)]
pub fn is_no_effect(&self) -> bool {
*self == RMVF_A::NoEffect
}
#[doc = "Clear the reset flags"]
#[inline(always)]
pub fn is_clear(&self) -> bool {
*self == RMVF_A::Clear
}
}
#[doc = "Field `RMVF` writer - Remove reset flag"]
pub type RMVF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, RMVF_A>;
impl<'a, REG, const O: u8> RMVF_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "No effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut crate::W<REG> {
self.variant(RMVF_A::NoEffect)
}
#[doc = "Clear the reset flags"]
#[inline(always)]
pub fn clear(self) -> &'a mut crate::W<REG> {
self.variant(RMVF_A::Clear)
}
}
#[doc = "Field `FWRSTF` reader - Firewall reset flag"]
pub type FWRSTF_R = crate::BitReader<FWRSTF_A>;
#[doc = "Firewall reset flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FWRSTF_A {
#[doc = "0: No reset from the firewall occurred"]
NotOccured = 0,
#[doc = "1: Reset from the firewall occurred"]
Occured = 1,
}
impl From<FWRSTF_A> for bool {
#[inline(always)]
fn from(variant: FWRSTF_A) -> Self {
variant as u8 != 0
}
}
impl FWRSTF_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> FWRSTF_A {
match self.bits {
false => FWRSTF_A::NotOccured,
true => FWRSTF_A::Occured,
}
}
#[doc = "No reset from the firewall occurred"]
#[inline(always)]
pub fn is_not_occured(&self) -> bool {
*self == FWRSTF_A::NotOccured
}
#[doc = "Reset from the firewall occurred"]
#[inline(always)]
pub fn is_occured(&self) -> bool {
*self == FWRSTF_A::Occured
}
}
#[doc = "Field `OBLRSTF` reader - Option byte loader reset flag"]
pub type OBLRSTF_R = crate::BitReader<OBLRSTF_A>;
#[doc = "Option byte loader reset flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OBLRSTF_A {
#[doc = "0: No reset from Option Byte loading occurred"]
NotOccured = 0,
#[doc = "1: Reset from Option Byte loading occurred"]
Occured = 1,
}
impl From<OBLRSTF_A> for bool {
#[inline(always)]
fn from(variant: OBLRSTF_A) -> Self {
variant as u8 != 0
}
}
impl OBLRSTF_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> OBLRSTF_A {
match self.bits {
false => OBLRSTF_A::NotOccured,
true => OBLRSTF_A::Occured,
}
}
#[doc = "No reset from Option Byte loading occurred"]
#[inline(always)]
pub fn is_not_occured(&self) -> bool {
*self == OBLRSTF_A::NotOccured
}
#[doc = "Reset from Option Byte loading occurred"]
#[inline(always)]
pub fn is_occured(&self) -> bool {
*self == OBLRSTF_A::Occured
}
}
#[doc = "Field `PINRSTF` reader - Pin reset flag"]
pub type PINRSTF_R = crate::BitReader<PINRSTF_A>;
#[doc = "Pin reset flag\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PINRSTF_A {
#[doc = "0: No reset from NRST pin occurred"]
NotOccured = 0,
#[doc = "1: Reset from NRST pin occurred"]
Occured = 1,
}
impl From<PINRSTF_A> for bool {
#[inline(always)]
fn from(variant: PINRSTF_A) -> Self {
variant as u8 != 0
}
}
impl PINRSTF_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> PINRSTF_A {
match self.bits {
false => PINRSTF_A::NotOccured,
true => PINRSTF_A::Occured,
}
}
#[doc = "No reset from NRST pin occurred"]
#[inline(always)]
pub fn is_not_occured(&self) -> bool {
*self == PINRSTF_A::NotOccured
}
#[doc = "Reset from NRST pin occurred"]
#[inline(always)]
pub fn is_occured(&self) -> bool {
*self == PINRSTF_A::Occured
}
}
#[doc = "Field `BORRSTF` reader - BOR flag"]
pub type BORRSTF_R = crate::BitReader<BORRSTF_A>;
#[doc = "BOR flag\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BORRSTF_A {
#[doc = "0: No BOR occurred"]
NotOccured = 0,
#[doc = "1: BOR occurred"]
Occured = 1,
}
impl From<BORRSTF_A> for bool {
#[inline(always)]
fn from(variant: BORRSTF_A) -> Self {
variant as u8 != 0
}
}
impl BORRSTF_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> BORRSTF_A {
match self.bits {
false => BORRSTF_A::NotOccured,
true => BORRSTF_A::Occured,
}
}
#[doc = "No BOR occurred"]
#[inline(always)]
pub fn is_not_occured(&self) -> bool {
*self == BORRSTF_A::NotOccured
}
#[doc = "BOR occurred"]
#[inline(always)]
pub fn is_occured(&self) -> bool {
*self == BORRSTF_A::Occured
}
}
#[doc = "Field `SFTRSTF` reader - Software reset flag"]
pub type SFTRSTF_R = crate::BitReader<SFTRSTF_A>;
#[doc = "Software reset flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SFTRSTF_A {
#[doc = "0: No software reset occurred"]
NotOccured = 0,
#[doc = "1: Software reset occurred"]
Occured = 1,
}
impl From<SFTRSTF_A> for bool {
#[inline(always)]
fn from(variant: SFTRSTF_A) -> Self {
variant as u8 != 0
}
}
impl SFTRSTF_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> SFTRSTF_A {
match self.bits {
false => SFTRSTF_A::NotOccured,
true => SFTRSTF_A::Occured,
}
}
#[doc = "No software reset occurred"]
#[inline(always)]
pub fn is_not_occured(&self) -> bool {
*self == SFTRSTF_A::NotOccured
}
#[doc = "Software reset occurred"]
#[inline(always)]
pub fn is_occured(&self) -> bool {
*self == SFTRSTF_A::Occured
}
}
#[doc = "Field `IWDGRSTF` reader - Independent window watchdog reset flag"]
pub type IWDGRSTF_R = crate::BitReader<IWDGRSTF_A>;
#[doc = "Independent window watchdog reset flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum IWDGRSTF_A {
#[doc = "0: No independent watchdog reset occurred"]
NotOccured = 0,
#[doc = "1: Independent watchdog reset occurred"]
Occured = 1,
}
impl From<IWDGRSTF_A> for bool {
#[inline(always)]
fn from(variant: IWDGRSTF_A) -> Self {
variant as u8 != 0
}
}
impl IWDGRSTF_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> IWDGRSTF_A {
match self.bits {
false => IWDGRSTF_A::NotOccured,
true => IWDGRSTF_A::Occured,
}
}
#[doc = "No independent watchdog reset occurred"]
#[inline(always)]
pub fn is_not_occured(&self) -> bool {
*self == IWDGRSTF_A::NotOccured
}
#[doc = "Independent watchdog reset occurred"]
#[inline(always)]
pub fn is_occured(&self) -> bool {
*self == IWDGRSTF_A::Occured
}
}
#[doc = "Field `WWDGRSTF` reader - Window watchdog reset flag"]
pub type WWDGRSTF_R = crate::BitReader<WWDGRSTF_A>;
#[doc = "Window watchdog reset flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WWDGRSTF_A {
#[doc = "0: No window watchdog reset occurred"]
NotOccured = 0,
#[doc = "1: Window watchdog reset occurred"]
Occured = 1,
}
impl From<WWDGRSTF_A> for bool {
#[inline(always)]
fn from(variant: WWDGRSTF_A) -> Self {
variant as u8 != 0
}
}
impl WWDGRSTF_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> WWDGRSTF_A {
match self.bits {
false => WWDGRSTF_A::NotOccured,
true => WWDGRSTF_A::Occured,
}
}
#[doc = "No window watchdog reset occurred"]
#[inline(always)]
pub fn is_not_occured(&self) -> bool {
*self == WWDGRSTF_A::NotOccured
}
#[doc = "Window watchdog reset occurred"]
#[inline(always)]
pub fn is_occured(&self) -> bool {
*self == WWDGRSTF_A::Occured
}
}
#[doc = "Field `LPWRRSTF` reader - Low-power reset flag"]
pub type LPWRRSTF_R = crate::BitReader<LPWRRSTF_A>;
#[doc = "Low-power reset flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LPWRRSTF_A {
#[doc = "0: No illegal mode reset occurred"]
NotOccured = 0,
#[doc = "1: Illegal mode reset occurred"]
Occured = 1,
}
impl From<LPWRRSTF_A> for bool {
#[inline(always)]
fn from(variant: LPWRRSTF_A) -> Self {
variant as u8 != 0
}
}
impl LPWRRSTF_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> LPWRRSTF_A {
match self.bits {
false => LPWRRSTF_A::NotOccured,
true => LPWRRSTF_A::Occured,
}
}
#[doc = "No illegal mode reset occurred"]
#[inline(always)]
pub fn is_not_occured(&self) -> bool {
*self == LPWRRSTF_A::NotOccured
}
#[doc = "Illegal mode reset occurred"]
#[inline(always)]
pub fn is_occured(&self) -> bool {
*self == LPWRRSTF_A::Occured
}
}
impl R {
#[doc = "Bit 0 - LSI oscillator enable"]
#[inline(always)]
pub fn lsion(&self) -> LSION_R {
LSION_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - LSI oscillator ready"]
#[inline(always)]
pub fn lsirdy(&self) -> LSIRDY_R {
LSIRDY_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 4 - Internal low-speed oscillator predivided by 128"]
#[inline(always)]
pub fn lsiprediv(&self) -> LSIPREDIV_R {
LSIPREDIV_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bits 8:11 - SI range after Standby mode"]
#[inline(always)]
pub fn msisrange(&self) -> MSISRANGE_R {
MSISRANGE_R::new(((self.bits >> 8) & 0x0f) as u8)
}
#[doc = "Bit 23 - Remove reset flag"]
#[inline(always)]
pub fn rmvf(&self) -> RMVF_R {
RMVF_R::new(((self.bits >> 23) & 1) != 0)
}
#[doc = "Bit 24 - Firewall reset flag"]
#[inline(always)]
pub fn fwrstf(&self) -> FWRSTF_R {
FWRSTF_R::new(((self.bits >> 24) & 1) != 0)
}
#[doc = "Bit 25 - Option byte loader reset flag"]
#[inline(always)]
pub fn oblrstf(&self) -> OBLRSTF_R {
OBLRSTF_R::new(((self.bits >> 25) & 1) != 0)
}
#[doc = "Bit 26 - Pin reset flag"]
#[inline(always)]
pub fn pinrstf(&self) -> PINRSTF_R {
PINRSTF_R::new(((self.bits >> 26) & 1) != 0)
}
#[doc = "Bit 27 - BOR flag"]
#[inline(always)]
pub fn borrstf(&self) -> BORRSTF_R {
BORRSTF_R::new(((self.bits >> 27) & 1) != 0)
}
#[doc = "Bit 28 - Software reset flag"]
#[inline(always)]
pub fn sftrstf(&self) -> SFTRSTF_R {
SFTRSTF_R::new(((self.bits >> 28) & 1) != 0)
}
#[doc = "Bit 29 - Independent window watchdog reset flag"]
#[inline(always)]
pub fn iwdgrstf(&self) -> IWDGRSTF_R {
IWDGRSTF_R::new(((self.bits >> 29) & 1) != 0)
}
#[doc = "Bit 30 - Window watchdog reset flag"]
#[inline(always)]
pub fn wwdgrstf(&self) -> WWDGRSTF_R {
WWDGRSTF_R::new(((self.bits >> 30) & 1) != 0)
}
#[doc = "Bit 31 - Low-power reset flag"]
#[inline(always)]
pub fn lpwrrstf(&self) -> LPWRRSTF_R {
LPWRRSTF_R::new(((self.bits >> 31) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - LSI oscillator enable"]
#[inline(always)]
#[must_use]
pub fn lsion(&mut self) -> LSION_W<CSR_SPEC, 0> {
LSION_W::new(self)
}
#[doc = "Bit 4 - Internal low-speed oscillator predivided by 128"]
#[inline(always)]
#[must_use]
pub fn lsiprediv(&mut self) -> LSIPREDIV_W<CSR_SPEC, 4> {
LSIPREDIV_W::new(self)
}
#[doc = "Bits 8:11 - SI range after Standby mode"]
#[inline(always)]
#[must_use]
pub fn msisrange(&mut self) -> MSISRANGE_W<CSR_SPEC, 8> {
MSISRANGE_W::new(self)
}
#[doc = "Bit 23 - Remove reset flag"]
#[inline(always)]
#[must_use]
pub fn rmvf(&mut self) -> RMVF_W<CSR_SPEC, 23> {
RMVF_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "CSR\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct CSR_SPEC;
impl crate::RegisterSpec for CSR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`csr::R`](R) reader structure"]
impl crate::Readable for CSR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`csr::W`](W) writer structure"]
impl crate::Writable for CSR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets CSR to value 0x0c00_0600"]
impl crate::Resettable for CSR_SPEC {
const RESET_VALUE: Self::Ux = 0x0c00_0600;
}
|
use log::{debug, info, warn};
use proxy_wasm::traits::{Context, HttpContext};
use proxy_wasm::types::*;
#[no_mangle]
pub fn _start() {
proxy_wasm::set_log_level(LogLevel::Trace);
proxy_wasm::set_http_context(|_, _| -> Box<dyn HttpContext> { Box::new(TestStream) });
}
struct TestStream;
impl Context for TestStream {}
impl HttpContext for TestStream {
fn on_http_request_headers(&mut self, _: usize) -> Action {
if self.get_shared_data("shared_data_key_bad") == (None, None) {
debug!("get of bad key not found");
}
self.set_shared_data("shared_data_key1", Some(b"shared_data_value0"), None)
.unwrap();
self.set_shared_data("shared_data_key1", Some(b"shared_data_value1"), None)
.unwrap();
self.set_shared_data("shared_data_key2", Some(b"shared_data_value2"), None)
.unwrap();
if let (_, Some(cas)) = self.get_shared_data("shared_data_key2") {
match self.set_shared_data(
"shared_data_key2",
Some(b"shared_data_value3"),
Some(cas + 1),
) {
Err(Status::CasMismatch) => info!("set CasMismatch"),
_ => panic!(),
};
}
Action::Continue
}
fn on_log(&mut self) {
if self.get_shared_data("shared_data_key_bad") == (None, None) {
debug!("second get of bad key not found");
}
if let (Some(value), _) = self.get_shared_data("shared_data_key1") {
debug!("get 1 {}", String::from_utf8(value).unwrap());
}
if let (Some(value), _) = self.get_shared_data("shared_data_key2") {
warn!("get 2 {}", String::from_utf8(value).unwrap());
}
}
}
|
trait Monster {
fn attack(&self);
}
struct OrcBerzerker {
strength: int
}
impl Monster for OrcBerzerker {
fn attack(&self) {
println!("The Orc berserker slashes his axe at your head for {:d}.", self.strength)
}
}
struct SkavenPlagueMonk {
strength: int
}
impl Monster for SkavenPlagueMonk {
fn attack(&self) {
println!("The Skaven plague monk stabs you with a poisoned dagger for {:d}.", self.strength)
}
}
fn monster_attack(monsters: &[&Monster]) {
for monster in monsters.iter() {
monster.attack();
}
}
struct GoblinFanatic {
strength: int
}
impl Monster for GoblinFanatic {
fn attack(&self) {
println!("Goblin fanatic hits you with a huge metal ball for {:d}.", self.strength);
}
}
fn main() {
let monster_vector: &[&Monster] = [
&(OrcBerzerker {strength: 25}) as &Monster,
&(SkavenPlagueMonk {strength: 10}) as &Monster,
&(GoblinFanatic {strength: 35}) as &Monster,
];
monster_attack(monster_vector);
} |
#[no_mangle]
pub extern fn physics_single_chain_efjc_thermodynamics_isotensional_asymptotic_legendre_helmholtz_free_energy(number_of_links: u8, link_length: f64, hinge_mass: f64, link_stiffness: f64, force: f64, temperature: f64) -> f64
{
super::helmholtz_free_energy(&number_of_links, &link_length, &hinge_mass, &link_stiffness, &force, &temperature)
}
#[no_mangle]
pub extern fn physics_single_chain_efjc_thermodynamics_isotensional_asymptotic_legendre_helmholtz_free_energy_per_link(link_length: f64, hinge_mass: f64, link_stiffness: f64, force: f64, temperature: f64) -> f64
{
super::helmholtz_free_energy_per_link(&link_length, &hinge_mass, &link_stiffness, &force, &temperature)
}
#[no_mangle]
pub extern fn physics_single_chain_efjc_thermodynamics_isotensional_asymptotic_legendre_relative_helmholtz_free_energy(number_of_links: u8, link_length: f64, link_stiffness: f64, force: f64, temperature: f64) -> f64
{
super::relative_helmholtz_free_energy(&number_of_links, &link_length, &link_stiffness, &force, &temperature)
}
#[no_mangle]
pub extern fn physics_single_chain_efjc_thermodynamics_isotensional_asymptotic_legendre_relative_helmholtz_free_energy_per_link(link_length: f64, link_stiffness: f64, force: f64, temperature: f64) -> f64
{
super::relative_helmholtz_free_energy_per_link(&link_length, &link_stiffness, &force, &temperature)
}
#[no_mangle]
pub extern fn physics_single_chain_efjc_thermodynamics_isotensional_asymptotic_legendre_nondimensional_helmholtz_free_energy(number_of_links: u8, link_length: f64, hinge_mass: f64, nondimensional_link_stiffness: f64, nondimensional_force: f64, temperature: f64) -> f64
{
super::nondimensional_helmholtz_free_energy(&number_of_links, &link_length, &hinge_mass, &nondimensional_link_stiffness, &nondimensional_force, &temperature)
}
#[no_mangle]
pub extern fn physics_single_chain_efjc_thermodynamics_isotensional_asymptotic_legendre_nondimensional_helmholtz_free_energy_per_link(link_length: f64, hinge_mass: f64, nondimensional_link_stiffness: f64, nondimensional_force: f64, temperature: f64) -> f64
{
super::nondimensional_helmholtz_free_energy_per_link(&link_length, &hinge_mass, &nondimensional_link_stiffness, &nondimensional_force, &temperature)
}
#[no_mangle]
pub extern fn physics_single_chain_efjc_thermodynamics_isotensional_asymptotic_legendre_nondimensional_relative_helmholtz_free_energy(number_of_links: u8, nondimensional_link_stiffness: f64, nondimensional_force: f64) -> f64
{
super::nondimensional_relative_helmholtz_free_energy(&number_of_links, &nondimensional_link_stiffness, &nondimensional_force)
}
#[no_mangle]
pub extern fn physics_single_chain_efjc_thermodynamics_isotensional_asymptotic_legendre_nondimensional_relative_helmholtz_free_energy_per_link(nondimensional_link_stiffness: f64, nondimensional_force: f64) -> f64
{
super::nondimensional_relative_helmholtz_free_energy_per_link(&nondimensional_link_stiffness, &nondimensional_force)
} |
use crate::cpu::{ioregister, Cpu, Instruction, Reg};
use crate::mem::{self, Memory};
use crate::peripherals::sound;
use std::io::{self, Write};
use crate::gebemula::GBMode;
struct BreakCommand {
break_addr: Option<u16>,
break_reg: Option<Reg>,
break_ioreg: Option<u16>,
break_reg_value: u16,
break_debug: u8,
is_running: bool,
}
impl Default for BreakCommand {
fn default() -> BreakCommand {
BreakCommand {
break_addr: None,
break_reg: None,
break_ioreg: None,
break_reg_value: 0,
break_debug: 0,
is_running: false,
}
}
}
impl BreakCommand {
// true if should go to read loop;
fn run(&mut self, instruction: &Instruction, cpu: &Cpu, mem: &Memory) -> bool {
let go_to_read_loop: bool;
if let Some(addr) = self.break_addr {
go_to_read_loop = instruction.address == addr;
Debugger::print_cpu_human(self.break_debug, instruction, cpu);
} else if let Some(ioreg) = self.break_ioreg {
go_to_read_loop = mem.read_byte(ioreg) as u16 == self.break_reg_value;
Debugger::print_cpu_human(self.break_debug, instruction, cpu);
} else if let Some(reg) = self.break_reg {
go_to_read_loop = cpu.reg16(reg) == self.break_reg_value;
Debugger::print_cpu_human(self.break_debug, instruction, cpu);
} else {
go_to_read_loop = true;
}
if go_to_read_loop {
self.break_debug = 0b10; //ensure the last instruction is printed
if self.is_running {
Debugger::print_cpu_human(self.break_debug, instruction, cpu);
self.is_running = false;
}
self.break_addr = None;
self.break_reg = None;
self.break_ioreg = None;
self.break_reg_value = 0;
self.break_debug = 0;
}
go_to_read_loop
}
// true if should_run_cpu
fn parse(&mut self, params: &[&str]) -> bool {
if params.is_empty() {
Debugger::display_help("Invalid number of arguments for 'break'\n");
return false;
}
let mut should_run_cpu = false;
let mut has_cpu_human = false;
let mut cpu_human_param_index = 1;
if params.len() == 1 || params[1] == "cpu" || params[1] == "human" {
if let Some(addr) = Debugger::hex_from_str(¶ms[0]) {
self.break_addr = Some(addr);
self.break_reg = None;
self.break_reg_value = 0;
has_cpu_human = params.len() >= 2;
should_run_cpu = true;
cpu_human_param_index = 1;
}
} else {
should_run_cpu = true;
let ioregister = match params[0] {
"LCDC" => Some(ioregister::LCDC_REGISTER_ADDR),
"LYC" => Some(ioregister::LYC_REGISTER_ADDR),
"LY" => Some(ioregister::LY_REGISTER_ADDR),
"SCX" => Some(ioregister::SCX_REGISTER_ADDR),
"SCY" => Some(ioregister::SCY_REGISTER_ADDR),
"WY" => Some(ioregister::WY_REGISTER_ADDR),
"WX" => Some(ioregister::WX_REGISTER_ADDR),
"IF" => Some(ioregister::IF_REGISTER_ADDR),
"IE" => Some(ioregister::IE_REGISTER_ADDR),
"STAT" => Some(ioregister::STAT_REGISTER_ADDR),
"DIV" => Some(ioregister::DIV_REGISTER_ADDR),
"TIMA" => Some(ioregister::TIMA_REGISTER_ADDR),
_ => None,
};
let reg = match params[0] {
"A" => Some(Reg::A),
"F" => Some(Reg::F),
"B" => Some(Reg::B),
"C" => Some(Reg::C),
"D" => Some(Reg::D),
"E" => Some(Reg::E),
"H" => Some(Reg::H),
"L" => Some(Reg::L),
"AF" => Some(Reg::AF),
"BC" => Some(Reg::BC),
"HL" => Some(Reg::HL),
"SP" => Some(Reg::SP),
"PC" => Some(Reg::PC),
_ => None,
};
if ioregister.is_some() {
if let Some(value) = Debugger::hex_from_str(¶ms[1]) {
self.break_addr = None;
self.break_reg = None;
self.break_ioreg = ioregister;
self.break_reg_value = value as u16;
self.break_debug = 0;
cpu_human_param_index = 2;
has_cpu_human = params.len() >= 3;
} else {
should_run_cpu = false;
}
} else if reg.is_some() {
if let Some(value) = Debugger::hex_from_str(¶ms[1]) {
self.break_addr = None;
self.break_reg = reg;
self.break_ioreg = None;
self.break_reg_value = value as u16;
self.break_debug = 0;
cpu_human_param_index = 2;
has_cpu_human = params.len() >= 3;
} else {
should_run_cpu = false;
}
} else {
should_run_cpu = false;
}
if should_run_cpu {
self.is_running = true;
} else {
Debugger::display_help(&format!("Invalid register value: {}", params[1]));
}
}
if has_cpu_human {
if let Some(value) = Debugger::cpu_human_in_params(¶ms[cpu_human_param_index..]) {
self.break_debug = value;
} else {
// user has input some incorret value
self.break_addr = None;
self.break_reg = None;
self.break_ioreg = None;
self.break_reg_value = 0;
self.break_debug = 0;
should_run_cpu = false;
}
}
should_run_cpu
}
}
pub struct Debugger {
should_run_cpu: bool,
run_debug: Option<u8>, // 0b0000_0000 - bit 0: cpu, bit 1: human;
break_command: BreakCommand,
steps_debug: u8, // same as run_debug
num_steps: u32,
display_header: bool,
pub exit: bool,
}
impl Default for Debugger {
fn default() -> Debugger {
Debugger {
should_run_cpu: false,
run_debug: None,
break_command: BreakCommand::default(),
steps_debug: 0b0,
num_steps: 0,
display_header: true,
exit: false,
}
}
}
impl Debugger {
pub fn run(&mut self, instruction: &Instruction, cpu: &Cpu, mem: &Memory) {
if self.display_header {
println!("##################################");
println!("# Gebemula Debug Console #");
println!("##################################");
self.display_info(mem);
println!("Type 'help' for the command list.");
println!("----------------------------------");
self.display_header = false;
}
if self.run_debug.is_some() {
Debugger::print_cpu_human(self.run_debug.unwrap(), instruction, cpu);
return;
}
let mut go_to_loop = self.break_command.run(instruction, cpu, mem);
if go_to_loop && self.num_steps > 0 {
self.num_steps -= 1;
Debugger::print_cpu_human(self.steps_debug, instruction, cpu);
if self.num_steps == 0 && self.steps_debug == 0 {
println!("{}", instruction);
} else {
go_to_loop = false;
}
};
if go_to_loop {
self.read_loop(instruction, cpu, mem);
}
}
pub fn display_info(&self, mem: &Memory) {
println!("GB Type: {:?}", GBMode::get(mem));
println!("Game: {}", mem::cartridge::game_title_str(mem));
let cart_type_id = mem.read_byte(mem::cartridge::CARTRIDGE_TYPE_ADDR);
let (mapper_type, extra_cart_hw) = mem::cartridge::cart_type_from_id(cart_type_id);
let cart_string = mem::cartridge::cartridge_type_string(mapper_type, extra_cart_hw);
println!("Cartridge Type: {}", cart_string);
}
fn read_loop(&mut self, instruction: &Instruction, cpu: &Cpu, mem: &Memory) {
loop {
self.should_run_cpu = false;
print!("gdc> "); //gdc: gebemula debugger console
io::stdout().flush().unwrap();
let mut input = String::new();
match io::stdin().read_line(&mut input) {
Ok(_) => {
input.pop(); //removes the '\n'.
self.parse(&input, instruction, cpu, mem);
}
Err(error) => println!("error: {}", error),
}
if self.should_run_cpu {
break;
}
}
}
fn print_cpu_human(mask: u8, instruction: &Instruction, cpu: &Cpu) {
let debug_cpu = mask & 0b1 == 0b1;
let debug_human = (mask >> 1) & 0b1 == 0b1;
if debug_human {
let v = if debug_cpu { ":\n\t" } else { "\n" };
print!("{}{}", instruction, v);
}
if debug_cpu {
println!("{}", cpu);
}
}
fn parse(&mut self, command: &str, instruction: &Instruction, cpu: &Cpu, mem: &Memory) {
let aux: &mut Vec<&str> = &mut command.trim().split(' ').collect();
let mut words = Vec::new();
for w in aux.iter().filter(|x| *x.to_owned() != "") {
words.push(w.trim());
}
if !words.is_empty() {
match words[0] {
"show" => {
Debugger::parse_show(&words[1..], cpu, mem);
self.should_run_cpu = false;
}
"step" => {
self.parse_step(&words[1..]);
self.should_run_cpu = self.num_steps > 0;
}
"last" => {
println!("{}", instruction);
self.should_run_cpu = false;
}
"break" => {
self.should_run_cpu = self.break_command.parse(&words[1..]);
}
"help" => {
Debugger::display_help("");
}
"run" => {
self.parse_run(&words[1..]);
}
"info" => {
self.display_info(mem);
}
"exit" | "quit" | "e" | "q" => {
self.exit = true;
self.should_run_cpu = true;
}
"" => {
// does nothing
}
_ => {
Debugger::display_help(&format!("Invalid command: {}", words[0]));
}
}
}
}
fn display_help(error_msg: &str) {
if error_msg != "" {
println!("***ERROR: {}", error_msg);
}
println!(
"- show [cpu|ioregs|memory [<min_addr_hex> <max_addr_hex>]\n\tShow state \
of component."
);
println!(
"- step [decimal] [cpu|human]\n\tRun instruction pointed by PC and print \
it.\n\tIf a number is set, run step num times and print the last one.\n\tIf a \
number is set and cpu or human or both, then it will print all the \
instructions until the n'th instruction."
);
println!("- last\n\tPrint last instruction.");
println!(
"- break [<0xaddr>|<reg> <0xvalue>] [cpu|human]\n\tBreak when addr is hit or \
reg has value.\n\tIf cpu, human or both are set, every instruction until the \
break point will be displayed.\n\tAvailable regs: \
A,F,B,C,D,E,H,L,AF,BC,DE,HL,SP,PC\n\tAvailable ioregs: \
LY,LYC,IF,IE,STAT,LCDC,SCX,SCY,WX,WY,DIV,TIMA"
);
println!(
"- run [cpu|human]\n\tDisable the debugger and run the code.\n\tIf set, \
information about cpu state or instruction (human friendly) or both will be \
printed."
);
println!("- info\n\tDisplay information about the game rom.");
println!("- help\n\tShow this.");
println!(
"Tip: when running 'run', 'step' or 'break' press 'Q' to stop it and go back to \
the debugger."
);
}
fn parse_step(&mut self, parameters: &[&str]) {
if parameters.is_empty() {
self.num_steps = 1;
} else if parameters.len() >= 1 {
if let Ok(s) = parameters[0].parse::<u32>() {
self.num_steps = s;
} else {
Debugger::display_help("Couldn't parse number of steps.");
self.num_steps = 0;
return;
}
if let Some(value) = Debugger::cpu_human_in_params(¶meters[1..]) {
self.steps_debug = value;
}
} else {
Debugger::display_help("Too many parameters for the command `step`.");
}
}
pub fn cancel_run(&mut self) {
self.run_debug = None;
self.should_run_cpu = false;
self.steps_debug = 0b0;
self.num_steps = 0;
self.break_command = BreakCommand::default();
}
fn parse_run(&mut self, parameters: &[&str]) {
if parameters.is_empty() {
self.run_debug = Some(0);
self.should_run_cpu = true;
} else if parameters.len() > 2 {
Debugger::display_help("Invalid number of parameters for run.");
} else if let Some(value) = Debugger::cpu_human_in_params(¶meters) {
self.run_debug = Some(value);
self.should_run_cpu = true;
}
}
fn cpu_human_in_params(params: &[&str]) -> Option<u8> {
let mut cpu = false;
let mut human = false;
for param in params {
match *param {
"cpu" => {
cpu = true;
}
"human" => {
human = true;
}
_ => {
Debugger::display_help(&format!(
"Invalid parameter for cpu|human: {}\n",
param
));
return None;
}
}
}
let mut res = 0;
if cpu || human {
res = if human { 0b10 } else { 0b00 };
res = if cpu { res | 0b01 } else { res };
}
Some(res)
}
fn parse_show(parameters: &[&str], cpu: &Cpu, mem: &Memory) {
if parameters.is_empty() {
Debugger::display_help("Invalid number of parameters for 'show'.");
return;
}
match parameters[0] {
"cpu" => {
println!("{}", cpu);
}
"ioregs" => {
let tima = mem.read_byte(ioregister::TIMA_REGISTER_ADDR);
let tma = mem.read_byte(ioregister::TMA_REGISTER_ADDR);
let tac = mem.read_byte(ioregister::TAC_REGISTER_ADDR);
let div = mem.read_byte(ioregister::DIV_REGISTER_ADDR);
let if_ = mem.read_byte(ioregister::IF_REGISTER_ADDR);
let ie = mem.read_byte(ioregister::IE_REGISTER_ADDR);
let ly = mem.read_byte(ioregister::LY_REGISTER_ADDR);
let lcdc = mem.read_byte(ioregister::LCDC_REGISTER_ADDR);
let scx = mem.read_byte(ioregister::SCX_REGISTER_ADDR);
let scy = mem.read_byte(ioregister::SCY_REGISTER_ADDR);
let stat = mem.read_byte(ioregister::STAT_REGISTER_ADDR);
let lyc = mem.read_byte(ioregister::LYC_REGISTER_ADDR);
let wx = mem.read_byte(ioregister::WX_REGISTER_ADDR);
let wy = mem.read_byte(ioregister::WY_REGISTER_ADDR);
let p1 = mem.read_byte(ioregister::JOYPAD_REGISTER_ADDR);
let nr10 = mem.read_byte(sound::NR10_REGISTER_ADDR);
let nr11 = mem.read_byte(sound::NR11_REGISTER_ADDR);
let nr12 = mem.read_byte(sound::NR12_REGISTER_ADDR);
let nr13 = mem.read_byte(sound::NR13_REGISTER_ADDR);
let nr14 = mem.read_byte(sound::NR14_REGISTER_ADDR);
let nr21 = mem.read_byte(sound::NR21_REGISTER_ADDR);
let nr22 = mem.read_byte(sound::NR22_REGISTER_ADDR);
let nr23 = mem.read_byte(sound::NR23_REGISTER_ADDR);
let nr24 = mem.read_byte(sound::NR24_REGISTER_ADDR);
let nr30 = mem.read_byte(sound::NR30_REGISTER_ADDR);
let nr31 = mem.read_byte(sound::NR31_REGISTER_ADDR);
let nr32 = mem.read_byte(sound::NR32_REGISTER_ADDR);
let nr33 = mem.read_byte(sound::NR33_REGISTER_ADDR);
let nr34 = mem.read_byte(sound::NR34_REGISTER_ADDR);
let nr50 = mem.read_byte(sound::NR50_REGISTER_ADDR);
let nr51 = mem.read_byte(sound::NR51_REGISTER_ADDR);
let nr52 = mem.read_byte(sound::NR52_REGISTER_ADDR);
println!("IF: {:#b}", if_);
println!("IE: {:#b}", ie);
println!("DIV: {:#x}", div);
println!("LY: {:#x} {}", ly, ly);
println!("LYC: {:#x} {}", lyc, lyc);
println!("LCDC: {:#x} {:#b}", lcdc, lcdc);
println!("STAT: {:#x} {:#b}", stat, stat);
println!("TIMA: {:#x}", tima);
println!("TMA: {:#x}", tma);
println!("TAC: {:#b}", tac);
println!("SCX: {}", scx);
println!("SCY: {}", scy);
println!("WX: {}", wx);
println!("WY: {}", wy);
println!("Joypad: {:#b}", p1);
println!("###############");
println!("Sound Registers");
println!("###############");
println!("NR10: {:#b}", nr10);
println!("NR11: {:#b}", nr11);
println!("NR12: {:#b}", nr12);
println!("NR13: {:#b}", nr13);
println!("NR14: {:#b}", nr14);
println!("###############");
println!("NR21: {:#b}", nr21);
println!("NR22: {:#b}", nr22);
println!("NR23: {:#b}", nr23);
println!("NR24: {:#b}", nr24);
println!("###############");
println!("NR30: {:#b}", nr30);
println!("NR31: {:#b}", nr31);
println!("NR32: {:#b}", nr32);
println!("NR33: {:#b}", nr33);
println!("NR34: {:#b}", nr34);
println!("###############");
println!("NR50: {:#b}", nr50);
println!("NR51: {:#b}", nr51);
println!("NR52: {:#b}", nr52);
}
"memory" => {
Debugger::parse_show_memory(¶meters[1..], mem);
}
_ => {
Debugger::display_help(&format!(
"Invalid parameter for 'show': {}\n",
parameters[0]
));
}
}
}
fn parse_show_memory(parameters: &[&str], mem: &Memory) {
if parameters.len() == 2 {
let min_addr = Debugger::hex_from_str(parameters[0]);
let max_addr = Debugger::hex_from_str(parameters[1]);
if min_addr.is_some() && max_addr.is_some() {
println!("{}", mem.format(min_addr, max_addr));
}
} else {
Debugger::display_help("Invalid number of arguments for 'show memory'\n");
}
}
fn hex_from_str(mut str_hex: &str) -> Option<u16> {
if str_hex.len() > 2 && str_hex[..2].to_owned() == "0x" {
str_hex = &str_hex[2..];
}
match u16::from_str_radix(str_hex, 16) {
Ok(value) => Some(value),
Err(value) => {
Debugger::display_help(&format!("Address is not a valid hex number: {}\n", value));
None
}
}
}
}
pub fn instr_to_human(instruction: &Instruction) -> String {
if let Some(_) = instruction.prefix {
// CB-prefixed instructions
let reg = Reg::pair_from_ddd(instruction.opcode);
let mut r = format!("{:?}", reg);
if reg == Reg::HL {
r = "(HL)".to_owned();
}
let bit = instruction.opcode >> 3 & 0b111;
match instruction.opcode {
0x00..=0x07 => format!("rlc {}", r),
0x08..=0x0F => format!("rrc {}", r),
0x10..=0x17 => {
// RL m
format!("rl {}", r)
}
0x18..=0x1F => {
// RR m
format!("rr {}", r)
}
0x20..=0x27 => format!("sla {}", r),
0x28..=0x2F => {
// SRA n
format!("sra {}", r)
}
0x30..=0x37 => {
// SWAP n
format!("swap {}", r)
}
0x38..=0x3F => {
// SRL n
format!("srl {}", r)
}
0x40..=0x7F => {
// BIT b,r; BIT b,(HL)
format!("bit {},{}", bit, r)
}
0x80..=0xBF => {
// RES b,r; RES b,(HL)
format!("res {},{}", bit, r)
}
0xC0..=0xFF => {
// SET b,r; SET b,(HL)
format!("set {},{}", bit, r)
}
_ => unreachable!(),
}
} else {
match instruction.opcode {
/***************************************/
/* Misc/Control instructions */
/***************************************/
0x0 => {
//NOP
"nop".to_owned()
}
0x10 => {
//STOP
"stop".to_owned()
}
0x76 => {
//HALT
"halt".to_owned()
}
0xF3 => {
//DI
"di".to_owned()
}
0xFB => {
//EI
"ei".to_owned()
}
/**************************************/
/* 8 bit rotations/shifts */
/**************************************/
0x07 => "RLCA".to_owned(),
0x17 => "RLA".to_owned(),
0x0F => "RRCA".to_owned(),
0x1F => "RRA".to_owned(),
/**************************************/
/* 8 bit load/store/move instructions */
/**************************************/
0x02 | 0x12 => {
//LD (rr),A;
let reg = Reg::pair_from_dd(instruction.opcode >> 4);
format!("ld ({:?}),A", reg)
}
0x22 => {
//LD (HL+),A
"ld (HL+),A".to_owned()
}
0x32 => {
//LD (HL-),A
"ld (HL-),A".to_owned()
}
0x0A | 0x1A => {
//LD A,(rr);
let reg = Reg::pair_from_dd(instruction.opcode >> 4);
format!("ld ({:?}),A", reg)
}
0x2A => {
//LD A,(HL+);
"ld A,(HL+)".to_owned()
}
0x3A => {
//LD A,(HL-)
"ld A,(HL-)".to_owned()
}
0x06 | 0x16 | 0x26 | 0x0E | 0x1E | 0x2E | 0x3E | 0x36 => {
//LD r,n; LD (HL),n
let reg = Reg::pair_from_ddd(instruction.opcode >> 3);
let mut r = format!("{:?}", reg);
if reg == Reg::HL {
r = "(HL)".to_owned();
}
format!("ld {},{:#x}", r, instruction.imm8.unwrap())
}
0x40..=0x6F | 0x70..=0x75 | 0x77..=0x7F => {
//LD r,r; LD r,(HL); LD (HL),r
let reg_rhs = Reg::pair_from_ddd(instruction.opcode);
let reg_lhs = Reg::pair_from_ddd(instruction.opcode >> 3);
let r: String;
let l: String;
if reg_rhs == Reg::HL {
r = "(HL)".to_owned();
} else {
r = format!("{:?}", reg_rhs);
}
if reg_lhs == Reg::HL {
l = "(HL)".to_owned();
} else {
l = format!("{:?}", reg_lhs);
}
format!("ld {},{}", l, r)
}
0xE0 => {
//LDH (n),A
format!("ldh ({:#x}),A", instruction.imm8.unwrap())
}
0xF0 => {
//LDH A,(n)
format!("ldh A,({:#x})", instruction.imm8.unwrap())
}
0xE2 => {
//LD (C),A
"ld (0xff00+C), A".to_owned()
}
0xF2 => {
//LD A,(C)
"ld A,(0xff00+C)".to_owned()
}
0xEA => {
//LD (nn),A
format!("ld ({:#x}),A", instruction.imm16.unwrap())
}
0xFA => {
//LD A,(nn)
format!("ld A,({:#x})", instruction.imm16.unwrap())
}
/***************************************/
/* 16 bit load/store/move instructions */
/***************************************/
0x01 | 0x11 | 0x21 | 0x31 => {
//LD rr,nn
let reg = Reg::pair_from_dd(instruction.opcode >> 4);
format!("ld {:?},{:#x}", reg, instruction.imm16.unwrap())
}
0x08 => {
//LD (nn), SP
format!("ld ({:#x}),SP", instruction.imm16.unwrap())
}
0xC1 | 0xD1 | 0xE1 | 0xF1 => {
//POP rr
let mut reg = Reg::pair_from_dd(instruction.opcode >> 4);
if reg == Reg::SP {
reg = Reg::AF;
}
format!("pop {:?}", reg)
}
0xC5 | 0xD5 | 0xE5 | 0xF5 => {
//PUSH rr
let mut reg = Reg::pair_from_dd(instruction.opcode >> 4);
if reg == Reg::SP {
reg = Reg::AF;
}
format!("push {:?}", reg)
}
0xF8 => {
//LD HL,SP+n
format!("ld HL,SP+{:#x}", instruction.imm8.unwrap())
}
0xF9 => {
//LD SP,HL
"ld SP,HL".to_owned()
}
/*****************************************/
/* 8 bit arithmetic/logical instructions */
/*****************************************/
0x80..=0x87 => {
let reg = Reg::pair_from_ddd(instruction.opcode);
let mut v = format!("{:?}", reg);
if reg == Reg::HL {
v = "(HL)".to_owned()
}
format!("add A,{}", v)
}
0x88..=0x8F => {
let reg = Reg::pair_from_ddd(instruction.opcode);
let mut v = format!("{:?}", reg);
if reg == Reg::HL {
v = "(HL)".to_owned()
}
format!("adc A,{}", v)
}
0x90..=0x97 => {
let reg = Reg::pair_from_ddd(instruction.opcode);
let mut v = format!("{:?}", reg);
if reg == Reg::HL {
v = "(HL)".to_owned()
}
format!("sub {}", v)
}
0x98..=0x9F => {
let reg = Reg::pair_from_ddd(instruction.opcode);
let mut v = format!("{:?}", reg);
if reg == Reg::HL {
v = "(HL)".to_owned()
}
format!("sbc A,{}", v)
}
0xA0..=0xA7 => {
let reg = Reg::pair_from_ddd(instruction.opcode);
let mut v = format!("{:?}", reg);
if reg == Reg::HL {
v = "(HL)".to_owned()
}
format!("and {}", v)
}
0xA8..=0xAF => {
let reg = Reg::pair_from_ddd(instruction.opcode);
let mut v = format!("{:?}", reg);
if reg == Reg::HL {
v = "(HL)".to_owned()
}
format!("xor {}", v)
}
0xB0..=0xB7 => {
let reg = Reg::pair_from_ddd(instruction.opcode);
let mut v = format!("{:?}", reg);
if reg == Reg::HL {
v = "(HL)".to_owned()
}
format!("or {}", v)
}
0xB8..=0xBF => {
let reg = Reg::pair_from_ddd(instruction.opcode);
let mut v = format!("{:?}", reg);
if reg == Reg::HL {
v = "(HL)".to_owned()
}
format!("cp {}", v)
}
0xC6 => format!("add A,{:#x}", instruction.imm8.unwrap()),
0xD6 => format!("sub {:#x}", instruction.imm8.unwrap()),
0xE6 => format!("and {:#x}", instruction.imm8.unwrap()),
0xF6 => format!("or {:#x}", instruction.imm8.unwrap()),
0xCE => format!("adc A,{:#x}", instruction.imm8.unwrap()),
0xDE => format!("sbc A,{:#x}", instruction.imm8.unwrap()),
0xEE => format!("xor {:#x}", instruction.imm8.unwrap()),
0xFE => format!("cp {:#x}", instruction.imm8.unwrap()),
0x04 | 0x14 | 0x24 | 0x34 | 0x0C | 0x1C | 0x2C | 0x3C => {
//INC r; INC (HL)
let reg = Reg::pair_from_ddd(instruction.opcode >> 3);
let mut v = format!("{:?}", reg);
if reg == Reg::HL {
v = "(HL)".to_owned()
}
format!("inc {}", v)
}
0x05 | 0x15 | 0x25 | 0x35 | 0x0D | 0x1D | 0x2D | 0x3D => {
//DEC r; DEC (HL)
let reg = Reg::pair_from_ddd(instruction.opcode >> 3);
let mut v = format!("{:?}", reg);
if reg == Reg::HL {
v = "(HL)".to_owned();
}
format!("dec {}", v)
}
0x27 => "DAA".to_owned(),
0x37 => "SCF".to_owned(),
0x2F => "CPL".to_owned(),
0x3F => "CCF".to_owned(),
/******************************************/
/* 16 bit arithmetic/logical instructions */
/******************************************/
0x03 | 0x13 | 0x23 | 0x33 => {
//INC rr
let reg = Reg::pair_from_dd(instruction.opcode >> 4);
format!("inc {:?}", reg)
}
0x0B | 0x1B | 0x2B | 0x3B => {
//DEC rr
let reg = Reg::pair_from_dd(instruction.opcode >> 4);
format!("dec {:?}", reg)
}
0x09 | 0x19 | 0x29 | 0x39 => {
//ADD HL,rr
let reg = Reg::pair_from_dd(instruction.opcode >> 4);
format!("add HL,{:?}", reg)
}
0xE8 => {
//ADD SP,n
format!("add SP,{:#x}", instruction.imm8.unwrap())
}
/*****************************************/
/* Jumps/Calls */
/*****************************************/
0x18 => {
//JR n
format!("jr {:#x}", instruction.imm8.unwrap())
}
0x20 => {
//JR NZ,r8
format!("jr nz {:#x}", instruction.imm8.unwrap())
}
0x28 => {
//JR Z,r8
format!("jr z {:#x}", instruction.imm8.unwrap())
}
0x30 => {
//JR NC,r8
format!("jr nc {:#x}", instruction.imm8.unwrap())
}
0x38 => {
//JR C,r8
format!("jr c {:#x}", instruction.imm8.unwrap())
}
0xC3 => {
//JP nn
format!("jp {:#x}", instruction.imm16.unwrap())
}
0xC2 => format!("jp nz {:#x}", instruction.imm16.unwrap()),
0xCA => format!("jp z {:#x}", instruction.imm16.unwrap()),
0xD2 => format!("jp nc {:#x}", instruction.imm16.unwrap()),
0xDA => format!("jp c {:#x}", instruction.imm16.unwrap()),
0xE9 => "jp (HL)".to_owned(),
0xC0 => "ret nz".to_owned(),
0xC8 => "ret z".to_owned(),
0xC9 => "ret".to_owned(),
0xD0 => "ret nc".to_owned(),
0xD8 => "ret c".to_owned(),
0xD9 => "reti".to_owned(),
0xC4 => format!("call nz,{:#x}", instruction.imm16.unwrap()),
0xCC => format!("call z,{:#x}", instruction.imm16.unwrap()),
0xCD => format!("call {:#x}", instruction.imm16.unwrap()),
0xD4 => format!("call nc,{:#x}", instruction.imm16.unwrap()),
0xDC => format!("call c,{:#x}", instruction.imm16.unwrap()),
0xC7 | 0xCF | 0xD7 | 0xDF | 0xE7 | 0xEF | 0xF7 | 0xFF => {
//RST
"rst".to_owned()
}
_ => panic!("Unknown instruction: {:#x}", instruction.opcode),
}
}
}
|
// Opcodes are fundamental operations to the CPU, LC-3 only has 16 opcodes.
// Each instruction is 16 bits long, with first 4 bits storing the Opcode,
// the rest is reserved for the parameter.
use super::vm::VM;
use std::io;
use std::io::Read;
use std::io::Write;
use std::process;
#[derive(Debug)]
pub enum OpCode {
BR = 0, // branch
ADD, // add
LD, // load
ST, // store
JSR, // jump register
AND, // bitwise and
LDR, // load register
STR, // store register
RTI, // unused
NOT, // bitwise not
LDI, // load indirect
STI, // store indirect
JMP, // jump
RES, // reserved (unused)
LEA, // load effective address
TRAP, // execute trap
}
// TRAP Codes
pub enum TrapCode {
/// get character from keyboard
Getc = 0x20,
/// output a character
Out = 0x21,
/// output a word string
Puts = 0x22,
/// input a string
In = 0x23,
/// output a byte string
Putsp = 0x24,
/// halt the program
Halt = 0x25,
}
pub fn execute_instruction(instr: u16, vm: &mut VM) {
// Extract OPCode from the instruction
let op_code = get_op_code(&instr);
// Match OPCode and execute instruction
match op_code {
Some(OpCode::ADD) => add(instr, vm),
Some(OpCode::AND) => and(instr, vm),
Some(OpCode::NOT) => not(instr, vm),
Some(OpCode::BR) => br(instr, vm),
Some(OpCode::JMP) => jmp(instr, vm),
Some(OpCode::JSR) => jsr(instr, vm),
Some(OpCode::LD) => ld(instr, vm),
Some(OpCode::LDI) => ldi(instr, vm),
Some(OpCode::LDR) => ldr(instr, vm),
Some(OpCode::LEA) => lea(instr, vm),
Some(OpCode::ST) => st(instr, vm),
Some(OpCode::STI) => sti(instr, vm),
Some(OpCode::STR) => str(instr, vm),
Some(OpCode::TRAP) => trap(instr, vm),
_ => {}
}
}
// Each instruction is 16 bits long, with the left 4 bits storing the opcode.
// The rest of the bits are used to store the parameters.
// To extract left 4 bits out of the instruction, we'll use a right bit shift `>>`
// operator and shift to the right the first 4 bits 12 positions.
pub fn get_op_code(instruction: &u16) -> Option<OpCode> {
match instruction >> 12 {
0 => Some(OpCode::BR),
1 => Some(OpCode::ADD),
2 => Some(OpCode::LD),
3 => Some(OpCode::ST),
4 => Some(OpCode::JSR),
5 => Some(OpCode::AND),
6 => Some(OpCode::LDR),
7 => Some(OpCode::STR),
8 => Some(OpCode::RTI),
9 => Some(OpCode::NOT),
10 => Some(OpCode::LDI),
11 => Some(OpCode::STI),
12 => Some(OpCode::JMP),
13 => Some(OpCode::RES),
14 => Some(OpCode::LEA),
15 => Some(OpCode::TRAP),
_ => None,
}
}
/// ADD takes two values and stores them in a register.
/// In register mode, the second value to add is found in a register.
/// In immediate mode, the second value is embedded in the right-most 5 bits of the instruction.
/// Values which are shorter than 16 bits need to be sign extended.
/// Any time an instruction modifies a register, the condition flags need to be updated
/// If bit [5] is 0, the second source operand is obtained from SR2.
/// If bit [5] is 1, the second source operand is obtained by sign-extending the imm5 field to 16 bits.
/// In both cases, the second source operand is added to the contents of SR1 and the result stored in DR.
/// The condition codes are set, based on whether the result is negative, zero, or positive.
/// Encoding:
///
/// 15 12 │11 9│8 6│ 5 │4 3│2 0
/// ┌───────────────┼───────────┼───────────┼───┼───────┼───────────┐
/// │ 0001 │ DR │ SR1 │ 0 │ 00 │ SR2 │
/// └───────────────┴───────────┴───────────┴───┴───────┴───────────┘
///
/// 15 12│11 9│8 6│ 5 │4 0
/// ┌───────────────┼───────────┼───────────┼───┼───────────────────┐
/// │ 0001 │ DR │ SR1 │ 1 │ IMM5 │
/// └───────────────┴───────────┴───────────┴───┴───────────────────┘
pub fn add(instruction: u16, vm: &mut VM) {
// Get destination address using bitwise operation tricks.
// `instruction >> 9` will shift the binary from instruction it 9 times to the right
// That means the last bit will be the end of the DR portion of the instruction
// And the bitwise-and (`&`) `0x7` will grab only the length of `111` out of the
// instruction, i.e the last 3 bits, which is exactly the length of the DR.
let dr = (instruction >> 9) & 0x7;
// First operand -- Same things as described above, but we move only 6 times to grab the sr1.
let sr1 = (instruction >> 6) & 0x7;
// Check if we're in immediate mode or register mode. Grab just the imm_flag portion of the
// instruction
let imm_flag = (instruction >> 5) & 0x1;
if imm_flag == 1 {
let imm5 = sign_extend(instruction & 0x1F, 5);
// This is declared as u32 to prevent from overflow.
let val: u32 = imm5 as u32 + vm.registers.get(sr1) as u32;
// Set the result of the sum to the target register
vm.registers.update(dr, val as u16);
} else {
// If not immediate mode, we need to extract the second register.
let sr2 = instruction & 0x7;
// Proceed as usual
let val: u32 = vm.registers.get(sr1) as u32 + vm.registers.get(sr2) as u32;
// Set the result of the sum to the target register
vm.registers.update(dr, val as u16);
}
// Update the cond register. We pass `dr` here because this is the register that
// has the result of the last operation. Remember that the cond register's idea
// is to set positive/negative/zero based on the result of the last operation,
// which in this case live in `dr`.
vm.registers.update_r_cond_register(dr);
}
/// Load indirect
/// An address is computed by sign-extending bits [8:0] to 16 bits and adding this
/// value to the incremented PC. What is stored in memory at this address is the address
/// of the data to be loaded into DR. The condition codes are set, based on whether the
// value loaded is negative, zero, or positive.
///
/// Encoding:
///
/// 15 12 11 9 8 0
/// ┌───────────────┬───────────┬───────────────────────────────────┐
/// │ 1010 │ DR │ PCOffset9 │
/// └───────────────┴───────────┴───────────────────────────────────┘
pub fn ldi(instruction: u16, vm: &mut VM) {
// Get the direct register encoded in the instruction (see `add` fn for more in-depth details)
let dr = (instruction >> 9) & 0x7;
// Get the PC offset and sign extend it to be 16 bits
let pc_offset = sign_extend(instruction & 0x1ff, 9);
// This sum is an address to a location in memory, and that address contains
// another value which is the address of the value to load. That's why it's called "indirect".
let first_read = vm.read_memory(vm.registers.pc + pc_offset);
// Read the resulting address and update the DR.
let resulting_address = vm.read_memory(first_read);
vm.registers.update(dr, resulting_address);
vm.registers.update_r_cond_register(dr);
}
/// Your good old logical `and` function. Two operation modes, immediate or passing a register.
///
/// 15 12 │11 9│8 6│ 5 │4 3│2 0
/// ┌───────────────┼───────────┼───────────┼───┼───────┼───────────┐
/// │ 0101 │ DR │ SR1 │ 0 │ 00 │ SR2 │
/// └───────────────┴───────────┴───────────┴───┴───────┴───────────┘
/// 15 12│11 9│8 6│ 5 │4 0
/// ┌───────────────┼───────────┼───────────┼───┼───────────────────┐
/// │ 0101 │ DR │ SR1 │ 1 │ IMM5 │
/// └───────────────┴───────────┴───────────┴───┴───────────────────┘
pub fn and(instruction: u16, vm: &mut VM) {
// Get the direct register encoded in the instruction (see `add` fn for more in-depth details)
let dr = (instruction >> 9) & 0x7;
// As seen in `add` fn, same tricks.
let sr1 = (instruction >> 6) & 0x7;
let imm_flag = (instruction >> 5) & 0x1;
if imm_flag == 1 {
let imm5 = sign_extend(instruction & 0x1F, 5);
// Perform the bitwise and (`&`) and store its value in the DR.
vm.registers.update(dr, vm.registers.get(sr1) & imm5);
} else {
let sr2 = instruction & 0x7;
// Perform the bitwise and (`&`) and store its value in the DR.
vm.registers
.update(dr, vm.registers.get(sr1) & vm.registers.get(sr2));
}
vm.registers.update_r_cond_register(dr);
}
/// Simple binary negation.
/// 15 12 │11 9│8 6│ 5 │4 0
/// ┌───────────────┼───────────┼───────────┼───┼───────────────────┐
/// │ 1001 │ DR │ SR │ 1 │ 1111 │
/// └───────────────┴───────────┴───────────┴───┴───────────────────┘
pub fn not(instruction: u16, vm: &mut VM) {
// Get the direct register encoded in the instruction (see `add` fn for more in-depth details)
let dr = (instruction >> 9) & 0x7;
let sr1 = (instruction >> 6) & 0x7;
vm.registers.update(dr, !vm.registers.get(sr1));
vm.registers.update_r_cond_register(dr);
}
/// The branching operation; means to go somewhere else in the assembly code
/// depending on whether some conditions are met.
/// The condition codes specified by the state of bits [11:9] are tested.
/// If bit [11] is set, N is tested; if bit [11] is clear, N is not tested.
/// If bit [10] is set, Z is tested. If any of the condition codes tested is set,
/// the program branches to the location specified by
/// adding the sign-extended PCOffset9 field to the incremented PC.
///
/// 15 12 │11 │10 │ 9 │8 0
/// ┌───────────────┼───┼───┼───┼───────────────────────────────────┐
/// │ 0000 │ N │ Z │ P │ PCOffset9 │
/// └───────────────┴───┴───┴───┴───────────────────────────────────┘
pub fn br(instruction: u16, vm: &mut VM) {
// Grab the PCOffset of the instruction and sign extend it
// You can read more sign extension inside the `sign_extend` fn.
let pc_offset = sign_extend((instruction) & 0x1ff, 9);
// Shift 9 and grab 3 bits (& 0x7 is doing that)
// You can read more about this trick inside `lea` fn.
let cond_flag = (instruction >> 9) & 0x7;
// so we're taking the `001`, xor `010`, xor `100` that's stored in the condition register
// and `&`ing it to the `001`, or `010`, or `100` coming from the instruction,
// note that it can be `110`, `111` or any combination.
if cond_flag & vm.registers.cond != 0 {
let val: u32 = vm.registers.pc as u32 + pc_offset as u32;
vm.registers.pc = val as u16;
}
// If the branch isn't taken (no condition met), PC isn't changed
// and PC will just point to the next sequential instruction.
}
/// The program unconditionally jumps to the location specified by the contents of the base register.
/// Bits [8:6] identify the base register. `RET` is listed as a separate instruction
/// in the specification, since it is a different keyword in assembly.
/// However, it is actually a special case of JMP. RET happens whenever R1 is 7.
///
/// 15 12│11 9│8 6│ 5 0
/// ┌───────────────┼───────────┼───────────┼───────────────────────┐
/// │ 1100 │ 000 │ BaseR │ 00000 │
/// └───────────────┴───────────┴───────────┴───────────────────────┘
/// 15 12│11 9│8 6│ 5 0
/// ┌───────────────┼───────────┼───────────┼───────────────────────┐
/// │ 1100 │ 000 │ 111 │ 00000 │
/// └───────────────┴───────────┴───────────┴───────────────────────┘
pub fn jmp(instruction: u16, vm: &mut VM) {
// base_reg will either be an arbitrary register or the register 7 (`111`) which in this
// case it would be the `RET` operation.
let base_reg = (instruction >> 6) & 0x7;
vm.registers.pc = vm.registers.get(base_reg);
}
/// First, the incremented PC is saved in R7.
/// This is the linkage back to the calling routine.
/// Then the PC is loaded with the address of the first instruction of the subroutine,
/// causing an unconditional jump to that address.
/// The address of the subroutine is obtained from the base register (if bit [11] is 0),
/// or the address is computed by sign-extending bits [10:0] and adding this value to the incremented PC (if bit [11] is 1).
/// 15 12│11 │10
/// ┌───────────────┼───┼───────────────────────────────────────────┐
/// │ 0100 │ 1 │ PCOffset11 │
/// └───────────────┴───┴───────────────────────────────────────────┘
/// 15 12│11 │10 9│8 6│5 0
/// ┌───────────────┼───┼───────┼───────┼───────────────────────────┐
/// │ 0100 │ 0 │ 00 │ BaseR │ 00000 │
/// └───────────────┴───┴───────┴───────┴───────────────────────────┘
pub fn jsr(instruction: u16, vm: &mut VM) {
// Grab the base register
let base_reg = (instruction >> 6) & 0x7;
// 0x7ff == 11111111111 (11 ones, exactly the length of PCOffset11)
// Grab it and extend it to 16 bits.
let long_pc_offset = sign_extend(instruction & 0x7ff, 11);
// Grab the flag bit at [11] and test it
let long_flag = (instruction >> 11) & 1;
// Save the incremented PC in R7
vm.registers.r7 = vm.registers.pc;
if long_flag != 0 {
// JSR case, the address to jump is computed from PCOffset11
let val: u32 = vm.registers.pc as u32 + long_pc_offset as u32;
vm.registers.pc = val as u16;
} else {
// JSRR case, address to jump to lives in the base register
vm.registers.pc = vm.registers.get(base_reg);
}
}
/// An address is computed by sign-extending bits [8:0] to 16 bits and
/// adding this value to the incremented PC.
/// The contents of memory at this address are loaded into DR.
/// The condition codes are set, based on whether the value loaded is negative, zero, or positive.
///
/// 15 12│11 9│8 0
/// ┌───────────────┼───────────┼───────────────────────────────────┐
/// │ 0010 │ DR │ PCOffset9 │
/// └───────────────┴───────────┴───────────────────────────────────┘
pub fn ld(instruction: u16, vm: &mut VM) {
// Get the direct register encoded in the instruction (see `add` fn for more in-depth details)
let dr = (instruction >> 9) & 0x7;
// Grab the PCOffset and sign extend it
let pc_offset = sign_extend(instruction & 0x1ff, 9);
let mem: u32 = pc_offset as u32 + vm.registers.pc as u32;
// Read the value from the place where the memory above was computed
let value = vm.read_memory(mem as u16);
// Save that value to the direct register and update the condition register
vm.registers.update(dr, value);
vm.registers.update_r_cond_register(dr);
}
/// Load base + offset
/// An address is computed by sign-extending bits [5:0] to 16 bits
/// and adding this value to the contents of the register specified by bits [8:6].
/// The contents of memory at this address are loaded into DR.
/// The condition codes are set, based on whether the value loaded is negative, zero, or positive.
///
/// 15 12│11 9│8 6│5 0
/// ┌───────────────┼───────────┼───────────────┼───────────────────┐
/// │ 1010 │ DR │ BaseR │ PCOffset6 │
/// └───────────────┴───────────┴───────────────┴───────────────────┘
pub fn ldr(instruction: u16, vm: &mut VM) {
// Get the direct register encoded in the instruction (see `add` fn for more in-depth details)
let dr = (instruction >> 9) & 0x7;
// Grab the base register
let base_reg = (instruction >> 6) & 0x7;
// Grab the offset6 and sign extend it
let offset = sign_extend(instruction & 0x3F, 6);
// Compute the memory location to be loaded
let val: u32 = vm.registers.get(base_reg) as u32 + offset as u32;
// Read the value at that memory location
let mem_value = vm.read_memory(val as u16).clone();
// Update the register with the loaded value and update the condition register
vm.registers.update(dr, mem_value);
vm.registers.update_r_cond_register(dr);
}
/// An address is computed by sign-extending bits [8:0] to 16 bits and adding
/// this value to the incremented PC.
/// This address is loaded into DR. The condition codes are set, based on whether the
/// value loaded is negative, zero, or positive.
///
/// 15 12│11 9│8 0
/// ┌───────────────┼───────────┼───────────────────────────────────┐
/// │ 1110 │ DR │ PCOffset9 │
/// └───────────────┴───────────┴───────────────────────────────────┘
pub fn lea(instruction: u16, vm: &mut VM) {
// This (instruction >> 9) & 0x7 is trying to say: shift it so that the last three bits
// are the direct register we're looking for, mask it with 0x7 (`0b0000000000000111`) so that
// we clear _everything_ up to the last three bits, which is what we want.
// The resulting 16 bits value will be _exactly_ the direct register!
let dr = (instruction >> 9) & 0x7;
// 0x1ff is `111111111`, 9 consecutive ones.
let pc_offset = sign_extend(instruction & 0x1ff, 9);
// Value that we want to store in the register (`dr`)
// Which is the current program counter + the
// calculated offset.
let val: u32 = vm.registers.pc as u32 + pc_offset as u32;
vm.registers.update(dr, val as u16);
vm.registers.update_r_cond_register(dr);
}
/// The contents of the register specified by SR are stored in the memory location
/// whose address is computed by sign-extending bits [8:0] to 16 bits and adding
/// this value to the incremented PC.
///
/// 15 12│11 9│8 0
/// ┌───────────────┼───────────┼───────────────────────────────────┐
/// │ 0011 │ SR │ PCOffset9 │
/// └───────────────┴───────────┴───────────────────────────────────┘
pub fn st(instruction: u16, vm: &mut VM) {
// Get the direct register encoded in the instruction (see `add` fn for more in-depth details)
let sr = (instruction >> 9) & 0x7;
// Grab the PC offset and sign extend it
let pc_offset = sign_extend(instruction & 0x1ff, 9);
// Add the current PC to the PC offset
// We're doing these conversions to avoid overflow
let val: u32 = vm.registers.pc as u32 + pc_offset as u32;
let val: u16 = val as u16;
// Store the value in the register being passed in the instruction at
// the address computed above
vm.write_memory(val as usize, vm.registers.get(sr));
}
/// The contents of the register specified by SR are stored in the memory location
/// whose address is obtained as follows: Bits [8:0] are sign-extended to 16 bits and added to the incremented PC.
/// What is in memory at this address is the address of the location to which the data in SR is stored.
///
/// 15 12│11 9│8 0
/// ┌───────────────┼───────────┼───────────────────────────────────┐
/// │ 1011 │ SR │ PCOffset9 │
/// └───────────────┴───────────┴───────────────────────────────────┘
pub fn sti(instruction: u16, vm: &mut VM) {
// Get the register encoded in the instruction (see `add` fn for more in-depth details)
let sr = (instruction >> 9) & 0x7;
// Grab the PC offset and sign extend it
let pc_offset = sign_extend(instruction & 0x1ff, 9);
// Add the current PC to the PC offset
// We're doing these conversions to avoid overflow
let val: u32 = vm.registers.pc as u32 + pc_offset as u32;
let val: u16 = val as u16;
// This is the difference between STI and ST
let address = vm.read_memory(val) as usize;
vm.write_memory(address, vm.registers.get(sr));
}
/// The contents of the register specified by SR are stored in the memory location
/// whose address is computed by sign-extending bits [5:0] to 16 bits
/// and adding this value to the contents of the register specified by bits [8:6].
///
/// 15 12│11 9│8 6│ 0
/// ┌───────────────┼───────────┼───────────┼───────────────────────┐
/// │ 0111 │ SR │ BaseR │ PCOffset6 │
/// └───────────────┴───────────┴───────────┴───────────────────────┘
pub fn str(instruction: u16, vm: &mut VM) {
// Get the register encoded in the instruction (see `add` fn for more in-depth details)
let dr = (instruction >> 9) & 0x7;
// Grab the base register
let base_reg = (instruction >> 6) & 0x7;
// Grab the offset and sign extend it
let offset = sign_extend(instruction & 0x3F, 6);
// Get the value in the base_register and sum it to the offset encoded in the instruction
// Note that we're doing some conversions here to prevent overflow.
let val: u32 = vm.registers.get(base_reg) as u32 + offset as u32;
let val: u16 = val as u16;
vm.write_memory(val as usize, vm.registers.get(dr));
}
/// `trap` fn allows interacting with I/O devices
/// First R7 is loaded with the incremented PC.
// (This enables a return to the instruction physically following the TRAP instruction in the original program
/// after the service routine has completed execution.)
/// Then the PC is loaded with the starting address of the system call specified by trap vector8.
/// The starting address is contained in the memory location whose address is obtained by zero-extending trap vector8 to 16 bits.
pub fn trap(instruction: u16, vm: &mut VM) {
match instruction & 0xFF {
0x20 => {
// Get character
let mut buffer = [0; 1];
std::io::stdin().read_exact(&mut buffer).unwrap();
vm.registers.r0 = buffer[0] as u16;
}
0x21 => {
// Write out character
let c = vm.registers.r0 as u8;
print!("{}", c as char);
// println!("[*] OUT");
}
0x22 => {
// Puts
let mut index = vm.registers.r0;
let mut c = vm.read_memory(index);
while c != 0x0000 {
print!("{}", (c as u8) as char);
index += 1;
c = vm.read_memory(index);
}
io::stdout().flush().expect("failed to flush");
}
0x23 => {
// In, Print a prompt on the screen and read a single character from the keyboard. The character is echoed onto the console monitor, and its ASCII code is copied into R0.The high eight bits of R0 are cleared.
print!("Enter a character : ");
io::stdout().flush().expect("failed to flush");
let char = std::io::stdin()
.bytes()
.next()
.and_then(|result| result.ok())
.map(|byte| byte as u16)
.unwrap();
vm.registers.update(0, char);
}
0x24 => {
// Putsp
let mut index = vm.registers.r0;
let mut c = vm.read_memory(index);
while c != 0x0000 {
let c1 = ((c & 0xFF) as u8) as char;
print!("{}", c1);
let c2 = ((c >> 8) as u8) as char;
if c2 != '\0' {
print!("{}", c2);
}
index += 1;
c = vm.read_memory(index);
}
io::stdout().flush().expect("failed to flush");
}
0x25 => {
println!("HALT detected");
io::stdout().flush().expect("failed to flush");
process::exit(1);
}
_ => {
process::exit(1);
}
}
}
pub fn sign_extend(mut x: u16, bit_count: u8) -> u16 {
// bit_count is the original number of bits
// that this binary value has. We want to take that
// and transform it into a 16 bits value
// This if clause is testing the sign of the value.
// We're moving `x` to the right up until
// the sign bit (`bit_count - 1`).
// Then check if it's different than zero,
// if it is, it's signed as 1 (negative)
// Meaning we have to pad with ones instead of zeroes
if (x >> (bit_count - 1)) & 1 != 0 {
x |= 0xFFFF << bit_count;
}
// If it's positive, return as is, it will be padded
// with zeroes.
x
}
|
//! Futures and other types that allow asynchronous interaction with channels.
use std::{
future::Future,
pin::Pin,
task::{Context, Poll},
};
use crate::*;
use futures::{Stream, stream::FusedStream, future::FusedFuture};
impl<T> Receiver<T> {
#[inline]
fn poll(&self, cx: &mut Context<'_>) -> Poll<Result<T, RecvError>> {
let mut buf = self.buffer.borrow_mut();
let res = if let Some(msg) = buf.pop_front() {
return Poll::Ready(Ok(msg));
} else {
self
.shared
.poll_inner()
.map(|mut inner| self
.shared
.try_recv(
move || {
// Detach the waker
inner.recv_waker = None;
// Inform the sender that we no longer need waking
inner.listen_mode = 1;
inner
},
&mut buf,
&self.finished,
)
)
};
let poll = match res {
Some(Ok(msg)) => Poll::Ready(Ok(msg)),
Some(Err((_, TryRecvError::Disconnected))) => Poll::Ready(Err(RecvError::Disconnected)),
Some(Err((mut inner, TryRecvError::Empty))) => {
// Inform the sender that we need waking
inner.recv_waker = Some(cx.waker().clone());
inner.listen_mode = 2;
Poll::Pending
},
// Can't access the inner lock, try again
None => {
cx.waker().wake_by_ref();
Poll::Pending
},
};
poll
}
}
/// A future used to receive a value from the channel.
pub struct RecvFuture<'a, T> {
recv: &'a mut Receiver<T>,
}
impl<'a, T> RecvFuture<'a, T> {
pub(crate) fn new(recv: &mut Receiver<T>) -> RecvFuture<T> {
RecvFuture { recv }
}
}
impl<'a, T> Future for RecvFuture<'a, T> {
type Output = Result<T, RecvError>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
self.recv.poll(cx)
}
}
impl<'a, T> FusedFuture for RecvFuture<'a, T> {
fn is_terminated(&self) -> bool {
self.recv.finished.get()
}
}
impl<T> Stream for Receiver<T> {
type Item = T;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.poll(cx).map(|ready| ready.ok())
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.buffer.borrow().len(), None)
}
}
impl<T> FusedStream for Receiver<T> {
fn is_terminated(&self) -> bool {
self.finished.get()
}
}
|
fn main() {
let man = env!("CARGO_MANIFEST_DIR").replace('\\', "/");
let protos_dir = format!("{}/../../protos", man);
println!("cargo:rerun-if-changed={}", protos_dir);
let protos = std::fs::read_dir(protos_dir.as_str())
.expect("Failed to read protos directory")
.filter(|path| {
path.as_ref()
.ok()
.and_then(|p| {
Some(p.path().extension()? == "proto" && p.file_type().ok()?.is_file())
})
.unwrap_or(false)
})
.map(|p| p.as_ref().unwrap().path())
.collect::<Vec<_>>();
let protos = protos
.iter()
.map(|p| p.as_os_str().to_str().unwrap())
.collect::<Vec<_>>();
tonic_build::configure()
.compile(protos.as_slice(), &[protos_dir.as_str()])
.expect("Failed to run protoc");
}
|
//! `FromCast` and `IntoCast` implementations for portable 16-bit wide vectors
#![rustfmt::skip]
use crate::*;
impl_from_cast!(
i8x2[test_v16]: u8x2, m8x2, i16x2, u16x2, m16x2, i32x2, u32x2, f32x2, m32x2,
i64x2, u64x2, f64x2, m64x2, i128x2, u128x2, m128x2, isizex2, usizex2, msizex2
);
impl_from_cast!(
u8x2[test_v16]: i8x2, m8x2, i16x2, u16x2, m16x2, i32x2, u32x2, f32x2, m32x2,
i64x2, u64x2, f64x2, m64x2, i128x2, u128x2, m128x2, isizex2, usizex2, msizex2
);
impl_from_cast_mask!(
m8x2[test_v16]: i8x2, u8x2, i16x2, u16x2, m16x2, i32x2, u32x2, f32x2, m32x2,
i64x2, u64x2, f64x2, m64x2, i128x2, u128x2, m128x2, isizex2, usizex2, msizex2
);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.