text stringlengths 8 4.13M |
|---|
use std;
use read_process_memory::CopyAddress;
/// Copies a struct from another process
pub fn copy_struct<T, P>(addr: usize, process: &P) -> std::io::Result<T>
where P: CopyAddress {
let mut data = vec![0; std::mem::size_of::<T>()];
process.copy_address(addr, &mut data)?;
Ok(unsafe { std::ptr::read(data.as_ptr() as *const _) })
}
/// Given a pointer that points to a struct in another process, returns the
/// struct from the other process
pub fn copy_pointer<T, P>(ptr: *const T, process: &P) -> std::io::Result<T>
where P: CopyAddress {
copy_struct(ptr as usize, process)
}
#[cfg(test)]
pub mod tests {
use super::*;
/// Mock for using CopyAddress on the local process.
pub struct LocalProcess;
impl CopyAddress for LocalProcess {
fn copy_address(&self, addr: usize, buf: &mut [u8]) -> std::io::Result<()> {
unsafe {
std::ptr::copy_nonoverlapping(addr as *mut u8, buf.as_mut_ptr(), buf.len());
}
Ok(())
}
}
struct Point { x: i32, y: i64 }
#[test]
fn test_copy_pointer() {
let original = Point{x:15, y:25};
let copy = copy_pointer(&original, &LocalProcess).unwrap();
assert_eq!(original.x, copy.x);
assert_eq!(original.y, copy.y);
}
#[test]
fn test_copy_struct() {
let original = Point{x:10, y:20};
let copy: Point = copy_struct(&original as *const Point as usize, &LocalProcess).unwrap();
assert_eq!(original.x, copy.x);
assert_eq!(original.y, copy.y);
}
}
|
fn main() {
// Set in build.rs.
let compiler_path = env!("COMPILER_PATH");
let mut compiler_command = std::process::Command::new(compiler_path);
// Use the --version flag on everything other than MSVC.
if !cfg!(target_env = "msvc") {
compiler_command.arg("--version");
}
// Run the compiler to print its version. Ignore the exit status.
let _ = compiler_command.status().unwrap();
}
|
mod spiral;
pub fn solve_puzzle_part_1(input: u32) -> String {
//puzzle(input).to_string()
puzzle1(input as usize).to_string()
}
pub fn solve_puzzle_part_2(input: u32) -> String {
puzzle2(input).to_string()
}
fn puzzle1(index: usize) -> u32 {
// loop over all rings, look for the location of index in the ring
let square_location = spiral::SpiralRingIterator::new()
.map(|ring| spiral::location_of_square_in_ring(&ring, index))
.skip_while(|x| x.is_none())
.next()
.unwrap()
.unwrap();
// Manhattan distance of location
(square_location.x.abs() + square_location.y.abs()) as u32
}
fn puzzle2(input: u32) -> u32 {
// if the input is 0 then the answer is 1 in ring 0
if input == 0 {
return 1;
}
// we check every ring of the spiral for a number larger than the input.
// we only need the previous ring to do this.
let mut ring_iter = spiral::SpiralRingIterator::new();
// create ring 0 and store 1 into it
let mut prev_ring = ring_iter.next().unwrap();
prev_ring.squares[0].content = Some(1);
for ring in ring_iter {
// create a mutable ring that we can store the values in
let mut ring = ring.clone();
// the loop for general rings doesn't work for ring 1
if ring.n == 1 {
// 5 4 2
// 10 1 1
// 11 23 25
for i in 0..ring.squares.len() {
let content: u32 = match i {
0 => 1,
1 => 2,
2 => 4,
3 => 5,
4 => 10,
5 => 11,
6 => 23,
7 => 25,
_ => panic!("invalid index in ring 1"),
};
if content > input {
return content;
}
ring.squares[i].content = Some(content);
}
} else {
// 7 6 5 4 3
// 8 3 2 1 2
// 9 4 0 0 1
// 10 5 6 7 0
// 11 12 13 14 15
let ring_length = ring.squares.len();
let prev_ring_length = prev_ring.squares.len();
let mut prev_val = 0;
let mut prev_prev_val = 0;
let mut corners_passed = 0;
for i in 0..ring.squares.len() {
// function to check if square i is a corner square
let is_corner_square = |i| (i + 1) % (ring_length / 4) == 0;
// j is the index of the square in the previous ring beside square i
let j = (i + (ring_length - 1) + (ring_length - 2) * corners_passed) % ring_length;
// f(i) returns the content of the square at index i in the previous ring
let f = |i: usize| prev_ring.squares[i].content.unwrap();
let content = if i == 0 {
// first square
f(0) + f(prev_ring_length - 1)
} else if i == 1 {
// second square
f(0) + f(1) + f(prev_ring_length - 1) + prev_val
} else if is_corner_square(i + 1) {
// one square before a corner
f(j - 1) + f(j) + prev_val + if i == ring_length - 2 {
// this is one square before last corner
ring.squares[0].content.unwrap()
} else {
0
}
} else if is_corner_square(i) {
// corner square
corners_passed += 1;
f(j - 1) + prev_val + if i == ring_length - 1 {
// this is the last square
ring.squares[0].content.unwrap()
} else {
0
}
} else if is_corner_square(i - 1) {
// one square after a corner
f(j) + f(j + 1) + prev_val + prev_prev_val
} else {
// "normal" squares
f(j - 1) + f(j) + f(j + 1) + prev_val
};
// check if we found our answer
if content > input {
return content;
}
// save value in square
ring.squares[i].content = Some(content);
// update values of previous squares
prev_prev_val = prev_val;
prev_val = content;
}
}
// save copy of this ring for next iteration
prev_ring = ring;
}
panic!("unable to solve puzzle 2")
}
|
use pyo3::prelude::*;
use pyo3::wrap_pyfunction;
use std::fmt;
use std::fs::File;
use std::io::{BufRead, BufReader, Error, ErrorKind};
use std::num::ParseIntError;
use std::{env, error};
use game::Game;
mod game;
mod grid;
#[derive(Debug)]
pub enum ConnectzError {
Incomplete,
IllegalContinue,
IllegalRow,
IllegalColumn,
IllegalGame,
InvalidFile,
FileNotFound,
Argument(String),
}
impl fmt::Display for ConnectzError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ConnectzError::Incomplete => write!(f, "{}", 3),
ConnectzError::IllegalContinue => write!(f, "{}", 4),
ConnectzError::IllegalRow => write!(f, "{}", 5),
ConnectzError::IllegalColumn => write!(f, "{}", 6),
ConnectzError::IllegalGame => write!(f, "{}", 7),
ConnectzError::InvalidFile => write!(f, "{}", 8),
ConnectzError::FileNotFound => write!(f, "{}", 9),
ConnectzError::Argument(v) => write!(f, "{}", v),
}
}
}
impl error::Error for ConnectzError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
None
}
}
// Implement the conversion from `ParseIntError` to `DoubleError`.
// This will be automatically called by `?` if a `ParseIntError`
// needs to be converted into a `DoubleError`.
impl From<ParseIntError> for ConnectzError {
fn from(_err: ParseIntError) -> ConnectzError {
ConnectzError::InvalidFile
}
}
impl From<std::io::Error> for ConnectzError {
fn from(_: Error) -> Self {
ConnectzError::FileNotFound
}
}
type Result<T> = std::result::Result<T, ConnectzError>;
#[derive(PartialEq, Debug)]
pub enum Outcome {
Draw,
PlayerWin(Player),
Incomplete,
IllegalContinue,
IllegalRow,
IllegalColumn,
IllegalGame,
InvalidFile,
FileNotFound,
}
impl Outcome {
pub fn as_u8(&self) -> &u8 {
match self {
Outcome::Draw => &0,
Outcome::PlayerWin(player) => player,
Outcome::Incomplete => &3,
Outcome::IllegalContinue => &4,
Outcome::IllegalRow => &5,
Outcome::IllegalColumn => &6,
Outcome::IllegalGame => &7,
Outcome::InvalidFile => &8,
Outcome::FileNotFound => &9,
}
}
}
impl fmt::Display for Outcome {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.as_u8())
}
}
impl ToPyObject for Outcome {
fn to_object(&self, py: Python) -> PyObject {
self.as_u8().to_object(py)
}
}
type Player = u8;
pub struct Config {
filename: String,
}
impl Config {
pub fn new(mut args: env::Args) -> Result<Config> {
args.next();
let filename = match args.next() {
Some(arg) => arg,
None => {
return Err(ConnectzError::Argument(String::from(
"Provide one input file",
)))
}
};
Ok(Config { filename })
}
}
pub fn run(config: Config) -> Result<Outcome> {
let file = File::open(config.filename)?;
let mut file = BufReader::new(file);
let mut header = String::new();
file.read_line(&mut header)?;
let mut game = Game::from_string(&header)?;
if let Ok(moves) = file
.lines()
.map(|line| {
line.and_then(|v| {
v.parse::<u32>()
.map_err(|e| Error::new(ErrorKind::InvalidData, e))
.map(|v| v - 1)
})
})
.collect()
{
Ok(game.play(&moves))
} else {
Err(ConnectzError::InvalidFile)
}
}
#[pyfunction]
fn run_file(filename: String) -> PyResult<String> {
if let Ok(result) = run(Config { filename }) {
Ok(format!("{}", result))
} else {
Ok(String::from("-1"))
}
}
// create_exception!(connectz, ConnectzError, PyException);
/// A Python module implemented in Rust.
#[pymodule]
fn connectz(_py: Python, m: &PyModule) -> PyResult<()> {
// m.add("ConnectzError", py.get_type::<ConnectzError>())?;
m.add_function(wrap_pyfunction!(run_file, m)?)?;
m.add_class::<Game>()?;
Ok(())
}
|
use crate::auth::{AuthenticationError, Credentials};
use crate::{
auth::UserDetail,
server::{
controlchan::{
error::ControlChanError,
handler::{CommandContext, CommandHandler},
Reply, ReplyCode,
},
session::SessionState,
},
storage::{Metadata, StorageBackend},
};
use async_trait::async_trait;
use bytes::Bytes;
use std::sync::Arc;
#[derive(Debug)]
pub struct User {
username: Bytes,
}
impl User {
pub fn new(username: Bytes) -> Self {
User { username }
}
}
#[async_trait]
impl<Storage, Usr> CommandHandler<Storage, Usr> for User
where
Usr: UserDetail,
Storage: StorageBackend<Usr> + 'static,
Storage::Metadata: Metadata,
{
#[tracing_attributes::instrument]
async fn handle(&self, args: CommandContext<Storage, Usr>) -> Result<Reply, ControlChanError> {
let mut session = args.session.lock().await;
let username_str = std::str::from_utf8(&self.username)?;
let cert_auth_sufficient = args.authenticator.cert_auth_sufficient(username_str).await;
match (session.state, &session.cert_chain, cert_auth_sufficient) {
(SessionState::New, Some(_), true) => {
let auth_result: Result<Usr, AuthenticationError> = args
.authenticator
.authenticate(
username_str,
&Credentials {
certificate_chain: session.cert_chain.clone(),
password: None,
source_ip: session.source.ip(),
},
)
.await;
match auth_result {
Ok(user_detail) => {
let user = username_str;
session.username = Some(user.to_string());
session.state = SessionState::WaitCmd;
session.user = Arc::new(Some(user_detail));
Ok(Reply::new(ReplyCode::UserLoggedInViaCert, "User logged in"))
}
Err(_e) => Ok(Reply::new(ReplyCode::NotLoggedIn, "Invalid credentials")),
}
}
(SessionState::New, None, _) | (SessionState::New, Some(_), false) => {
let user = std::str::from_utf8(&self.username)?;
session.username = Some(user.to_string());
session.state = SessionState::WaitPass;
Ok(Reply::new(ReplyCode::NeedPassword, "Password Required"))
}
_ => Ok(Reply::new(ReplyCode::BadCommandSequence, "Please create a new connection to switch user")),
}
}
}
#[cfg(test)]
mod tests {
use crate::auth::{AuthenticationError, Authenticator, ClientCert, Credentials, DefaultUser, UserDetail};
use crate::server::controlchan::handler::CommandHandler;
use crate::server::session::SharedSession;
use crate::server::{Command, ControlChanMsg, Reply, ReplyCode, Session, SessionState};
use crate::storage::{Fileinfo, Result};
use crate::storage::{Metadata, StorageBackend};
use async_trait::async_trait;
use bytes::Bytes;
use pretty_assertions::assert_eq;
use slog::o;
use std::fmt::Debug;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::SystemTime;
use tokio::io::AsyncRead;
use tokio::sync::mpsc;
use tokio::sync::Mutex;
#[derive(Debug)]
struct Auth {
pub short_auth: bool,
pub auth_ok: bool,
}
#[async_trait]
#[allow(unused)]
impl Authenticator<DefaultUser> for Auth {
async fn authenticate(&self, username: &str, creds: &Credentials) -> std::result::Result<DefaultUser, AuthenticationError> {
if self.auth_ok {
Ok(DefaultUser {})
} else {
Err(AuthenticationError::new("bad credentials"))
}
}
async fn cert_auth_sufficient(&self, username: &str) -> bool {
self.short_auth
}
}
struct Meta {}
#[allow(unused)]
impl Metadata for Meta {
fn len(&self) -> u64 {
todo!()
}
fn is_dir(&self) -> bool {
todo!()
}
fn is_file(&self) -> bool {
todo!()
}
fn is_symlink(&self) -> bool {
todo!()
}
fn modified(&self) -> Result<SystemTime> {
todo!()
}
fn gid(&self) -> u32 {
todo!()
}
fn uid(&self) -> u32 {
todo!()
}
}
#[derive(Debug)]
struct Vfs {}
#[async_trait]
#[allow(unused)]
impl StorageBackend<DefaultUser> for Vfs {
type Metadata = Meta;
async fn metadata<P: AsRef<Path> + Send + Debug>(&self, user: &DefaultUser, path: P) -> Result<Self::Metadata> {
todo!()
}
async fn list<P: AsRef<Path> + Send + Debug>(&self, user: &DefaultUser, path: P) -> Result<Vec<Fileinfo<PathBuf, Self::Metadata>>>
where
<Self as StorageBackend<DefaultUser>>::Metadata: Metadata,
{
todo!()
}
async fn get<P: AsRef<Path> + Send + Debug>(&self, user: &DefaultUser, path: P, start_pos: u64) -> Result<Box<dyn AsyncRead + Send + Sync + Unpin>> {
todo!()
}
async fn put<P: AsRef<Path> + Send + Debug, R: AsyncRead + Send + Sync + Unpin + 'static>(
&self,
user: &DefaultUser,
input: R,
path: P,
start_pos: u64,
) -> Result<u64> {
todo!()
}
async fn del<P: AsRef<Path> + Send + Debug>(&self, user: &DefaultUser, path: P) -> Result<()> {
todo!()
}
async fn mkd<P: AsRef<Path> + Send + Debug>(&self, user: &DefaultUser, path: P) -> Result<()> {
todo!()
}
async fn rename<P: AsRef<Path> + Send + Debug>(&self, user: &DefaultUser, from: P, to: P) -> Result<()> {
todo!()
}
async fn rmd<P: AsRef<Path> + Send + Debug>(&self, user: &DefaultUser, path: P) -> Result<()> {
todo!()
}
async fn cwd<P: AsRef<Path> + Send + Debug>(&self, user: &DefaultUser, path: P) -> Result<()> {
todo!()
}
}
impl Reply {
fn matches_code(&self, code: ReplyCode) -> bool {
match self {
Reply::None => false,
Reply::CodeAndMsg { code: c, .. } | Reply::MultiLine { code: c, .. } => c == &code,
}
}
}
impl<Storage, User> super::CommandContext<Storage, User>
where
Storage: StorageBackend<User> + 'static,
Storage::Metadata: Metadata + Sync,
User: UserDetail + 'static,
{
fn test(session_arc: SharedSession<Storage, User>, auther: Arc<dyn Authenticator<User>>) -> super::CommandContext<Storage, User> {
let (tx, _) = mpsc::channel::<ControlChanMsg>(1);
super::CommandContext {
parsed_command: Command::User {
username: Bytes::from("test-user"),
},
session: session_arc,
authenticator: auther,
tls_configured: true,
passive_ports: Default::default(),
passive_host: Default::default(),
tx_control_chan: tx,
local_addr: "127.0.0.1:8080".parse().unwrap(),
storage_features: 0,
tx_proxyloop: None,
logger: slog::Logger::root(slog::Discard {}, o!()),
sitemd5: Default::default(),
}
}
}
struct Test {
short_auth: bool,
auth_ok: bool,
cert: Option<Vec<crate::auth::ClientCert>>,
expected_reply: ReplyCode,
expected_state: SessionState,
}
async fn test(test: Test) {
let user_cmd = super::User {
username: Bytes::from("test-user"),
};
let mut session = Session::new(Arc::new(Vfs {}), "127.0.0.1:8080".parse().unwrap());
session.cert_chain = test.cert;
let session_arc = Arc::new(Mutex::new(session));
let ctx = super::CommandContext::test(
session_arc.clone(),
Arc::new(Auth {
short_auth: test.short_auth,
auth_ok: test.auth_ok,
}),
);
let reply = user_cmd.handle(ctx).await.unwrap();
assert_eq!(reply.matches_code(test.expected_reply), true, "Reply code must match");
assert_eq!(session_arc.lock().await.state, test.expected_state, "Next state must match");
}
#[tokio::test]
async fn login_user_pass_no_cert() {
test(Test {
short_auth: false,
auth_ok: false,
cert: None,
expected_reply: ReplyCode::NeedPassword,
expected_state: SessionState::WaitPass,
})
.await
}
#[tokio::test]
async fn login_user_pass_with_cert() {
test(Test {
short_auth: false,
auth_ok: true,
cert: Some(vec![ClientCert(vec![0])]),
expected_reply: ReplyCode::NeedPassword,
expected_state: SessionState::WaitPass,
})
.await
}
#[tokio::test]
async fn login_by_cert_bad_creds() {
test(Test {
short_auth: true,
auth_ok: false,
cert: Some(vec![ClientCert(vec![0])]),
expected_reply: ReplyCode::NotLoggedIn,
expected_state: SessionState::New,
})
.await
}
#[tokio::test]
async fn login_by_cert_ok() {
test(Test {
short_auth: true,
auth_ok: true,
cert: Some(vec![ClientCert(vec![0])]),
expected_reply: ReplyCode::UserLoggedInViaCert,
expected_state: SessionState::WaitCmd,
})
.await
}
}
|
/*!
Traits and types related to loading an abi_stable dynamic library,
as well as functions/modules within.
*/
use std::{
fmt::{self, Display},
io,
marker::PhantomData,
mem,
path::{Path,PathBuf},
sync::atomic,
};
#[allow(unused_imports)]
use core_extensions::prelude::*;
use libloading::{
Library as LibLoadingLibrary,
Symbol as LLSymbol,
};
pub use abi_stable_shared::mangled_root_module_loader_name;
use crate::{
abi_stability::stable_abi_trait::SharedStableAbi,
globals::{self,Globals},
marker_type::ErasedObject,
type_layout::TypeLayout,
sabi_types::{ LateStaticRef, ParseVersionError, VersionNumber, VersionStrings },
std_types::{RVec,RBoxError,StaticStr},
utils::{transmute_reference},
};
pub mod c_abi_testing;
mod lib_header;
mod root_mod_trait;
mod raw_library;
pub use self::{
c_abi_testing::{CAbiTestingFns,C_ABI_TESTING_FNS},
lib_header::{AbiHeader,LibHeader},
root_mod_trait::{
RootModule,
lib_header_from_raw_library,
lib_header_from_path,
abi_header_from_raw_library,
abi_header_from_path,
RootModuleConsts,
ErasedRootModuleConsts,
},
raw_library::RawLibrary,
};
///////////////////////////////////////////////////////////////////////////////
/// What naming convention to expect when loading a library from a directory.
#[derive(Debug,Copy,Clone,PartialEq,Eq,Ord,PartialOrd,Hash)]
pub enum LibrarySuffix{
/// Loads a dynamic library at `<folder>/<base_name>.extension`
NoSuffix,
/// Loads a dynamic library at `<folder>/<base_name>-<pointer_size>.<extension>`
Suffix,
}
//////////////////////////////////////////////////////////////////////
/// The path a library is loaded from.
#[derive(Debug,Copy,Clone,PartialEq,Eq,Ord,PartialOrd,Hash)]
pub enum LibraryPath<'a>{
FullPath(&'a Path),
Directory(&'a Path),
}
//////////////////////////////////////////////////////////////////////
/// Whether the ABI of a root module is checked.
#[repr(u8)]
#[derive(Debug,Copy,Clone,StableAbi)]
pub enum IsLayoutChecked{
Yes(&'static TypeLayout),
No
}
impl IsLayoutChecked{
pub fn into_option(self)->Option<&'static TypeLayout>{
match self {
IsLayoutChecked::Yes(x)=>Some(x),
IsLayoutChecked::No =>None,
}
}
}
//////////////////////////////////////////////////////////////////////
/// The static variables declared for some `RootModule` implementor.
#[doc(hidden)]
pub struct RootModuleStatics<M>{
root_mod:LateStaticRef<M>,
raw_lib:LateStaticRef<RawLibrary>,
}
impl<M> RootModuleStatics<M>{
#[doc(hidden)]
#[inline]
pub const fn _private_new()->Self{
Self{
root_mod:LateStaticRef::new(),
raw_lib:LateStaticRef::new(),
}
}
}
/// Implements the `RootModule::root_module_statics` associated function.
///
/// To define the associated function use:
/// `abi_stable::declare_root_module_statics!{TypeOfSelf}`.
/// Passing `Self` instead of `TypeOfSelf` won't work.
#[macro_export]
macro_rules! declare_root_module_statics {
( $this:ty ) => (
#[inline]
fn root_module_statics()->&'static $crate::library::RootModuleStatics<$this>{
static _ROOT_MOD_STATICS:$crate::library::RootModuleStatics<$this>=
$crate::library::RootModuleStatics::_private_new();
&_ROOT_MOD_STATICS
}
)
}
//////////////////////////////////////////////////////////////////////
/// All the possible errors that could happen when loading a library,
/// or a module.
#[derive(Debug)]
pub enum LibraryError {
/// When a library can't be loaded, because it doesn't exist.
OpenError{
path:PathBuf,
io:io::Error,
},
/// When a function/static does not exist.
GetSymbolError{
library:PathBuf,
/// The name of the function/static.Does not have to be utf-8.
symbol:Vec<u8>,
io:io::Error,
},
/// The version string could not be parsed into a version number.
ParseVersionError(ParseVersionError),
/// The version numbers of the library was incompatible.
IncompatibleVersionNumber {
library_name: &'static str,
expected_version: VersionNumber,
actual_version: VersionNumber,
},
/// The abi is incompatible.
/// The error is opaque,since the error always comes from the main binary
/// (dynamic libraries can be loaded from other dynamic libraries),
/// and no approach for extensible enums is settled on yet.
AbiInstability(RBoxError),
/// The type used to check that this is a compatible abi_stable
/// is not the same.
InvalidAbiHeader(AbiHeader),
/// When Rust changes how it implements the C abi,
/// most likely because of zero-sized types.
InvalidCAbi{
expected:RBoxError,
found:RBoxError,
},
/// There could have been 0 or more errors in the function.
Many(RVec<Self>),
}
impl From<ParseVersionError> for LibraryError {
fn from(v: ParseVersionError) -> LibraryError {
LibraryError::ParseVersionError(v)
}
}
impl Display for LibraryError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("\n")?;
match self {
LibraryError::OpenError{path,io} => writeln!(
f,
"Could not open library at:\n\t{}\nbecause:\n\t{}",
path.display(),io
),
LibraryError::GetSymbolError{library,symbol,io} => writeln!(
f,
"Could load symbol:\n\t{}\nin library:\n\t{}\nbecause:\n\t{}",
String::from_utf8_lossy(symbol),
library.display(),
io
),
LibraryError::ParseVersionError(x) => fmt::Display::fmt(x, f),
LibraryError::IncompatibleVersionNumber {
library_name,
expected_version,
actual_version,
} => writeln!(
f,
"\n'{}' library version mismatch:\nuser:{}\nlibrary:{}",
library_name, expected_version, actual_version,
),
LibraryError::AbiInstability(x) => fmt::Display::fmt(x, f),
LibraryError::InvalidAbiHeader(found) => write!(
f,
"The abi of the library was:\n{:#?}\n\
When this library expected:\n{:#?}",
found, AbiHeader::VALUE,
),
LibraryError::InvalidCAbi{expected,found}=>{
write!{
f,
"The C abi of the library is different than expected:\n\
While running tests on the library:\n\
{s}Found:\n{s}{s}{found}\n\
{s}Expected:\n{s}{s}{expected}\n\
",
s=" ",
found=found,
expected=expected,
}
},
LibraryError::Many(list)=>{
for e in list {
Display::fmt(e,f)?;
}
Ok(())
}
}?;
f.write_str("\n")?;
Ok(())
}
}
impl ::std::error::Error for LibraryError {}
|
use std::io::prelude::*;
use std::io::{self, BufReader, BufWriter};
use std::net::TcpStream;
pub struct BufTcpStream {
input: BufReader<TcpStream>,
output: BufWriter<TcpStream>,
}
impl BufTcpStream {
pub fn new(stream: TcpStream) -> io::Result<Self> {
let input = BufReader::new(stream.try_clone()?);
let output = BufWriter::new(stream);
Ok(Self { input, output })
}
pub fn send_msg(&mut self, msg: String) {
self.output.write_all(msg.as_bytes()).unwrap();
self.output.flush().unwrap();
}
pub fn recv(&mut self) -> String {
let mut buffer = String::new();
self.input.read_line(&mut buffer).unwrap();
buffer
}
}
|
// From: https://github.com/godot-rust/godot-rust/blob/bddbaedccaa56ce6411db6cb8f74206a01dd1196/examples/dodge_the_creeps/src/extensions.rs
use gdnative::prelude::*;
pub trait NodeExt {
/// Gets a node at `path`, assumes that it's safe to use, and casts it to `T`.
///
/// # Safety
///
/// See `Ptr::assume_safe`.
unsafe fn get_typed_node<T, P>(&self, path: P) -> TRef<'_, T, Shared>
where T: GodotObject + SubClass<Node>, P: Into<NodePath>;
}
impl NodeExt for Node {
unsafe fn get_typed_node<T, P>(&self, path: P) -> TRef<'_, T, Shared>
where T: GodotObject + SubClass<Node>, P: Into<NodePath> {
self.get_node(path.into()).expect("node should exist").assume_safe().cast()
.expect("node should be of the correct type")
}
}
|
pub fn start(){
// Declare variable => Immutable by default
let imut_var = 1;
println!("This is Immutable variable: {}", imut_var);
// Declare variable mutable
let mut mut_var = 1;
println!("This is Mutable variable: {}", mut_var);
mut_var = 2;
println!("This is Mutable variable: {}", mut_var);
// Declare constant
const PI: f64 = 3.14;
println!("This is Constant variable: {}", PI);
} |
use std::collections::VecDeque;
use std::io::{self, Read};
use crate::disk::block::BlockDeviceRef;
use crate::disk::block::Location;
use crate::disk::block::BLOCK_SIZE;
use crate::disk::chain::{ChainIterator, ChainReader};
use crate::disk::directory::{self, DirectoryEntry};
use crate::disk::DiskError;
use crate::disk::geos::GEOSDirectoryEntry;
/// A block can store 254 bytes of data -- the 256 full block size, minus 2
/// bytes for the next track and sector pointer.
const BLOCK_DATA_SIZE: usize = BLOCK_SIZE - 2;
enum GEOSReaderState {
DirectoryEntry,
InfoBlock,
VLIRIndexBlock,
Records,
Finished,
}
/// A GEOSReader serializes a complex GEOS file into a flat byte stream in a
/// manner compatible with the GEOS Convert utility. This preserves directory
/// entry metadata, info blocks, and VLIR records.
pub struct GEOSReader {
blocks: BlockDeviceRef,
state: GEOSReaderState,
buffer: Vec<u8>,
is_vlir: bool,
info_location: Location,
start_location: Location,
chains: VecDeque<ChainReader>,
}
impl GEOSReader {
/// Create a new GEOSReader for serializing the GEOS file at the provided
/// directory entry.
pub fn new(blocks: BlockDeviceRef, entry: &DirectoryEntry) -> io::Result<GEOSReader> {
const CVT_SIGNATURE_OFFSET: usize = 0x20;
const CVT_SIGNATURE_PRG: &[u8] = b"PRG";
const CVT_SIGNATURE_SEQ: &[u8] = b"SEQ";
const CVT_SIGNATURE_SUFFIX: &[u8] = b" formatted GEOS file V1.0";
// Construct the initial 254-byte data block which contains a copy of the
// original directory entry and any extra implementation-specific data
// such as the signature string.
let mut buffer = [0; BLOCK_SIZE].to_vec();
// Load the directory entry bytes
entry.to_bytes(&mut buffer[0..directory::ENTRY_SIZE]);
// Write the signature string. I don't think this is required, but both the
// GEOS Convert2.5 program and Vice's c1541 seem to add this.
if entry.is_vlir()? {
buffer[CVT_SIGNATURE_OFFSET..CVT_SIGNATURE_OFFSET + 3]
.copy_from_slice(CVT_SIGNATURE_PRG);
} else {
buffer[CVT_SIGNATURE_OFFSET..CVT_SIGNATURE_OFFSET + 3]
.copy_from_slice(CVT_SIGNATURE_SEQ);
}
buffer[CVT_SIGNATURE_OFFSET + 3..CVT_SIGNATURE_OFFSET + 3 + CVT_SIGNATURE_SUFFIX.len()]
.copy_from_slice(CVT_SIGNATURE_SUFFIX);
// Remove the would-be NTS (next track and sector) link.
buffer.drain(0..2);
assert!(buffer.len() == BLOCK_DATA_SIZE);
Ok(GEOSReader {
blocks,
state: GEOSReaderState::DirectoryEntry,
buffer,
is_vlir: entry.is_vlir()?,
info_location: entry
.info_location()?
.ok_or_else(|| DiskError::GEOSInfoNotFound.to_io_error())?,
start_location: entry.first_sector,
chains: VecDeque::new(),
})
}
/// Process the VLIR index block by converting (track, sector) pairs into
/// (block count, bytes used in the final block) pairs. Along the way,
/// accumulate the ChainReaders that will be needed to read the VLIR
/// records in the Records state.
fn process_vlir_index_block(&mut self) -> io::Result<()> {
let blocks = self.blocks.borrow();
let mut index_block = blocks.sector(self.start_location)?[2..].to_vec();
/// Scan the chain and return the number of blocks used, and the number
/// of bytes used in the final block.
fn scan_chain(blocks: BlockDeviceRef, start: Location) -> io::Result<(u8, u8)> {
let (count, last) = ChainIterator::new(blocks, start).fold(Ok((0, 0)), |acc, b| {
acc.and_then(|(count, _last)| {
// Note we subtract one from the data length to convert to CBM's "offset of last
// used byte within the full block containing a two block track and sector
// prefix".
b.map(|b| (count + 1, b.data.len() - 1))
})
})?;
if count > ::std::u8::MAX as usize {
return Err(DiskError::RecordTooLarge.into());
}
assert!(last <= ::std::u8::MAX as usize);
Ok((count as u8, last as u8))
}
// For every pair of bytes in the index block, generate an optional chain
// reader, the block count, and the number of bytes used in the final
// block.
let (chains, conversions): (Vec<Option<ChainReader>>, Vec<(u8, u8)>) = index_block
.chunks_mut(2)
.take_while(|chunk| chunk[0] != 0x00 || chunk[1] != 0x00)
.map(|chunk| {
if chunk[0] == 0x00 && chunk[1] == 0xFF {
// Empty record
Ok((None, (0x00, 0xFF)))
} else {
let record_start = Location::from_bytes(chunk);
let (count, last) = scan_chain(self.blocks.clone(), record_start)?;
let reader = ChainReader::new(self.blocks.clone(), record_start);
Ok((Some(reader), (count, last)))
}
})
.collect::<io::Result<Vec<_>>>()?
.into_iter()
.unzip();
// Render the new VLIR block where (track, sector) pairs have been converted
// into (block count, final bytes) pairs.
let mut block =
conversions
.iter()
.fold(Vec::with_capacity(BLOCK_DATA_SIZE), |mut v, conversion| {
v.push(conversion.0);
v.push(conversion.1);
v
});
// Pad remainder of block with zeros.
block.resize(BLOCK_DATA_SIZE, 0);
// The converted index block will be fed to the reader in VLIRIndexBlock state.
self.buffer = block;
// Save the chain readers for later processing in the Records state.
self.chains = chains.into_iter().flatten().collect();
Ok(())
}
/// Transition to the next state, loading the buffer with the bytes to be
/// read in the new state.
fn next_state(&mut self) -> io::Result<()> {
match self.state {
GEOSReaderState::DirectoryEntry => {
// Transition to reading the GEOS info block.
self.state = GEOSReaderState::InfoBlock;
let blocks = self.blocks.borrow();
let info_block = blocks.sector(self.info_location)?;
self.buffer = info_block[2..].to_vec();
}
GEOSReaderState::InfoBlock => {
if self.is_vlir {
// Transition to reading the VLIR index block.
self.state = GEOSReaderState::VLIRIndexBlock;
// Convert the VLIR index block and initialize chain readers.
self.process_vlir_index_block()?;
} else {
// If this is a sequential file, start reading the single record.
self.state = GEOSReaderState::Records;
self.chains
.push_back(ChainReader::new(self.blocks.clone(), self.start_location));
}
}
GEOSReaderState::VLIRIndexBlock => {
self.state = GEOSReaderState::Records;
self.next_state()?;
}
GEOSReaderState::Records => {
match self.chains.pop_front() {
Some(mut chain) => {
chain.read_to_end(&mut self.buffer)?;
// Pad to a multiple of BLOCK_DATA_SIZE unless this is the last record.
if !self.chains.is_empty() {
let remainder = self.buffer.len() % BLOCK_DATA_SIZE;
if remainder > 0 {
let padded_size = self.buffer.len() + BLOCK_DATA_SIZE - remainder;
self.buffer.resize(padded_size, 0);
}
}
}
None => self.state = GEOSReaderState::Finished,
}
}
GEOSReaderState::Finished => {}
};
Ok(())
}
}
impl Read for GEOSReader {
fn read(&mut self, mut buf: &mut [u8]) -> io::Result<usize> {
if let GEOSReaderState::Finished = self.state {
return Ok(0);
}
let mut bytes_written: usize = 0;
loop {
let bytes = buf.len().min(self.buffer.len());
// Write bytes
let _ = &mut buf[..bytes].copy_from_slice(&self.buffer[..bytes]);
bytes_written += bytes;
if bytes == buf.len() {
// Output buffer filled -- nothing more to do for now.
break;
}
// Reduce the output buffer to the unwritten portion.
let buf_ref = &mut buf;
let value: &mut [u8] = std::mem::take(buf_ref);
*buf_ref = &mut value[bytes..];
// Reduce the input buffer
self.buffer.drain(0..bytes);
// Input buffer drained -- transition to next step
if self.buffer.is_empty() {
// State transition
self.next_state()?;
if let GEOSReaderState::Finished = self.state {
break;
}
}
}
Ok(bytes_written)
}
}
|
pub mod http;
pub mod models;
pub mod dao;
pub mod test;
pub mod data;
pub mod additional_service;
pub mod sql_mapper;
pub mod service;
|
/// Assume two values are not equal.
///
/// * When true, return `Ok(true)`.
///
/// * When false, return [`Err`] with a message and the values of the
/// expressions with their debug representations.
///
/// # Example
///
/// ```rust
/// # #[macro_use] extern crate assertable; fn main() {
/// let x = assume_ne!(1, 2);
/// //-> Ok(true)
/// # }
/// ```
///
/// ```rust
/// # #[macro_use] extern crate assertable; fn main() {
/// let x = assume_ne!(1, 1);
/// //-> Err("assume_ne left:1 right:1")
/// # }
/// ```
///
/// This macro has a second form where a custom message can be provided.
#[macro_export]
macro_rules! assume_ne {
($left:expr, $right:expr $(,)?) => ({
match (&$left, &$right) {
(left_val, right_val) => {
if (left_val != right_val) {
Ok(true)
} else {
Err(format!("assumption failed: `assume_ne(left, right)`\n left: `{:?}`\n right: `{:?}`", $left, $right))
}
}
}
});
($left:expr, $right:expr, $($arg:tt)+) => ({
match (&($left), &($right)) {
(left_val, right_val) => {
if (left_val != right_val) {
Ok(true)
} else {
Err($($arg)+)
}
}
}
});
}
#[cfg(test)]
mod tests {
#[test]
fn test_assume_ne_x_arity_2_success() {
let a = 1;
let b = 2;
let x = assume_ne!(a, b);
assert_eq!(
x.unwrap(),
true
);
}
#[test]
fn test_assume_ne_x_arity_2_failure() {
let a = 1;
let b = 1;
let x = assume_ne!(a, b);
assert_eq!(
x.unwrap_err(),
"assumption failed: `assume_ne(left, right)`\n left: `1`\n right: `1`"
);
}
#[test]
fn test_assume_ne_x_arity_3_success() {
let a = 1;
let b = 2;
let x = assume_ne!(a, b, "message");
assert_eq!(
x.unwrap(),
true
);
}
#[test]
fn test_assume_ne_x_arity_3_failure() {
let a = 1;
let b = 1;
let x = assume_ne!(a, b, "message");
assert_eq!(
x.unwrap_err(),
"message"
);
}
}
|
fn main() {
{
let xx = String::from("hello hdl!");
let word = first_word(&xx);
println!("{:?}", word);
println!("{:?}", xx);
}
}
// String slice 的类型写法是 &str
fn first_word(ss: &String) -> &str {
let bytes = ss.as_bytes();
for (ii, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &ss[0..ii];
}
}
&ss[..]
}
|
use super::*;
use std::collections::VecDeque;
use std::sync::{Arc, RwLock};
/// Represents a node in network.
pub struct Node<I: Input, S: Storage<Item = I>> {
/// A weight vector.
pub weights: Vec<f64>,
/// An error of the neuron.
pub error: f64,
/// Tracks amount of times node is selected as BU.
pub total_hits: usize,
/// Tracks last hits,
pub last_hits: VecDeque<usize>,
/// A coordinate in network.
pub coordinate: Coordinate,
/// A reference to topology.
pub topology: Topology<I, S>,
/// Remembers passed data.
pub storage: S,
/// A node creating time.
pub creation_time: usize,
/// How many last hits should be remembered.
hit_memory_size: usize,
}
/// Represents a node neighbourhood.
pub struct Topology<I: Input, S: Storage<Item = I>> {
/// An input dimension.
pub dimension: usize,
/// A link to right neighbour.
pub right: Option<NodeLink<I, S>>,
/// A link to left neighbour.
pub left: Option<NodeLink<I, S>>,
/// A link to up neighbour.
pub up: Option<NodeLink<I, S>>,
/// A link to down neighbour.
pub down: Option<NodeLink<I, S>>,
}
/// A reference to the node.
pub type NodeLink<I, S> = Arc<RwLock<Node<I, S>>>;
/// Coordinate of the node.
#[derive(Clone, Hash, PartialEq, Eq)]
pub struct Coordinate(pub i32, pub i32);
impl<I: Input, S: Storage<Item = I>> Node<I, S> {
/// Creates a new instance of `Node`.
pub fn new(coordinate: Coordinate, weights: &[f64], time: usize, hit_memory_size: usize, storage: S) -> Self {
Self {
weights: weights.to_vec(),
error: 0.0,
total_hits: 0,
last_hits: VecDeque::with_capacity(hit_memory_size + 1),
coordinate,
topology: Topology::empty(weights.len()),
storage,
creation_time: time,
hit_memory_size,
}
}
/// Adjusts the weights of the node.
pub fn adjust(&mut self, target: &[f64], learning_rate: f64) {
debug_assert!(self.weights.len() == target.len());
for (idx, value) in target.iter().enumerate() {
self.weights[idx] += learning_rate * (*value - self.weights[idx]);
}
}
/// Returns distance to the given weights.
pub fn distance(&self, weights: &[f64]) -> f64 {
self.storage.distance(self.weights.as_slice(), weights)
}
/// Updates hit statistics.
pub fn new_hit(&mut self, time: usize) {
self.total_hits += 1;
if self.last_hits.get(0).map_or(true, |last_time| *last_time != time) {
self.last_hits.push_front(time);
self.last_hits.truncate(self.hit_memory_size);
}
}
/// Checks whether time is considered old.
pub fn is_old(&self, time: usize) -> bool {
(time as i32 - self.hit_memory_size as i32) > self.creation_time as i32
}
}
impl<I: Input, S: Storage<Item = I>> Clone for Topology<I, S> {
fn clone(&self) -> Self {
Self {
dimension: self.dimension,
right: self.right.clone(),
left: self.left.clone(),
up: self.up.clone(),
down: self.down.clone(),
}
}
}
impl<I: Input, S: Storage<Item = I>> Topology<I, S> {
/// Creates an empty cell at given coordinate.
pub fn empty(dimension: usize) -> Self {
Self { dimension, right: None, left: None, up: None, down: None }
}
/// Gets neighbors.
pub fn neighbours(&self) -> impl Iterator<Item = &NodeLink<I, S>> {
TopologyIterator { topology: self, state: 0 }
}
/// Checks if the cell is at the boundary of the network.
pub fn is_boundary(&self) -> bool {
self.right.is_none() || self.left.is_none() || self.up.is_none() || self.down.is_none()
}
}
struct TopologyIterator<'a, I: Input, S: Storage<Item = I>> {
topology: &'a Topology<I, S>,
state: usize,
}
impl<'a, I: Input, S: Storage<Item = I>> TopologyIterator<'a, I, S> {
fn transition(&mut self, state: usize, node: Option<&'a NodeLink<I, S>>) -> Result<(), Option<&'a NodeLink<I, S>>> {
if self.state == state {
self.state = state + 1;
if node.is_some() {
return Err(node);
}
}
Ok(())
}
fn iterate(&mut self) -> Result<(), Option<&'a NodeLink<I, S>>> {
self.transition(0, self.topology.left.as_ref())?;
self.transition(1, self.topology.right.as_ref())?;
self.transition(2, self.topology.down.as_ref())?;
self.transition(3, self.topology.up.as_ref())?;
Ok(())
}
}
impl<'a, I: Input, S: Storage<Item = I>> Iterator for TopologyIterator<'a, I, S> {
type Item = &'a NodeLink<I, S>;
fn next(&mut self) -> Option<Self::Item> {
if let Err(node) = self.iterate() {
node
} else {
None
}
}
}
|
pub mod errors;
pub mod imp;
pub mod decode_pixel;
pub mod encode_pixel; |
pub fn run() {
hello_world(&5);
let status = is_fadil("Fadil");
println!("{}", status);
// ? Closure
let add_nums = |n1: i32, n2: i32| n1 + n2;
println!("C Sum: {}", add_nums(7, 8));
}
fn hello_world(n: &i32) {
for i in 1..*n {
println!("Hello world on index {}", i);
}
println!("{}", n);
}
fn is_fadil(value: &str) -> bool {
println!("{}", value);
if value == "Fadil" {
return true;
}
return false;
}
|
use super::{comparison_operator::ComparisonOperator, expression::Expression};
use std::sync::Arc;
#[derive(Clone, Debug, PartialEq)]
pub struct ComparisonOperation {
operator: ComparisonOperator,
lhs: Arc<Expression>,
rhs: Arc<Expression>,
}
impl ComparisonOperation {
pub fn new(
operator: ComparisonOperator,
lhs: impl Into<Expression>,
rhs: impl Into<Expression>,
) -> Self {
Self {
operator,
lhs: Arc::new(lhs.into()),
rhs: Arc::new(rhs.into()),
}
}
pub fn operator(&self) -> ComparisonOperator {
self.operator
}
pub fn lhs(&self) -> &Expression {
&self.lhs
}
pub fn rhs(&self) -> &Expression {
&self.rhs
}
}
|
use std::path::Path;
use std::fs::File;
use std::io::{BufRead, BufReader};
use super::triangle::Triangle;
use super::point::Point;
pub struct MDL {
pub triangles: Vec<Triangle>,
pub points: Vec<Point>,
}
impl MDL {
pub fn open (file_path: &str) -> MDL {
let location = Path::new(file_path);
let file = File::open(&location).unwrap();
let reader = BufReader::new(file);
let mut points: Vec<Point> = Vec::new();
let mut triangles: Vec<Triangle> = Vec::new();
for (index, line) in reader.lines().enumerate() {
let mut line = line.unwrap();
line = line.trim().to_string();
if line.is_empty() {
continue
}
let first_char = line.chars().next().unwrap();
match first_char {
'p' => {
let mut numbers: [i64; 3] = [0, 0, 0];
let mut numbers_found: u8 = 0;
for (index, item) in line.split_whitespace().skip(1).enumerate() {
let number = item.parse::<i64>().unwrap();
numbers[index] = number;
numbers_found += 1;
}
if numbers_found != 3 {
panic!("\nError at {}:{}\nLine must contain 3 numbers but obtained: {}", file_path, index + 1, line)
}
points.push(
Point::new(
numbers[0],
numbers[1],
numbers[2],
)
)
},
't' => {
let mut numbers: [usize; 3] = [0, 0, 0];
let mut numbers_found: u8 = 0;
for (index, item) in line.split_whitespace().skip(1).enumerate() {
let number = item.parse::<usize>().unwrap();
numbers[index] = number;
numbers_found += 1;
}
if numbers_found != 3 {
panic!("\nError at {}:{}\nLine must contain 3 numbers but obtained: {}", file_path, index + 1, line)
}
triangles.push(
Triangle::new(
points[numbers[0]],
points[numbers[1]],
points[numbers[2]],
)
)
},
_ => continue
}
}
MDL {
triangles: triangles,
points: points,
}
}
} |
use std::path::{Path, PathBuf};
// https://stackoverflow.com/questions/54267608/expand-tilde-in-rust-path-idiomatically
pub fn expand_home<P: AsRef<Path>>(path_user_input: P) -> Option<PathBuf> {
let p = path_user_input.as_ref();
if !p.starts_with("~") {
return Some(p.to_path_buf());
}
if p == Path::new("~") {
return dirs::home_dir();
}
dirs::home_dir().map(|mut h| {
if h == Path::new("/") {
// Corner case: `h` root directory;
// don't prepend extra `/`, just drop the tilde.
p.strip_prefix("~").unwrap().to_path_buf()
} else {
h.push(p.strip_prefix("~/").unwrap());
h
}
})
}
|
use super::con_back::Command;
use super::*;
use conrod_core as cc;
use gfx_hal::{
command::CommandBuffer,
pso::{Primitive, VertexInputRate},
};
pub struct UiPipeline<B: Backend> {
device: Arc<Dev<B>>,
pub layouts: ManuallyDrop<<B as Backend>::PipelineLayout>,
pub gfx_pipeline: ManuallyDrop<<B as Backend>::GraphicsPipeline>,
}
impl<B: Backend + BackendExt> UiPipeline<B> {
pub fn create(
device: Arc<Dev<B>>,
render_area: Rect,
render_pass: &<B as Backend>::RenderPass,
vertex_compile_artifact: shaderc::CompilationArtifact,
fragment_compile_artifact: shaderc::CompilationArtifact,
descriptor_set_layouts: &Vec<<B as Backend>::DescriptorSetLayout>,
) -> Result<UiPipeline<B>, Error> {
let vertex_shader_module = unsafe {
device
.create_shader_module(vertex_compile_artifact.as_binary())
.map_err(|_| "Couldn't make the vertex module")?
};
let fragment_shader_module = unsafe {
device
.create_shader_module(fragment_compile_artifact.as_binary())
.map_err(|_| "Couldn't make the fragment module")?
};
let (vs_entry, fs_entry) = (
EntryPoint {
entry: "main",
module: &vertex_shader_module,
specialization: Specialization::EMPTY,
},
EntryPoint {
entry: "main",
module: &fragment_shader_module,
specialization: Specialization::EMPTY,
},
);
let shaders = GraphicsShaderSet {
vertex: vs_entry,
hull: None,
domain: None,
geometry: None,
fragment: Some(fs_entry),
};
let input_assembler = InputAssemblerDesc::new(Primitive::TriangleList);
let vertex_buffers: Vec<VertexBufferDesc> = vec![VertexBufferDesc {
binding: 0,
stride: (size_of::<f32>() * (2 + 2) + 2 * size_of::<u32>()) as ElemStride,
rate: VertexInputRate::Vertex,
}];
let position_attribute = AttributeDesc {
location: 0,
binding: 0,
element: Element {
format: Format::Rg32Sfloat,
offset: 0,
},
};
let uv_attribute = AttributeDesc {
location: 1,
binding: 0,
element: Element {
format: Format::Rg32Sfloat,
offset: (size_of::<f32>() * 2) as ElemOffset,
},
};
let mode_attribute = AttributeDesc {
location: 2,
binding: 0,
element: Element {
format: Format::R32Uint,
offset: (size_of::<f32>() * 4) as ElemOffset,
},
};
let color_attribute = AttributeDesc {
location: 3,
binding: 0,
element: Element {
format: Format::Rgba8Unorm,
offset: (size_of::<f32>() * 4 + size_of::<u32>()) as ElemOffset,
},
};
let attributes: Vec<AttributeDesc> = vec![
position_attribute,
color_attribute,
mode_attribute,
uv_attribute,
];
let rasterizer = Rasterizer {
depth_clamping: false,
polygon_mode: PolygonMode::Fill,
cull_face: Face::NONE, // Face::BACK,
front_face: FrontFace::Clockwise,
depth_bias: None,
conservative: false,
};
let depth_stencil = DepthStencilDesc {
depth: None,
depth_bounds: false,
stencil: None,
};
let blender = BlendDesc {
logic_op: None,
targets: vec![ColorBlendDesc {
mask: ColorMask::ALL,
blend: Some(BlendState::ALPHA),
}],
};
let baked_states = BakedStates {
viewport: Some(Viewport {
rect: render_area,
depth: (0.0..1.0),
}),
scissor: None,
blend_color: None,
depth_bounds: None,
};
let push_constants = vec![(ShaderStageFlags::VERTEX, 0..8)]; //needs to be divisible by 4 for dx12?
let layout = unsafe {
device
.create_pipeline_layout(descriptor_set_layouts, push_constants)
.map_err(|_| "Couldn't create a pipeline layout")?
};
let gfx_pipeline = {
let desc = GraphicsPipelineDesc {
shaders,
rasterizer,
vertex_buffers,
attributes,
input_assembler,
blender,
depth_stencil,
multisampling: None,
baked_states,
layout: &layout,
subpass: Subpass {
index: 0,
main_pass: render_pass,
},
flags: PipelineCreationFlags::empty(),
parent: BasePipeline::None,
};
unsafe {
device.create_graphics_pipeline(&desc, None).map_err(|e| {
error!("{}", e);
"Couldn't create a graphics pipeline!"
})?
}
};
unsafe {
device.destroy_shader_module(vertex_shader_module);
device.destroy_shader_module(fragment_shader_module);
}
Ok(UiPipeline {
device,
layouts: ManuallyDrop::new(layout),
gfx_pipeline: ManuallyDrop::new(gfx_pipeline),
})
}
pub fn execute<'a>(
&mut self,
encoder: &mut impl CommandBuffer<B>,
resource_manager: &mut ResourceManager<B>,
vertex_buffers: &[BufferBundle<B>],
render_area: Rect,
cmds: &[Command],
) {
unsafe {
let vert = vertex_buffers.iter().map(|b| (b.buffer.deref(), 0));
encoder.bind_graphics_pipeline(&self.gfx_pipeline);
encoder.bind_vertex_buffers(0, vert);
// encoder.bind_index_buffer(index_buffer);
// encoder.bind_graphics_descriptor_sets(&self.layout, 0, Some(&self.descriptor_sets[next_descriptor]), &[], );
resource_manager.uniform_buffers[3]
.write(
&self.device,
0,
&[
(render_area.w as f32).to_bits(),
(render_area.h as f32).to_bits(),
],
)
.expect("couldn't write to uniform buffer");
let mut last_tex = None;
for cmd in cmds.iter() {
if last_tex.is_none() || (cmd.texture_id.is_some() && cmd.texture_id != last_tex) {
last_tex = cmd.texture_id;
let id = cmd.texture_id.unwrap_or(Id::new(0));
let desc = if let Some(desc) = resource_manager.get_descriptor_set(id) {
desc
} else {
resource_manager.get_or_write_descriptor_set(id).log();
resource_manager.get_descriptor_set(id).unwrap()
};
encoder.bind_graphics_descriptor_sets(
&self.layouts,
0,
vec![desc, &resource_manager.uniform_buffer_descs[3]],
&[],
);
}
let sr = cmd.clip_rect;
let scissor = calc_scissor(sr, render_area);
encoder.set_scissors(0, Some(scissor));
// encoder.draw_indexed(0..6, 0, 0..1);
encoder.draw(cmd.vtx_offset..cmd.vtx_offset + cmd.elem_count, 0..1);
}
}
}
}
impl<B: Backend> Drop for UiPipeline<B> {
fn drop(&mut self) {
unsafe {
self.device
.destroy_pipeline_layout(ManuallyDrop::take(&mut self.layouts));
self.device
.destroy_graphics_pipeline(ManuallyDrop::take(&mut self.gfx_pipeline));
}
}
}
fn calc_scissor(sr: cc::Rect, extent: Rect) -> Rect {
// return extent;
Rect {
x: (sr.x.start.round() as i16).max(extent.x),
y: (-sr.y.end.round() as i16).max(extent.y),
w: ((sr.x.end - sr.x.start).max(0.0).round() as i16).min(extent.w),
h: ((sr.y.end - sr.y.start).max(0.0).round() as i16).min(extent.h),
}
}
|
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate rmp_serde as rmps;
use serde::{Deserialize, Serialize};
use chrono::{DateTime, Utc};
#[derive(Debug, PartialEq, Deserialize, Serialize)]
enum LogLevel {
Debug,
Info,
Warning,
Error,
Fatal,
}
#[derive(Debug, PartialEq, Deserialize, Serialize)]
struct LogRecord {
level: LogLevel,
timestamp: DateTime<Utc>,
category: String,
message: String,
}
impl LogRecord {
fn debug(cat: &str, msg: &str) -> Self {
Self {
level: LogLevel::Debug,
timestamp: Utc::now(),
category: cat.to_string(),
message: msg.to_string(),
}
}
}
fn main() {
println!("Hello, world!");
}
#[cfg(test)]
mod tests {
use crate::*;
use rmp;
use rmps::{Deserializer, Serializer};
use std::io::Cursor;
#[test]
fn usage_rmp_basic() {
let mut buf = Vec::new();
let expect = true;
rmp::encode::write_bool(&mut buf, expect).unwrap();
assert_eq!([0xc3], buf[..]);
assert_eq!(expect, rmp::decode::read_bool(&mut &buf[..]).unwrap());
}
#[test]
fn usage_rmp_struct() {
let value = LogRecord::debug("test.dummy", "hellow world");
let buf = rmp_serde::to_vec(&value).unwrap();
let cur = Cursor::new(&buf[..]);
let mut de = Deserializer::new(cur);
let actual: LogRecord = Deserialize::deserialize(&mut de).unwrap();
assert_eq!(&value, &actual);
}
}
|
use crate::*;
pub fn init_process(globals: &mut Globals) -> Value {
let id = globals.get_ident_id("Process");
let class = ClassRef::from(id, globals.builtins.object);
let mut obj = Value::class(globals, class);
globals.add_builtin_class_method(obj, "clock_gettime", clock_gettime);
let id = globals.get_ident_id("CLOCK_MONOTONIC");
obj.set_var(id, Value::fixnum(0));
obj
}
// Class methods
fn clock_gettime(vm: &mut VM, _: Value, args: &Args) -> VMResult {
vm.check_args_num(args.len(), 1)?;
let duration = vm.globals.instant.elapsed();
Ok(Value::flonum(duration.as_secs_f64()))
}
|
#[derive(Debug, PartialEq, Eq, Clone)]
/// An identifier
pub struct Ident<T>(T);
impl<T> AsRef<str> for Ident<T>
where
T: AsRef<str>,
{
fn as_ref(&self) -> &str {
self.0.as_ref()
}
}
impl<T> PartialEq<str> for &Ident<T>
where
T: AsRef<str>,
{
fn eq(&self, other: &str) -> bool {
self.0.as_ref().eq(other)
}
}
impl<'a> From<&'a str> for Ident<&'a str> {
fn from(s: &'a str) -> Self {
Ident(s)
}
}
impl<T> ToString for Ident<T>
where
T: AsRef<str>,
{
fn to_string(&self) -> String {
self.0.as_ref().to_string()
}
}
impl<T> From<Ident<T>> for String
where
T: ToString,
{
fn from(id: Ident<T>) -> Self {
id.0.to_string()
}
}
|
#[macro_use] extern crate itertools;
mod point;
use self::point::Point;
use std::f64::consts::PI;
use std::cmp;
extern crate rayon;
use self::rayon::prelude::*;
mod color;
pub trait Turtle {
fn forward(&mut self, d: f64);
fn turn(&mut self, a: f64);
fn push(&mut self);
fn pop(&mut self);
fn turn_right(&mut self) {
self.turn(-PI/2.);
}
fn turn_left(&mut self) {
self.turn(PI/2.);
}
}
#[derive(Clone, Debug)]
struct State {
position: Point,
direction: f64,
}
pub struct Canvas {
paths: Vec<Vec<Point>>,
state: State,
stack: Vec<State>,
}
impl Turtle for Canvas {
fn forward(&mut self, d: f64) {
self.state.position += Point::step(d, self.state.direction);
self.paths.last_mut().unwrap().push(self.state.position.clone());
}
fn turn(&mut self, a: f64) {
self.state.direction += a;
}
fn push(&mut self) {
self.stack.push(self.state.clone());
}
fn pop(&mut self) {
self.state = self.stack.pop().unwrap(); // panics for ill defined l systems
self.paths.push(Vec::new());
self.paths.last_mut().unwrap().push(self.state.position.clone());
}
}
impl Canvas {
pub fn new() -> Canvas {
let start = Point::new(0., 0.);
let points = vec![start.clone()];
let paths = vec![points];
let state = State {
position: start,
direction: 0.0,
};
Canvas {
paths,
state,
stack: Vec::new(),
}
}
fn bounds(&self) -> (f64, f64, f64, f64) {
let mut max_x: f64 = -1./0.; // -inf
let mut max_y: f64 = -1./0.; // -inf
let mut min_x: f64 = 1./0.; // inf
let mut min_y: f64 = 1./0.; // inf
for p in &self.paths {
max_x = max_x.max(p.iter().map(|p| p.x).fold(-1./0. /* -inf */, f64::max));
max_y = max_y.max(p.iter().map(|p| p.y).fold(-1./0. /* -inf */, f64::max));
min_x = min_x.min(p.iter().map(|p| p.x).fold(1./0. /* inf */, f64::min));
min_y = min_y.min(p.iter().map(|p| p.y).fold(1./0. /* inf */, f64::min));
}
let w = max_x - min_x;
max_x += 0.1*w;
min_x -= 0.1*w;
let h = max_y - min_y;
max_y += 0.1*h;
min_y -= 0.1*h;
(min_x, min_y, max_x, max_y)
}
fn bound_rect(&self, points: [&Point; 4]) -> (f64, f64, f64, f64) {
let max_x = points.iter().map(|p| p.x).fold(-1./0. /* -inf */, f64::max);
let max_y = points.iter().map(|p| p.y).fold(-1./0. /* -inf */, f64::max);
let min_x = points.iter().map(|p| p.x).fold(1./0. /* inf */, f64::min);
let min_y = points.iter().map(|p| p.y).fold(1./0. /* inf */, f64::min);
(min_x, min_y, max_x, max_y)
}
pub fn render(&self, resolution: (u32, u32)) -> Vec<u8> {
let x = resolution.0;
let y = resolution.1;
let (min_x, min_y, max_x, max_y) = self.bounds();
let w = max_x - min_x;
let h = max_y - min_y;
let scale = f64::min(x as f64 / w, y as f64 / h);
let scale_r = 1. / scale;
let x_offset = x as f64 - w * scale;
let y_offset = y as f64 - h * scale;
let min_x = min_x - x_offset / 2. * scale_r;
let min_y = min_y - y_offset / 2. * scale_r;
let w = max_x - min_x;
let h = max_y - min_y;
// let scale = f64::min(x as f64 / w, y as f64 / h);
// let scale_r = 1. / scale;
let stroke = cmp::min(cmp::min(x, y) / 1000 + 1, 3);
let stroke_r = stroke as f64 * scale_r;
let segments = self.paths.iter().map(|p| {p.windows(2)});
let cell_lateral_count = (segments.len() as f64).sqrt() as usize + 1;
let cell_w = w / cell_lateral_count as f64;
let cell_h = h / cell_lateral_count as f64;
let mut cell_list: Vec<Vec<Vec<usize>>> = vec![vec![Vec::new(); cell_lateral_count+1]; cell_lateral_count+1];
let mut ctr: usize = 0;
let mut rects: Vec<(Point, Point, Point, Point)> = Vec::new();
for path in segments {
for line in path {
if let &[ref a, ref b] = line {
let bearing = (a.y-b.y).atan2(a.x-b.x);
let p1 = a.clone() + Point::step(stroke_r, bearing + PI/2.) + Point::step(stroke_r, bearing);
let p2 = a.clone() + Point::step(stroke_r, bearing - PI/2.) + Point::step(stroke_r, bearing);
let p3 = b.clone() + Point::step(stroke_r, bearing - PI/2.) - Point::step(stroke_r, bearing);
let p4 = b.clone() + Point::step(stroke_r, bearing + PI/2.) - Point::step(stroke_r, bearing);
let (min_x_rect, min_y_rect, max_x_rect, max_y_rect) = self.bound_rect([&p1, &p2, &p3, &p4]);
let cell_start_x = ((min_x_rect - min_x) / cell_w) as usize;
let cell_start_y = ((min_y_rect - min_y) / cell_h) as usize;
let cell_stop_x = ((max_x_rect - min_x) / cell_w) as usize;
let cell_stop_y = ((max_y_rect - min_y) / cell_h) as usize;
for x in cell_start_x..=cell_stop_x {
for y in cell_start_y..=cell_stop_y {
if x < cell_lateral_count && y < cell_lateral_count {
cell_list[x][y].push(ctr.clone());
}
}
}
ctr += 1;
rects.push((p1, p2, p3, p4));
}
}
}
let pixels: Vec<(i32, i32)> = iproduct!(0..y as i32, 0..x as i32).collect();
pixels.par_iter()
.map(|&(j, i)| {
let mut color = vec![255, 255, 255, 0];
let q = Point::new(
i as f64 * scale_r + min_x,
j as f64 * scale_r + min_y
);
let cell_x = ((q.x - min_x) / cell_w) as usize;
let cell_y = ((q.y - min_y) / cell_h) as usize;
if cell_x < cell_lateral_count && cell_y < cell_lateral_count {
for &n in cell_list[cell_x][cell_y].iter() {
let (ref p1, ref p2, ref p3, ref p4) = rects[n];
if q.in_rect(&p1, &p2, &p3, &p4) {
let progress = n as f64 / rects.len() as f64;
let hsv = color::HSV(progress, 1., 1.);
let color::RGB(r, g, b) = hsv.to_rgb();
color = vec![(r * 255.) as u8, (g * 255.) as u8, (b * 255.) as u8, 255];
break
}
}
}
color
})
.flatten()
.collect()
}
// fn ascii(&self) -> String {
//
// }
// fn svg(&self) -> String {
//
// }
}
|
#[doc = "Register `C2CR` reader"]
pub type R = crate::R<C2CR_SPEC>;
#[doc = "Register `C2CR` writer"]
pub type W = crate::W<C2CR_SPEC>;
#[doc = "Field `PG` reader - Programming"]
pub type PG_R = crate::BitReader<PG_A>;
#[doc = "Programming\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PG_A {
#[doc = "0: Flash programming disabled"]
Disabled = 0,
#[doc = "1: Flash programming enabled"]
Enabled = 1,
}
impl From<PG_A> for bool {
#[inline(always)]
fn from(variant: PG_A) -> Self {
variant as u8 != 0
}
}
impl PG_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> PG_A {
match self.bits {
false => PG_A::Disabled,
true => PG_A::Enabled,
}
}
#[doc = "Flash programming disabled"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == PG_A::Disabled
}
#[doc = "Flash programming enabled"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == PG_A::Enabled
}
}
#[doc = "Field `PG` writer - Programming"]
pub type PG_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, PG_A>;
impl<'a, REG, const O: u8> PG_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Flash programming disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(PG_A::Disabled)
}
#[doc = "Flash programming enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(PG_A::Enabled)
}
}
#[doc = "Field `PER` reader - Page erase"]
pub type PER_R = crate::BitReader<PER_A>;
#[doc = "Page erase\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PER_A {
#[doc = "0: Page erase disabled"]
Disabled = 0,
#[doc = "1: Page erase enabled"]
Enabled = 1,
}
impl From<PER_A> for bool {
#[inline(always)]
fn from(variant: PER_A) -> Self {
variant as u8 != 0
}
}
impl PER_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> PER_A {
match self.bits {
false => PER_A::Disabled,
true => PER_A::Enabled,
}
}
#[doc = "Page erase disabled"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == PER_A::Disabled
}
#[doc = "Page erase enabled"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == PER_A::Enabled
}
}
#[doc = "Field `PER` writer - Page erase"]
pub type PER_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, PER_A>;
impl<'a, REG, const O: u8> PER_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Page erase disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(PER_A::Disabled)
}
#[doc = "Page erase enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(PER_A::Enabled)
}
}
#[doc = "Field `MER` reader - Mass erase"]
pub type MER_R = crate::BitReader<MER_A>;
#[doc = "Mass erase\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MER_A {
#[doc = "0: No mass erase"]
NoErase = 0,
#[doc = "1: Trigger mass erase"]
MassErase = 1,
}
impl From<MER_A> for bool {
#[inline(always)]
fn from(variant: MER_A) -> Self {
variant as u8 != 0
}
}
impl MER_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> MER_A {
match self.bits {
false => MER_A::NoErase,
true => MER_A::MassErase,
}
}
#[doc = "No mass erase"]
#[inline(always)]
pub fn is_no_erase(&self) -> bool {
*self == MER_A::NoErase
}
#[doc = "Trigger mass erase"]
#[inline(always)]
pub fn is_mass_erase(&self) -> bool {
*self == MER_A::MassErase
}
}
#[doc = "Field `MER` writer - Mass erase"]
pub type MER_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, MER_A>;
impl<'a, REG, const O: u8> MER_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "No mass erase"]
#[inline(always)]
pub fn no_erase(self) -> &'a mut crate::W<REG> {
self.variant(MER_A::NoErase)
}
#[doc = "Trigger mass erase"]
#[inline(always)]
pub fn mass_erase(self) -> &'a mut crate::W<REG> {
self.variant(MER_A::MassErase)
}
}
#[doc = "Field `PNB` reader - Page number selection"]
pub type PNB_R = crate::FieldReader;
#[doc = "Field `PNB` writer - Page number selection"]
pub type PNB_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 7, O>;
#[doc = "Field `STRT` reader - Start"]
pub type STRT_R = crate::BitReader<STRTR_A>;
#[doc = "Start\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum STRTR_A {
#[doc = "0: Options modification completed or idle"]
Done = 0,
}
impl From<STRTR_A> for bool {
#[inline(always)]
fn from(variant: STRTR_A) -> Self {
variant as u8 != 0
}
}
impl STRT_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<STRTR_A> {
match self.bits {
false => Some(STRTR_A::Done),
_ => None,
}
}
#[doc = "Options modification completed or idle"]
#[inline(always)]
pub fn is_done(&self) -> bool {
*self == STRTR_A::Done
}
}
#[doc = "Start\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum STRTW_AW {
#[doc = "1: Trigger options programming operation"]
Start = 1,
}
impl From<STRTW_AW> for bool {
#[inline(always)]
fn from(variant: STRTW_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Field `STRT` writer - Start"]
pub type STRT_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, STRTW_AW>;
impl<'a, REG, const O: u8> STRT_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Trigger options programming operation"]
#[inline(always)]
pub fn start(self) -> &'a mut crate::W<REG> {
self.variant(STRTW_AW::Start)
}
}
#[doc = "Field `FSTPG` reader - Fast programming"]
pub type FSTPG_R = crate::BitReader<FSTPG_A>;
#[doc = "Fast programming\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FSTPG_A {
#[doc = "0: Fast programming disabled"]
Disabled = 0,
#[doc = "1: Fast programming enabled"]
Enabled = 1,
}
impl From<FSTPG_A> for bool {
#[inline(always)]
fn from(variant: FSTPG_A) -> Self {
variant as u8 != 0
}
}
impl FSTPG_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> FSTPG_A {
match self.bits {
false => FSTPG_A::Disabled,
true => FSTPG_A::Enabled,
}
}
#[doc = "Fast programming disabled"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == FSTPG_A::Disabled
}
#[doc = "Fast programming enabled"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == FSTPG_A::Enabled
}
}
#[doc = "Field `FSTPG` writer - Fast programming"]
pub type FSTPG_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, FSTPG_A>;
impl<'a, REG, const O: u8> FSTPG_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Fast programming disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(FSTPG_A::Disabled)
}
#[doc = "Fast programming enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(FSTPG_A::Enabled)
}
}
#[doc = "Field `EOPIE` reader - End of operation interrupt enable"]
pub type EOPIE_R = crate::BitReader<EOPIE_A>;
#[doc = "End of operation interrupt enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EOPIE_A {
#[doc = "0: End of program interrupt disable"]
Disabled = 0,
#[doc = "1: End of program interrupt enable"]
Enabled = 1,
}
impl From<EOPIE_A> for bool {
#[inline(always)]
fn from(variant: EOPIE_A) -> Self {
variant as u8 != 0
}
}
impl EOPIE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> EOPIE_A {
match self.bits {
false => EOPIE_A::Disabled,
true => EOPIE_A::Enabled,
}
}
#[doc = "End of program interrupt disable"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == EOPIE_A::Disabled
}
#[doc = "End of program interrupt enable"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == EOPIE_A::Enabled
}
}
#[doc = "Field `EOPIE` writer - End of operation interrupt enable"]
pub type EOPIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, EOPIE_A>;
impl<'a, REG, const O: u8> EOPIE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "End of program interrupt disable"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(EOPIE_A::Disabled)
}
#[doc = "End of program interrupt enable"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(EOPIE_A::Enabled)
}
}
#[doc = "Field `ERRIE` reader - Error interrupt enable"]
pub type ERRIE_R = crate::BitReader<ERRIE_A>;
#[doc = "Error interrupt enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ERRIE_A {
#[doc = "0: OPERR Error interrupt disable"]
Disabled = 0,
#[doc = "1: OPERR Error interrupt enable"]
Enabled = 1,
}
impl From<ERRIE_A> for bool {
#[inline(always)]
fn from(variant: ERRIE_A) -> Self {
variant as u8 != 0
}
}
impl ERRIE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> ERRIE_A {
match self.bits {
false => ERRIE_A::Disabled,
true => ERRIE_A::Enabled,
}
}
#[doc = "OPERR Error interrupt disable"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == ERRIE_A::Disabled
}
#[doc = "OPERR Error interrupt enable"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == ERRIE_A::Enabled
}
}
#[doc = "Field `ERRIE` writer - Error interrupt enable"]
pub type ERRIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, ERRIE_A>;
impl<'a, REG, const O: u8> ERRIE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "OPERR Error interrupt disable"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(ERRIE_A::Disabled)
}
#[doc = "OPERR Error interrupt enable"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(ERRIE_A::Enabled)
}
}
#[doc = "Field `RDERRIE` reader - RDERRIE"]
pub type RDERRIE_R = crate::BitReader<RDERRIE_A>;
#[doc = "RDERRIE\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RDERRIE_A {
#[doc = "0: PCROP read error interrupt disable"]
Disabled = 0,
#[doc = "1: PCROP read error interrupt enable"]
Enabled = 1,
}
impl From<RDERRIE_A> for bool {
#[inline(always)]
fn from(variant: RDERRIE_A) -> Self {
variant as u8 != 0
}
}
impl RDERRIE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> RDERRIE_A {
match self.bits {
false => RDERRIE_A::Disabled,
true => RDERRIE_A::Enabled,
}
}
#[doc = "PCROP read error interrupt disable"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == RDERRIE_A::Disabled
}
#[doc = "PCROP read error interrupt enable"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == RDERRIE_A::Enabled
}
}
#[doc = "Field `RDERRIE` writer - RDERRIE"]
pub type RDERRIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, RDERRIE_A>;
impl<'a, REG, const O: u8> RDERRIE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "PCROP read error interrupt disable"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(RDERRIE_A::Disabled)
}
#[doc = "PCROP read error interrupt enable"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(RDERRIE_A::Enabled)
}
}
impl R {
#[doc = "Bit 0 - Programming"]
#[inline(always)]
pub fn pg(&self) -> PG_R {
PG_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - Page erase"]
#[inline(always)]
pub fn per(&self) -> PER_R {
PER_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - Mass erase"]
#[inline(always)]
pub fn mer(&self) -> MER_R {
MER_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bits 3:9 - Page number selection"]
#[inline(always)]
pub fn pnb(&self) -> PNB_R {
PNB_R::new(((self.bits >> 3) & 0x7f) as u8)
}
#[doc = "Bit 16 - Start"]
#[inline(always)]
pub fn strt(&self) -> STRT_R {
STRT_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 18 - Fast programming"]
#[inline(always)]
pub fn fstpg(&self) -> FSTPG_R {
FSTPG_R::new(((self.bits >> 18) & 1) != 0)
}
#[doc = "Bit 24 - End of operation interrupt enable"]
#[inline(always)]
pub fn eopie(&self) -> EOPIE_R {
EOPIE_R::new(((self.bits >> 24) & 1) != 0)
}
#[doc = "Bit 25 - Error interrupt enable"]
#[inline(always)]
pub fn errie(&self) -> ERRIE_R {
ERRIE_R::new(((self.bits >> 25) & 1) != 0)
}
#[doc = "Bit 26 - RDERRIE"]
#[inline(always)]
pub fn rderrie(&self) -> RDERRIE_R {
RDERRIE_R::new(((self.bits >> 26) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - Programming"]
#[inline(always)]
#[must_use]
pub fn pg(&mut self) -> PG_W<C2CR_SPEC, 0> {
PG_W::new(self)
}
#[doc = "Bit 1 - Page erase"]
#[inline(always)]
#[must_use]
pub fn per(&mut self) -> PER_W<C2CR_SPEC, 1> {
PER_W::new(self)
}
#[doc = "Bit 2 - Mass erase"]
#[inline(always)]
#[must_use]
pub fn mer(&mut self) -> MER_W<C2CR_SPEC, 2> {
MER_W::new(self)
}
#[doc = "Bits 3:9 - Page number selection"]
#[inline(always)]
#[must_use]
pub fn pnb(&mut self) -> PNB_W<C2CR_SPEC, 3> {
PNB_W::new(self)
}
#[doc = "Bit 16 - Start"]
#[inline(always)]
#[must_use]
pub fn strt(&mut self) -> STRT_W<C2CR_SPEC, 16> {
STRT_W::new(self)
}
#[doc = "Bit 18 - Fast programming"]
#[inline(always)]
#[must_use]
pub fn fstpg(&mut self) -> FSTPG_W<C2CR_SPEC, 18> {
FSTPG_W::new(self)
}
#[doc = "Bit 24 - End of operation interrupt enable"]
#[inline(always)]
#[must_use]
pub fn eopie(&mut self) -> EOPIE_W<C2CR_SPEC, 24> {
EOPIE_W::new(self)
}
#[doc = "Bit 25 - Error interrupt enable"]
#[inline(always)]
#[must_use]
pub fn errie(&mut self) -> ERRIE_W<C2CR_SPEC, 25> {
ERRIE_W::new(self)
}
#[doc = "Bit 26 - RDERRIE"]
#[inline(always)]
#[must_use]
pub fn rderrie(&mut self) -> RDERRIE_W<C2CR_SPEC, 26> {
RDERRIE_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 = "Flash CPU2 control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`c2cr::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 [`c2cr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct C2CR_SPEC;
impl crate::RegisterSpec for C2CR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`c2cr::R`](R) reader structure"]
impl crate::Readable for C2CR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`c2cr::W`](W) writer structure"]
impl crate::Writable for C2CR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets C2CR to value 0xc000_0000"]
impl crate::Resettable for C2CR_SPEC {
const RESET_VALUE: Self::Ux = 0xc000_0000;
}
|
extern crate sdl2;
extern crate num;
use std::collections::vec_deque::VecDeque;
use super::scancodes::*;
use super::super::cpu::CPU;
use super::super::mem::Memory;
use super::super::bios::ByteBdaEntry;
#[derive(Clone,Copy)]
pub struct Keystroke
{
pub scancode: u8,
pub ascii: u8
}
const RSHIFT_FLAG: u8 = 0x1;
const RSHIFT_SCANCODE: u8 = 0x36;
const LSHIFT_FLAG: u8 = 0x2;
const LSHIFT_SCANCODE: u8 = 0x2a;
const CTRL_FLAG: u8 = 0x4;
const CTRL_SCANCODE: u8 = 0x1d;
const ALT_FLAG: u8 = 0x8;
const ALT_SCANCODE: u8 = 0x38;
/*const SCROLL_FLAG: u8 = 0x5;
const SCROLL_SCANCODE: u8 = 0x7E;
const NUMLOCK_FLAG: u8 = 0x6;
const NUMLOCK_SCANCODE: u8 = 0x77;
const INSERT_FLAG: u8 = 0x7;
const INSERT_SCANCODE: u8 = 0x52;*/
pub struct Keyboard
{
bios_queue: VecDeque<Keystroke>, // TODO: do we need a queue? It can actually never be filled with more than one element...
io_queue: VecDeque<u8>,
ppi_a: u8,
enable_irq: bool, // Disabled for BIOS wait_for_keystroke
shift_flags: ByteBdaEntry
}
impl Keystroke
{
pub fn new(scancode: u8, ascii: u8) -> Keystroke
{
Keystroke { scancode: scancode, ascii: ascii }
}
}
impl Keyboard
{
pub fn new() -> Keyboard
{
Keyboard
{
bios_queue: VecDeque::<Keystroke>::new(),
io_queue: VecDeque::<u8>::new(),
ppi_a: 0,
enable_irq: true,
shift_flags: ByteBdaEntry::new(0x17)
}
}
pub fn on_keydown(&mut self, cpu: &mut CPU, sdlk_opt: Option<sdl2::keyboard::Scancode>)
{
if let Some(sdlk) = sdlk_opt
{
if let Some(scancode) = sdlk_to_scancode(sdlk)
{
keyboard_print!("Pressed: scancode={:x}", scancode);
self.io_queue.push_back(scancode);
cpu.queue_hw_interrupt(0x9);
}
}
}
pub fn on_keyup(&mut self, cpu: &mut CPU, sdlk_opt: Option<sdl2::keyboard::Scancode>)
{
if let Some(sdlk) = sdlk_opt
{
if let Some(scancode) = sdlk_to_scancode(sdlk)
{
keyboard_print!("Released: scancode={:x}", scancode);
self.io_queue.push_back(scancode | 0x80);
cpu.queue_hw_interrupt(0x9);
}
}
}
pub fn bios_pump_keystrokes(&mut self, mem: &mut Memory)
{
while ! self.io_queue.is_empty()
{
let scancode = self.io_queue.pop_front().unwrap();
let is_released = scancode & 0x80 != 0;
let shift_flags = self.shift_flags.get(mem);
let is_shift_pressed = shift_flags & (RSHIFT_FLAG | LSHIFT_FLAG) != 0;
/* Shift flags handling */
{
let mut set_flag = |flag: u8, set: bool| // TODO: why mut?
{
let new_val = if set {shift_flags | flag } else { shift_flags & (flag ^ 0xff) };
self.shift_flags.set(mem, new_val)
};
match scancode & 0x7f
{
LSHIFT_SCANCODE => set_flag(LSHIFT_FLAG, !is_released),
RSHIFT_SCANCODE => set_flag(RSHIFT_FLAG, !is_released),
ALT_SCANCODE => set_flag(ALT_FLAG, !is_released),
CTRL_SCANCODE => set_flag(CTRL_FLAG, !is_released),
_ => ()
}
}
// Only consider the 'pressed' event
if is_released
{
continue
}
let ascii =
match scancode_to_ascii(scancode, is_shift_pressed)
{
Some(s) => s,
None => 0
};
self.bios_queue.push_back(Keystroke::new(scancode, ascii));
}
}
pub fn try_pop_keystroke(&mut self) -> Option<Keystroke>
{
/* We may encounter scancodes that cannot be used by the machine, so
* always check that we got something and loop if not */
self.bios_queue.pop_front()
}
pub fn check_keystroke(&mut self) -> Option<Keystroke>
{
match self.bios_queue.front()
{
Some(k) => Some(*k),
None => None
}
}
pub fn io_get_scancode(&mut self) -> Option<u8>
{
keyboard_print!("IO: Get scancode");
match self.io_queue.front()
{
Some(k) =>
{
keyboard_print!("Scancode {:02x}", k);
Some(*k)
}
None => None
}
}
pub fn set_ppi_a(&mut self, ppi_a: u8)
{
keyboard_print!("Set ppi_a to {:x}", ppi_a);
if ((self.ppi_a & 0x80) != 0) && ((ppi_a & 0x80) == 0)
{
// Keyboard was disabled and has been enabled: drop one entry from the IO queue
assert!(! self.io_queue.is_empty());
self.io_queue.pop_front();
}
self.ppi_a = ppi_a;
}
pub fn get_ppi_a(&self) -> u8
{
self.ppi_a
}
pub fn get_shift_flags(&self, mem: &Memory) -> u8
{
self.shift_flags.get(mem)
}
pub fn set_irq(&mut self, enabled: bool)
{
self.enable_irq = enabled;
}
}
|
fn main() {
let mut v : Vec<f64> = vec![1.1, 1.15, 5.5, 1.123, 2.0];
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
println!("{:?}", v);
} |
use serde::{Deserialize, Serialize};
use super::category_taxonomy;
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct Producer {
id: Option<String>,
name: Option<String>,
domain: Option<String>,
cat: Option<String>,
cattax: Option<category_taxonomy::CategoryTaxonomy>,
ext: Option<ProducerExt>,
}
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct ProducerExt {}
|
// q0056_merge_intervals
struct Solution;
impl Solution {
pub fn merge(intervals: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
if intervals.len() <= 1 {
return intervals;
}
let mut intervals = intervals;
Solution::sort(&mut intervals);
// println!("after soring: {:?}", intervals);
let mut ret = vec![];
let mut tmp = vec![intervals[0][0], intervals[0][1]];
for i in 1..intervals.len() {
if tmp[0] < intervals[i][0] && tmp[1] < intervals[i][0] {
ret.push(tmp.clone());
tmp[0] = intervals[i][0];
tmp[1] = intervals[i][1];
} else {
// tmp[0] = tmp[0].min(intervals[i][0]);
tmp[1] = tmp[1].max(intervals[i][1]);
}
}
ret.push(tmp);
ret
}
pub fn sort(itvl: &mut [Vec<i32>]) {
// println!("begin sort{:?}", itvl);
let l = itvl.len();
if l <= 1 {
return;
}
let mut j = 0; // 假设pivot最小
let pivot = itvl[l - 1][0];
// println!("pivot is {:?}", itvl[l-1]);
for i in 0..l - 1 {
// print!("compare {} {:?} ", i, itvl[i]);
if itvl[i][0] < pivot {
if i != j {
// print!("switch");
let t = std::mem::replace(&mut itvl[j], vec![]);
itvl[j] = std::mem::replace(&mut itvl[i], t);
}
j += 1;
}
// println!("");
}
if l - 1 != j {
let t = std::mem::replace(&mut itvl[j], vec![]);
itvl[j] = std::mem::replace(&mut itvl[l - 1], t);
}
// println!("sort {:?}", &itvl[0..j]);
Solution::sort(&mut itvl[0..j]);
// println!("after sort {:?}", &itvl[0..j]);
// println!("sort {:?}", &itvl[j+1..]);
Solution::sort(&mut itvl[j + 1..]);
// println!("after sort {:?}", &itvl[j+1..]);
}
}
#[cfg(test)]
mod tests {
use super::Solution;
#[test]
fn it_works() {
assert_eq!(
Solution::merge(vec![vec![1, 3], vec![2, 6], vec![8, 10], vec![15, 18]]),
vec![vec![1, 6], vec![8, 10], vec![15, 18]]
);
assert_eq!(
Solution::merge(vec![vec![1, 4], vec![4, 5]]),
vec![vec![1, 5]]
);
assert_eq!(
Solution::merge(vec![
vec![2, 3],
vec![4, 5],
vec![6, 7],
vec![8, 9],
vec![1, 10]
]),
vec![vec![1, 10]]
);
let empty: Vec<Vec<i32>> = vec![];
assert_eq!(Solution::merge(empty.clone()), empty);
}
#[test]
#[ignore]
fn sort() {
let mut t = vec![vec![1, 3], vec![2, 6], vec![8, 10], vec![15, 18]];
Solution::sort(&mut t);
let r = vec![vec![1, 3], vec![2, 6], vec![8, 10], vec![15, 18]];
assert_eq!(r, t);
// let mut t = vec![vec![2,3],vec![4,5],vec![6,7],vec![8,9],vec![1,10]];
// Solution::sort(&mut t);
// let r = vec![vec![1,10],vec![2,3],vec![4,5],vec![6,7],vec![8,9]];
// assert_eq!(r, t);
// let mut t = vec![vec![2,3],vec![4,5],vec![6,7],vec![8,9],vec![4,10]];
// Solution::sort(&mut t);
// let r = vec![vec![2,3],vec![4,5],vec![4,10],vec![6,7],vec![8,9]];
// assert_eq!(r, t);
// let mut t = vec![vec![2,3],vec![4,5],vec![6,7],vec![8,9],vec![1,10]];
// Solution::sort(&mut t);
// let r = vec![vec![1,10],vec![2,3],vec![4,5],vec![6,7],vec![8,9]];
// assert_eq!(r, t);
}
}
|
use glam::DAffine2;
use glam::DMat2;
use glam::DVec2;
use kurbo::Affine;
use kurbo::Shape as KurboShape;
use crate::intersection::intersect_quad_bez_path;
use crate::LayerId;
use crate::Quad;
use kurbo::BezPath;
use super::style;
use super::style::PathStyle;
use super::LayerData;
use serde::{Deserialize, Serialize};
use std::fmt::Write;
fn glam_to_kurbo(transform: DAffine2) -> Affine {
Affine::new(transform.to_cols_array())
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct Shape {
pub path: BezPath,
pub style: style::PathStyle,
pub render_index: i32,
pub solid: bool,
}
impl LayerData for Shape {
fn render(&mut self, svg: &mut String, transforms: &mut Vec<DAffine2>) {
let mut path = self.path.clone();
let transform = self.transform(transforms);
let inverse = transform.inverse();
if !inverse.is_finite() {
let _ = write!(svg, "<!-- SVG shape has an invalid transform -->");
return;
}
path.apply_affine(glam_to_kurbo(transform));
let _ = writeln!(svg, r#"<g transform="matrix("#);
inverse.to_cols_array().iter().enumerate().for_each(|(i, entry)| {
let _ = svg.write_str(&(entry.to_string() + if i != 5 { "," } else { "" }));
});
let _ = svg.write_str(r#")">"#);
let _ = write!(svg, r#"<path d="{}" {} />"#, path.to_svg(), self.style.render());
let _ = svg.write_str("</g>");
}
fn bounding_box(&self, transform: glam::DAffine2) -> Option<[DVec2; 2]> {
let mut path = self.path.clone();
if transform.matrix2 == DMat2::ZERO {
return None;
}
path.apply_affine(glam_to_kurbo(transform));
use kurbo::Shape;
let kurbo::Rect { x0, y0, x1, y1 } = path.bounding_box();
Some([(x0, y0).into(), (x1, y1).into()])
}
fn intersects_quad(&self, quad: Quad, path: &mut Vec<LayerId>, intersections: &mut Vec<Vec<LayerId>>) {
if intersect_quad_bez_path(quad, &self.path, self.solid) {
intersections.push(path.clone());
}
}
}
impl Shape {
pub fn transform(&self, transforms: &[DAffine2]) -> DAffine2 {
let start = match self.render_index {
-1 => 0,
x => (transforms.len() as i32 - x).max(0) as usize,
};
transforms.iter().skip(start).cloned().reduce(|a, b| a * b).unwrap_or(DAffine2::IDENTITY)
}
pub fn shape(sides: u8, style: PathStyle) -> Self {
use std::f64::consts::{FRAC_PI_2, TAU};
fn unit_rotation(theta: f64) -> DVec2 {
DVec2::new(theta.sin(), theta.cos())
}
let mut path = kurbo::BezPath::new();
let apothem_offset_angle = TAU / (sides as f64);
// Rotate odd sided shapes by 90 degrees
let offset = ((sides + 1) % 2) as f64 * FRAC_PI_2;
let relative_points = (0..sides).map(|i| apothem_offset_angle * i as f64 + offset).map(unit_rotation);
let min = relative_points.clone().reduce(|a, b| a.min(b)).unwrap_or_default();
let transform = DAffine2::from_scale_angle_translation(DVec2::ONE / 2., 0., -min / 2.);
let point = |vec: DVec2| kurbo::Point::new(vec.x, vec.y);
let mut relative_points = relative_points.map(|p| point(transform.transform_point2(p)));
path.move_to(relative_points.next().expect("Tried to create an ngon with 0 sides"));
relative_points.for_each(|p| path.line_to(p));
path.close_path();
Self {
path,
style,
render_index: 1,
solid: true,
}
}
pub fn rectangle(style: PathStyle) -> Self {
Self {
path: kurbo::Rect::new(0., 0., 1., 1.).to_path(0.01),
style,
render_index: 1,
solid: true,
}
}
pub fn ellipse(style: PathStyle) -> Self {
Self {
path: kurbo::Ellipse::from_rect(kurbo::Rect::new(0., 0., 1., 1.)).to_path(0.01),
style,
render_index: 1,
solid: true,
}
}
pub fn line(style: PathStyle) -> Self {
Self {
path: kurbo::Line::new((0., 0.), (1., 0.)).to_path(0.01),
style,
render_index: 1,
solid: true,
}
}
pub fn poly_line(points: Vec<impl Into<glam::DVec2>>, style: PathStyle) -> Self {
let mut path = kurbo::BezPath::new();
points
.into_iter()
.map(|v| v.into())
.map(|v: DVec2| kurbo::Point { x: v.x, y: v.y })
.enumerate()
.for_each(|(i, p)| if i == 0 { path.move_to(p) } else { path.line_to(p) });
Self {
path,
style,
render_index: 0,
solid: false,
}
}
}
|
use super::engine::ActionError;
use crate::cards::{BasicCard, BasicDeck, Suit};
use std::cmp::Ordering;
use std::slice;
#[derive(Debug)]
pub struct GameState {
/// current deck
pub deck: BasicDeck,
/// hands for each player
pub hands: [Vec<BasicCard>; 2],
/// score for each player
pub score: [usize; 2],
/// trump suit
pub trump: Suit,
/// card currently played
pub played: Option<BasicCard>,
/// player whose turn it is
pub active: usize,
/// number of rounds left in this phase
pub rounds_left: usize,
// currently revealed card, if any
pub revealed: Option<BasicCard>,
}
impl GameState {
/// Create a new round
pub fn new<T: Into<Option<usize>>>(player: T) -> GameState {
let mut deck = BasicDeck::new();
deck.shuffle();
let hands = [deck.draw_n(13).unwrap(), deck.draw_n(13).unwrap()];
let c = deck.draw().expect("deck has 26 cards left");
let trump = c.suit;
let score = [0, 0];
let active: usize = player.into().unwrap_or(0);
let played = None;
let rounds_left = 26;
GameState {
deck,
hands,
score,
trump,
active,
played,
rounds_left,
revealed: Some(c),
}
}
/// Return a mutable view of the player's hand.
pub fn player_view_mut(&mut self, player: usize) -> PlayerViewMut {
PlayerViewMut {
hand: &mut self.hands[player],
}
}
/// Return an immutable view of the player's hand.
pub fn player_view(&self, player: usize) -> PlayerView {
PlayerView::from_state(player, self)
}
/// Return true iff the leading player wins the trick
pub fn score_hand(&self, leading: &BasicCard, following: &BasicCard) -> Option<bool> {
if leading == following {
return None;
}
if leading.suit == self.trump {
Some(
following.suit != self.trump
|| leading.rank.ord_ace_high() > following.rank.ord_ace_high(),
)
} else {
Some(if following.suit == self.trump {
false
} else if following.suit != leading.suit {
true
} else {
leading.rank.ord_ace_high() > following.rank.ord_ace_high()
})
}
}
/// Reveal a new top card
pub fn draw(&mut self) -> Option<BasicCard> {
self.deck.draw()
}
/// Add score to specified player
pub fn increment_score(&mut self, player: usize, points: usize) {
self.score[player] += points;
}
/// Utility function to display cards in order.
///
/// Group by suit, trumps first, ordered within suit, ace_high
pub fn display_order(&self, c1: &BasicCard, c2: &BasicCard) -> Ordering {
let s1 = c1.suit.ord() + if c1.suit != self.trump { 4 } else { 0 };
let s2 = c2.suit.ord() + if c2.suit != self.trump { 4 } else { 0 };
(s1, c1.rank.ord_ace_high()).cmp(&(s2, c2.rank.ord_ace_high()))
}
}
pub struct PlayerViewMut<'a> {
hand: &'a mut Vec<BasicCard>,
}
impl<'a> PlayerViewMut<'a> {
pub fn has_card(&self, c: BasicCard) -> bool {
self.hand.contains(&c)
}
pub fn has_suit(&self, s: &Suit) -> bool {
self.hand.iter().any(|card| card.suit == *s)
}
pub fn add_card(&mut self, c: BasicCard) {
self.hand.push(c)
}
/// Remove the specified card from the players hand, returning an
/// error if the player didn't own the card.
pub fn remove_card(&mut self, c: &BasicCard) -> Result<(), ActionError> {
let p = self.hand.iter().position(|x| x == c);
match p {
Some(i) => {
self.hand.remove(i);
Ok(())
}
None => Err(ActionError::MissingCard),
}
}
}
pub struct PlayerView<'a> {
/// player's current hand
hand: &'a [BasicCard],
pub player: usize,
pub revealed: Option<BasicCard>,
pub leading_card: Option<BasicCard>,
pub trump: Suit,
pub score: [usize; 2],
}
impl<'a> PlayerView<'a> {
pub fn from_state(player: usize, gs: &GameState) -> PlayerView {
PlayerView {
player,
hand: &gs.hands[player],
revealed: gs.revealed,
leading_card: gs.played,
trump: gs.trump,
score: gs.score,
}
}
/// Return the set of cards playable in the current state.
///
/// Assumes the player is active.
pub fn playable_cards(&self) -> Vec<BasicCard> {
match self.leading_card {
// Second player must follow suit, if possible.
Some(ref c) if self.has_suit(&c.suit) =>
self.hand.iter().filter(|x| x.suit == c.suit)
.cloned().collect()
,
// Otherwise, can play anything
_ => self.hand.to_vec()
}
}
pub fn has_card(&self, c: BasicCard) -> bool {
self.hand.contains(&c)
}
pub fn has_suit(&self, s: &Suit) -> bool {
self.hand.iter().any(|card| card.suit == *s)
}
pub fn ord_suit(&self, s: Suit) -> u8 {
s.ord() + if s == self.trump { 4 } else { 0 }
}
/// Return true if the following card beats the leading card.
///
/// When cards are equivalent, return false.
pub fn wins_against(&self, leading: &BasicCard, follow: &BasicCard) -> bool {
if follow.suit == leading.suit {
follow.rank.ord_ace_high() > leading.rank.ord_ace_high()
} else {
follow.suit == self.trump
}
}
pub fn iter(&self) -> slice::Iter<BasicCard> {
self.hand.iter()
}
}
|
//! This module provides main application class.
mod events;
mod rustzx;
mod settings;
mod sound;
pub(crate) mod video;
// main re-export
pub use self::{rustzx::RustzxApp, settings::Settings};
|
use crate::config::template::config_template;
use config::NymConfig;
use serde::{Deserialize, Deserializer, Serialize};
use std::path::PathBuf;
use std::time;
pub mod persistence;
mod template;
// 'CLIENT'
const DEFAULT_LISTENING_PORT: u16 = 9001;
// 'DEBUG'
// where applicable, the below are defined in milliseconds
const DEFAULT_LOOP_COVER_STREAM_AVERAGE_DELAY: u64 = 1000;
const DEFAULT_MESSAGE_STREAM_AVERAGE_DELAY: u64 = 500;
const DEFAULT_AVERAGE_PACKET_DELAY: u64 = 200;
const DEFAULT_FETCH_MESSAGES_DELAY: u64 = 1000;
const DEFAULT_TOPOLOGY_REFRESH_RATE: u64 = 10_000;
const DEFAULT_TOPOLOGY_RESOLUTION_TIMEOUT: u64 = 5_000;
const DEFAULT_PACKET_FORWARDING_INITIAL_BACKOFF: u64 = 10_000; // 10s
const DEFAULT_PACKET_FORWARDING_MAXIMUM_BACKOFF: u64 = 300_000; // 5min
const DEFAULT_NUMBER_OF_HEALTHCHECK_TEST_PACKETS: u64 = 2;
const DEFAULT_NODE_SCORE_THRESHOLD: f64 = 0.0;
#[derive(Debug, Deserialize, PartialEq, Serialize, Clone, Copy)]
#[serde(deny_unknown_fields)]
pub enum SocketType {
TCP,
WebSocket,
None,
}
impl SocketType {
pub fn from_string<S: Into<String>>(val: S) -> Self {
let mut upper = val.into();
upper.make_ascii_uppercase();
match upper.as_ref() {
"TCP" => SocketType::TCP,
"WEBSOCKET" | "WS" => SocketType::WebSocket,
_ => SocketType::None,
}
}
}
#[derive(Debug, Default, Deserialize, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
client: Client,
socket: Socket,
#[serde(default)]
logging: Logging,
#[serde(default)]
debug: Debug,
}
impl NymConfig for Config {
fn template() -> &'static str {
config_template()
}
fn config_file_name() -> String {
"config.toml".to_string()
}
fn default_root_directory() -> PathBuf {
dirs::home_dir()
.expect("Failed to evaluate $HOME value")
.join(".nym")
.join("clients")
}
fn root_directory(&self) -> PathBuf {
self.client.nym_root_directory.clone()
}
fn config_directory(&self) -> PathBuf {
self.client
.nym_root_directory
.join(&self.client.id)
.join("config")
}
fn data_directory(&self) -> PathBuf {
self.client
.nym_root_directory
.join(&self.client.id)
.join("data")
}
}
impl Config {
pub fn new<S: Into<String>>(id: S) -> Self {
Config::default().with_id(id)
}
// builder methods
pub fn with_id<S: Into<String>>(mut self, id: S) -> Self {
let id = id.into();
if self.client.private_identity_key_file.as_os_str().is_empty() {
self.client.private_identity_key_file =
self::Client::default_private_identity_key_file(&id);
}
if self.client.public_identity_key_file.as_os_str().is_empty() {
self.client.public_identity_key_file =
self::Client::default_public_identity_key_file(&id);
}
self.client.id = id;
self
}
pub fn with_provider_id<S: Into<String>>(mut self, id: S) -> Self {
self.client.provider_id = id.into();
self
}
pub fn with_provider_auth_token<S: Into<String>>(mut self, token: S) -> Self {
self.client.provider_authtoken = Some(token.into());
self
}
pub fn with_custom_directory<S: Into<String>>(mut self, directory_server: S) -> Self {
self.client.directory_server = directory_server.into();
self
}
pub fn with_socket(mut self, socket_type: SocketType) -> Self {
self.socket.socket_type = socket_type;
self
}
pub fn with_port(mut self, port: u16) -> Self {
self.socket.listening_port = port;
self
}
// getters
pub fn get_config_file_save_location(&self) -> PathBuf {
self.config_directory().join(Self::config_file_name())
}
pub fn get_private_identity_key_file(&self) -> PathBuf {
self.client.private_identity_key_file.clone()
}
pub fn get_public_identity_key_file(&self) -> PathBuf {
self.client.public_identity_key_file.clone()
}
pub fn get_directory_server(&self) -> String {
self.client.directory_server.clone()
}
pub fn get_provider_id(&self) -> String {
self.client.provider_id.clone()
}
pub fn get_provider_auth_token(&self) -> Option<String> {
self.client.provider_authtoken.clone()
}
pub fn get_socket_type(&self) -> SocketType {
self.socket.socket_type
}
pub fn get_listening_port(&self) -> u16 {
self.socket.listening_port
}
// Debug getters
pub fn get_average_packet_delay(&self) -> time::Duration {
time::Duration::from_millis(self.debug.average_packet_delay)
}
pub fn get_loop_cover_traffic_average_delay(&self) -> time::Duration {
time::Duration::from_millis(self.debug.loop_cover_traffic_average_delay)
}
pub fn get_fetch_message_delay(&self) -> time::Duration {
time::Duration::from_millis(self.debug.fetch_message_delay)
}
pub fn get_message_sending_average_delay(&self) -> time::Duration {
time::Duration::from_millis(self.debug.message_sending_average_delay)
}
pub fn get_rate_compliant_cover_messages_disabled(&self) -> bool {
self.debug.rate_compliant_cover_messages_disabled
}
pub fn get_topology_refresh_rate(&self) -> time::Duration {
time::Duration::from_millis(self.debug.topology_refresh_rate)
}
pub fn get_topology_resolution_timeout(&self) -> time::Duration {
time::Duration::from_millis(self.debug.topology_resolution_timeout)
}
pub fn get_number_of_healthcheck_test_packets(&self) -> u64 {
self.debug.number_of_healthcheck_test_packets
}
pub fn get_node_score_threshold(&self) -> f64 {
self.debug.node_score_threshold
}
pub fn get_packet_forwarding_initial_backoff(&self) -> time::Duration {
time::Duration::from_millis(self.debug.packet_forwarding_initial_backoff)
}
pub fn get_packet_forwarding_maximum_backoff(&self) -> time::Duration {
time::Duration::from_millis(self.debug.packet_forwarding_maximum_backoff)
}
}
fn de_option_string<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
if s.is_empty() {
Ok(None)
} else {
Ok(Some(s))
}
}
#[derive(Debug, Deserialize, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Client {
/// ID specifies the human readable ID of this particular client.
id: String,
/// URL to the directory server.
directory_server: String,
/// Path to file containing private identity key.
private_identity_key_file: PathBuf,
/// Path to file containing public identity key.
public_identity_key_file: PathBuf,
/// provider_id specifies ID of the provider to which the client should send messages.
/// If initially omitted, a random provider will be chosen from the available topology.
provider_id: String,
/// A provider specific, optional, base58 stringified authentication token used for
/// communication with particular provider.
#[serde(deserialize_with = "de_option_string")]
provider_authtoken: Option<String>,
/// nym_home_directory specifies absolute path to the home nym Clients directory.
/// It is expected to use default value and hence .toml file should not redefine this field.
nym_root_directory: PathBuf,
}
impl Default for Client {
fn default() -> Self {
// there must be explicit checks for whether id is not empty later
Client {
id: "".to_string(),
directory_server: Self::default_directory_server(),
private_identity_key_file: Default::default(),
public_identity_key_file: Default::default(),
provider_id: "".to_string(),
provider_authtoken: None,
nym_root_directory: Config::default_root_directory(),
}
}
}
impl Client {
fn default_directory_server() -> String {
#[cfg(feature = "qa")]
return "https://qa-directory.nymtech.net".to_string();
#[cfg(feature = "local")]
return "http://localhost:8080".to_string();
"https://directory.nymtech.net".to_string()
}
fn default_private_identity_key_file(id: &str) -> PathBuf {
Config::default_data_directory(Some(id)).join("private_identity.pem")
}
fn default_public_identity_key_file(id: &str) -> PathBuf {
Config::default_data_directory(Some(id)).join("public_identity.pem")
}
}
#[derive(Debug, Deserialize, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Socket {
socket_type: SocketType,
listening_port: u16,
}
impl Default for Socket {
fn default() -> Self {
Socket {
socket_type: SocketType::None,
listening_port: DEFAULT_LISTENING_PORT,
}
}
}
#[derive(Debug, Deserialize, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Logging {}
impl Default for Logging {
fn default() -> Self {
Logging {}
}
}
#[derive(Debug, Deserialize, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Debug {
/// The parameter of Poisson distribution determining how long, on average,
/// sent packet is going to be delayed at any given mix node.
/// So for a packet going through three mix nodes, on average, it will take three times this value
/// until the packet reaches its destination.
/// The provided value is interpreted as milliseconds.
average_packet_delay: u64,
/// The parameter of Poisson distribution determining how long, on average,
/// it is going to take for another loop cover traffic message to be sent.
/// The provided value is interpreted as milliseconds.
loop_cover_traffic_average_delay: u64,
/// The uniform delay every which clients are querying the providers for received packets.
/// The provided value is interpreted as milliseconds.
fetch_message_delay: u64,
/// The parameter of Poisson distribution determining how long, on average,
/// it is going to take another 'real traffic stream' message to be sent.
/// If no real packets are available and cover traffic is enabled,
/// a loop cover message is sent instead in order to preserve the rate.
/// The provided value is interpreted as milliseconds.
message_sending_average_delay: u64,
/// Whether loop cover messages should be sent to respect message_sending_rate.
/// In the case of it being disabled and not having enough real traffic
/// waiting to be sent the actual sending rate is going be lower than the desired value
/// thus decreasing the anonymity.
rate_compliant_cover_messages_disabled: bool,
/// The uniform delay every which clients are querying the directory server
/// to try to obtain a compatible network topology to send sphinx packets through.
/// The provided value is interpreted as milliseconds.
topology_refresh_rate: u64,
/// During topology refresh, test packets are sent through every single possible network
/// path. This timeout determines waiting period until it is decided that the packet
/// did not reach its destination.
/// The provided value is interpreted as milliseconds.
topology_resolution_timeout: u64,
/// How many packets should be sent through each path during the healthcheck
number_of_healthcheck_test_packets: u64,
/// In the current healthcheck implementation, threshold indicating percentage of packets
/// node received during healthcheck. Node's score must be above that value to be
/// considered healthy.
node_score_threshold: f64,
/// Initial value of an exponential backoff to reconnect to dropped TCP connection when
/// forwarding sphinx packets.
/// The provided value is interpreted as milliseconds.
packet_forwarding_initial_backoff: u64,
/// Maximum value of an exponential backoff to reconnect to dropped TCP connection when
/// forwarding sphinx packets.
/// The provided value is interpreted as milliseconds.
packet_forwarding_maximum_backoff: u64,
}
impl Default for Debug {
fn default() -> Self {
Debug {
average_packet_delay: DEFAULT_AVERAGE_PACKET_DELAY,
loop_cover_traffic_average_delay: DEFAULT_LOOP_COVER_STREAM_AVERAGE_DELAY,
fetch_message_delay: DEFAULT_FETCH_MESSAGES_DELAY,
message_sending_average_delay: DEFAULT_MESSAGE_STREAM_AVERAGE_DELAY,
rate_compliant_cover_messages_disabled: false,
topology_refresh_rate: DEFAULT_TOPOLOGY_REFRESH_RATE,
topology_resolution_timeout: DEFAULT_TOPOLOGY_RESOLUTION_TIMEOUT,
number_of_healthcheck_test_packets: DEFAULT_NUMBER_OF_HEALTHCHECK_TEST_PACKETS,
node_score_threshold: DEFAULT_NODE_SCORE_THRESHOLD,
packet_forwarding_initial_backoff: DEFAULT_PACKET_FORWARDING_INITIAL_BACKOFF,
packet_forwarding_maximum_backoff: DEFAULT_PACKET_FORWARDING_MAXIMUM_BACKOFF,
}
}
}
#[cfg(test)]
mod client_config {
use super::*;
#[test]
fn after_saving_default_config_the_loaded_one_is_identical() {
// need to figure out how to do something similar but without touching the disk
// or the file system at all...
let temp_location = tempfile::tempdir().unwrap().path().join("config.toml");
let default_config = Config::default().with_id("foomp".to_string());
default_config
.save_to_file(Some(temp_location.clone()))
.unwrap();
let loaded_config = Config::load_from_file(Some(temp_location), None).unwrap();
assert_eq!(default_config, loaded_config);
}
}
|
use std::collections::HashSet;
pub fn anagrams_for<'a>(word: &str, possible_anagrams: &[&str]) -> HashSet<&'a str> {
// Get all letters in word
let mut found_word_buffer: Vec<char> = Vec::new();
let mut found_anagrams: Vec<&str> = Vec::new();
let mut anagrams_hs: HashSet<&'a str> = HashSet::new();
println!("\n\ntesting anagrams!");
for &possible_anagram in possible_anagrams {
// for every possible anagram
for char in word.chars() {
for pa_char in possible_anagram.chars() {
// check if letter exists
if char == pa_char {
// if yes, add letter to buffer array, and check if the next letter exists until all letters run out
found_word_buffer.push(pa_char);
}
}
}
// once letter run out, check if buffer array is the same size as the word.
if found_word_buffer.len() == word.len() {
// if it is, write the buffer array content to a list of found anagrams.
found_anagrams.push(possible_anagram);
anagrams_hs.insert(possible_anagram);
}
}
// once all possible anagrams are tested, resurn the found anagrams as a hashset
if found_anagrams.len() != 0 {
println!("anagrams found {}", found_anagrams.len());
for anagram in found_anagrams {
println!("{}", anagram);
}
} else {
println!("\n!!!No anagrams found!!!\n")
}
return anagrams_hs;
}
|
use std::fs;
use std::io;
const WIDTH: usize = 25;
const HEIGHT: usize = 6;
fn main() -> io::Result<()> {
let input = fs::read_to_string("input.txt")?;
let mut input = input.trim().chars().peekable();
let mut layers = Vec::new();
while input.peek().is_some() {
let mut layer: [[char; HEIGHT]; WIDTH] = [['x'; HEIGHT]; WIDTH];
for y in 0..HEIGHT {
for x in 0..WIDTH {
layer[x][y] = input.next().unwrap();
}
}
layers.push(layer);
}
let mut output: [[char; HEIGHT]; WIDTH] = [['x'; HEIGHT]; WIDTH];
for y in 0..HEIGHT {
for x in 0..WIDTH {
for l in 0..layers.len() {
match layers[l][x][y] {
'0' => {
output[x][y] = ' ';
break;
},
'1' => {
output[x][y] = 'X';
break;
},
'2' => (),
_ => panic!("unknown color"),
}
}
}
}
for y in 0..HEIGHT {
for x in 0..WIDTH {
print!("{}", output[x][y]);
}
println!();
}
Ok(())
}
|
use crate::lexer::parser::*;
pub fn get_lexer_rules() -> LexerOptions {
LexerOptions {
operators: LexerOperators {
arithmetic: vec![
"+".to_string(),
"-".to_string(),
"*".to_string(),
"/".to_string(),
"%".to_string(),
],
assignment: vec![
"=".to_string(),
"+=".to_string(),
"-=".to_string(),
"/=".to_string(),
"*=".to_string(),
"%=".to_string(),
"?=".to_string(),
":=".to_string(),
],
unary: vec!["++".to_string(), "--".to_string(), "!".to_string()],
logical: vec![
"==".to_string(),
"!=".to_string(),
"&&".to_string(),
"||".to_string(),
"<".to_string(),
"<=".to_string(),
">=".to_string(),
">".to_string(),
],
binary: vec!["^".to_string(), "&".to_string(), "|".to_string()],
comment: vec!["//".to_string()],
comment_multiline: vec!["/*".to_string(), "*/".to_string()],
other: vec![
":".to_string(),
".".to_string(),
"??".to_string(),
"?".to_string(),
"(".to_string(),
")".to_string(),
",".to_string(),
"?.".to_string(),
";".to_string(),
],
},
types: vec![
"u8".to_string(),
"i8".to_string(),
"u16".to_string(),
"i16".to_string(),
"u32".to_string(),
"u64".to_string(),
"i32".to_string(),
"i64".to_string(),
"f32".to_string(),
"f64".to_string(),
"u32".to_string(),
"u64".to_string(),
"str".to_string(),
"char".to_string(),
"bool".to_string(),
"null".to_string(),
"void".to_string(),
],
keywords: vec![
"let".to_string(),
"const".to_string(),
"func".to_string(),
"import".to_string(),
"export".to_string(),
"class".to_string(),
"interface".to_string(),
"true".to_string(),
"false".to_string(),
"extends".to_string(),
"implements".to_string(),
"as".to_string(),
"while".to_string(),
"if".to_string(),
"else".to_string(),
"for".to_string(),
"assert".to_string(),
"return".to_string(),
"at".to_string(),
"of".to_string(),
],
}
}
|
use std::io::{stdin, Read, StdinLock};
use std::str::FromStr;
#[allow(dead_code)]
struct Scanner<'a> {
cin: StdinLock<'a>,
}
#[allow(dead_code)]
impl<'a> Scanner<'a> {
fn new(cin: StdinLock<'a>) -> Scanner<'a> {
Scanner { cin: cin }
}
fn read<T: FromStr>(&mut self) -> Option<T> {
let token = self.cin.by_ref().bytes().map(|c| c.unwrap() as char)
.skip_while(|c| c.is_whitespace())
.take_while(|c| !c.is_whitespace())
.collect::<String>();
token.parse::<T>().ok()
}
fn input<T: FromStr>(&mut self) -> T {
self.read().unwrap()
}
}
fn main() {
let cin = stdin();
let cin = cin.lock();
let mut sc = Scanner::new(cin);
let q: isize = sc.input();
let max_n: isize = 1e5 as isize;
let is_prime = get_primes(max_n);
let mut cnt = vec![0; max_n as usize + 1];
let mut i = 3;
while i <= max_n as usize {
if is_prime[i] && is_prime[(i + 1) / 2] { cnt[i] += 1; }
i +=2;
}
for i in 0..max_n as usize {
cnt[i + 1] += cnt[i];
}
for _ in 0..q {
let (l, r): (usize, usize) = (sc.input(), sc.input());
println!("{}", cnt[r] - cnt[l - 1]);
}
}
fn get_primes(n: isize) -> Vec<bool> {
let mut is_prime = vec![true; n as usize + 1];
let mut i = 2;
while i * i <= n {
if is_prime[i as usize] {
let mut j = i * i;
while j <= n {
is_prime[j as usize] = false;
j += i;
}
}
i += 1;
}
is_prime
}
|
#[derive(Debug, Deserialize)]
pub struct Error {
pub ok: bool,
pub error: Option<String>,
}
#[derive(Deserialize, Serialize)]
pub struct Cursor(String); // TODO: Type safety goes here
#[derive(Deserialize)]
pub struct Paging {
pub count: Option<u32>,
pub page: Option<u32>,
pub pages: Option<u32>,
pub total: Option<u32>,
}
pub mod channels;
pub mod conversations;
pub mod emoji;
pub mod groups;
pub mod im;
pub mod reactions;
pub mod rtm;
pub mod users;
|
use cancellation::CancellationToken;
use crossbeam::channel::Sender;
use std::sync::Arc;
pub struct HashProgress {
pub bytes_processed: u64,
}
pub trait BlockHasher {
fn read(&mut self) -> usize;
fn update(&mut self, byte_count: usize);
fn digest(&mut self) -> String;
fn set_bytes_processed_event_sender(&mut self, sender: Sender<HashProgress>);
fn set_bytes_processed_event_sender_with_bytes_processed_notification_block_size(
&mut self,
sender: Sender<HashProgress>,
bytes_processed_notification_block_size: u64,
);
fn bytes_processed_notification_block_size(&self) -> u64;
fn is_bytes_processed_event_sender_defined(&self) -> bool;
fn handle_bytes_processed_event(&self, args: HashProgress);
fn compute(&mut self, cancellation_token: Arc<CancellationToken>) {
let mut bytes_read;
let mut running_notification_block_size = 0u64;
let mut bytes_processed = 0u64;
let bytes_processed_notification_block_size =
self.bytes_processed_notification_block_size();
loop {
if cancellation_token.is_canceled() {
break;
}
bytes_read = self.read();
if bytes_read > 0 {
self.update(bytes_read);
if self.is_bytes_processed_event_sender_defined()
&& bytes_processed_notification_block_size > 0
{
bytes_processed += bytes_read as u64;
running_notification_block_size += bytes_read as u64;
if running_notification_block_size >= bytes_processed_notification_block_size
|| bytes_read == 0
{
if bytes_read > 0 {
running_notification_block_size -=
bytes_processed_notification_block_size;
}
self.handle_bytes_processed_event(HashProgress { bytes_processed });
}
}
} else {
break;
}
}
}
}
|
use crate::random_txn;
use actix::Addr;
use criterion::{BatchSize, Bencher};
use parking_lot::RwLock;
use rand::prelude::*;
use rand::{RngCore, SeedableRng};
use starcoin_bus::BusActor;
use starcoin_chain::{BlockChain, ChainServiceImpl};
use starcoin_config::NodeConfig;
use starcoin_consensus::dummy::DummyConsensus;
use starcoin_genesis::Genesis;
use starcoin_txpool::{TxPool, TxPoolService};
use starcoin_wallet_api::WalletAccount;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use storage::cache_storage::CacheStorage;
use storage::storage::StorageInstance;
use storage::Storage;
use traits::{ChainReader, ChainService, Consensus};
/// Benchmarking support for chain.
pub struct ChainBencher {
chain: Arc<RwLock<ChainServiceImpl<DummyConsensus, Storage, TxPoolService>>>,
config: Arc<NodeConfig>,
storage: Arc<Storage>,
block_num: u64,
account: WalletAccount,
count: AtomicU64,
}
impl ChainBencher {
pub fn new(num: Option<u64>, bus: Addr<BusActor>) -> Self {
let node_config = NodeConfig::random_for_test();
let node_config = Arc::new(node_config);
let storage = Arc::new(
Storage::new(StorageInstance::new_cache_instance(CacheStorage::new())).unwrap(),
);
let genesis = Genesis::load(node_config.net()).unwrap();
let startup_info = genesis.execute(storage.clone()).unwrap();
let txpool = {
let best_block_id = *startup_info.get_master();
TxPool::start(
node_config.tx_pool.clone(),
storage.clone(),
best_block_id,
bus.clone(),
)
};
let chain = ChainServiceImpl::<DummyConsensus, Storage, TxPoolService>::new(
node_config.clone(),
startup_info,
storage.clone(),
txpool.get_service(),
bus,
)
.unwrap();
let miner_account = WalletAccount::random();
ChainBencher {
chain: Arc::new(RwLock::new(chain)),
block_num: match num {
Some(n) => n,
None => 100,
},
config: node_config,
storage,
account: miner_account,
count: AtomicU64::new(0),
}
}
pub fn execute(&self, proportion: Option<u64>) {
let mut latest_id = None;
let mut rng: StdRng = StdRng::from_seed([0; 32]);
for i in 0..self.block_num {
let block_chain = BlockChain::<DummyConsensus, Storage>::new(
self.config.clone(),
self.chain.read().get_master().head_block().header().id(),
self.storage.clone(),
)
.unwrap();
let mut branch_flag = false;
if let Some(p) = proportion {
let random = rng.next_u64();
if (random % p) == 0 {
branch_flag = true;
};
};
let parent = if branch_flag && i > 0 {
latest_id
} else {
self.count.fetch_add(1, Ordering::Relaxed);
None
};
let mut txn_vec = Vec::new();
txn_vec.push(random_txn(self.count.load(Ordering::Relaxed)));
let block_template = self
.chain
.read()
.create_block_template(
*self.account.address(),
Some(self.account.get_auth_key().prefix().to_vec()),
parent,
txn_vec,
)
.unwrap();
let block =
DummyConsensus::create_block(self.config.clone(), &block_chain, block_template)
.unwrap();
latest_id = Some(block.header().parent_hash());
self.chain.write().try_connect(block).unwrap().unwrap();
}
}
fn execute_query(&self, times: u64) {
let max_num = self.chain.read().master_head_header().number();
let mut rng = rand::thread_rng();
for _i in 0..times {
let number = rng.gen_range(0, max_num);
assert!(self
.chain
.read()
.master_block_by_number(number)
.unwrap()
.is_some());
}
}
pub fn query_bench(&self, b: &mut Bencher, times: u64) {
b.iter_batched(
|| (self, times),
|(bench, t)| bench.execute_query(t),
BatchSize::LargeInput,
)
}
pub fn bench(&self, b: &mut Bencher, proportion: Option<u64>) {
b.iter_batched(
|| (self, proportion),
|(bench, p)| bench.execute(p),
BatchSize::LargeInput,
)
}
}
|
use super::*;
#[test]
fn test_snake_size() {
let cases = [
(vec![1, 1, 1, 1, 1, 1, 1], 2),
(vec![2, 1, 1, 2, 1, 2, 1, 1, 2, 2, 1, 1, 1, 2, 2, 2, 2], 3),
];
for (snake, expected_size) in cases.iter() {
assert_eq!(*expected_size, snake_size(snake));
}
}
#[test]
#[should_panic]
fn test_snake_size_panic() {
let snake = vec![1, 1, 1, 1, 1, 1, 1, 1];
snake_size(&snake);
}
#[test]
fn test_orthogonal() {
use Orientation::*;
let cases = [((Up, Up), false), ((Right, Up), true)];
for ((o1, o2), expected) in cases.iter() {
assert_eq!(*expected, orthogonal(o1, o2));
}
}
|
/*
* Datadog API V1 Collection
*
* Collection of all Datadog Public endpoints.
*
* The version of the OpenAPI document: 1.0
* Contact: support@datadoghq.com
* Generated by: https://openapi-generator.tech
*/
/// Dashboard : A dashboard is Datadog’s tool for visually tracking, analyzing, and displaying key performance metrics, which enable you to monitor the health of your infrastructure.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Dashboard {
/// Identifier of the dashboard author.
#[serde(rename = "author_handle", skip_serializing_if = "Option::is_none")]
pub author_handle: Option<String>,
/// Creation date of the dashboard.
#[serde(rename = "created_at", skip_serializing_if = "Option::is_none")]
pub created_at: Option<String>,
/// Description of the dashboard.
#[serde(rename = "description", skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// ID of the dashboard.
#[serde(rename = "id", skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
/// Whether this dashboard is read-only. If True, only the author and admins can make changes to it.
#[serde(rename = "is_read_only", skip_serializing_if = "Option::is_none")]
pub is_read_only: Option<bool>,
#[serde(rename = "layout_type")]
pub layout_type: crate::models::DashboardLayoutType,
/// Modification date of the dashboard.
#[serde(rename = "modified_at", skip_serializing_if = "Option::is_none")]
pub modified_at: Option<String>,
/// List of handles of users to notify when changes are made to this dashboard.
#[serde(rename = "notify_list", skip_serializing_if = "Option::is_none")]
pub notify_list: Option<Vec<String>>,
#[serde(rename = "reflow_type", skip_serializing_if = "Option::is_none")]
pub reflow_type: Option<crate::models::DashboardReflowType>,
/// Array of template variables saved views.
#[serde(rename = "template_variable_presets", skip_serializing_if = "Option::is_none")]
pub template_variable_presets: Option<Vec<crate::models::DashboardTemplateVariablePreset>>,
/// List of template variables for this dashboard.
#[serde(rename = "template_variables", skip_serializing_if = "Option::is_none")]
pub template_variables: Option<Vec<crate::models::DashboardTemplateVariable>>,
/// Title of the dashboard.
#[serde(rename = "title")]
pub title: String,
/// The URL of the dashboard.
#[serde(rename = "url", skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
/// List of widgets to display on the dashboard.
#[serde(rename = "widgets")]
pub widgets: Vec<crate::models::Widget>,
}
impl Dashboard {
/// A dashboard is Datadog’s tool for visually tracking, analyzing, and displaying key performance metrics, which enable you to monitor the health of your infrastructure.
pub fn new(layout_type: crate::models::DashboardLayoutType, title: String, widgets: Vec<crate::models::Widget>) -> Dashboard {
Dashboard {
author_handle: None,
created_at: None,
description: None,
id: None,
is_read_only: None,
layout_type,
modified_at: None,
notify_list: None,
reflow_type: None,
template_variable_presets: None,
template_variables: None,
title,
url: None,
widgets,
}
}
}
|
fn main() {
println!("{0}, Thgis is {1}. {1}, this is {0}", "Alice", "Bob"); // Alice, Thgis is Bob. Bob, this is Alice
println!("{subject} {verb} {object}",
object="the lazy dog",
subject="the quick brown fox",
verb="jump over"); // the quick brown fox jump over the lazy dog
// 특별한 형식은 `:` 이후에 정할 수 있다.
println!("{} of {:b} people know binary, the other half doesn't.", 1, 2); // 1 of 10 people know binary, the other half doesn't.
// 길이를 정해서 우측정렬 포맷을 설정할 수 있다.
println!("{number:>width$}", number=1, width=6); // 1
println!("{number:>width$}", number=31, width=6); // 31
println!("{number:>width$}", number=666666, width=6); // 666666
println!("{number:>width$}", number=7654321, width=6); // 7654321
// 패딩을 공백에서 다른 문자로 변경할 수 있다.
println!("{number:>0width$}", number=1, width=6); // 000001
println!("{number:>0width$}", number=31, width=6); // 000031
println!("{number:>0width$}", number=666666, width=6); // 666666
println!("{number:>0width$}", number=7654321, width=6); // 7654321
println!("My name is {0}, {1} {0}.", "Bond", "James");
#[allow(dead_code)]
struct Structure(i32);
// 위와 같은 커스텀 타입은 더욱 복잡함을 필요로한다.
// println!("This struct `{}` won't print...", Structure(3)); // FIXME!
}
|
use anyhow::{Context, Result};
use dialoguer::{theme::ColorfulTheme, FuzzySelect};
use crate::config::read_config;
use crate::note::{DbNote, NoteData};
use crate::db::{init_schema, select_notes_for_review};
pub enum ReviewResult {
Easy, Hard, Again
}
fn get_review_result() -> Result<Option<ReviewResult>> {
let theme = ColorfulTheme::default();
let res = FuzzySelect::with_theme(&theme)
.default(0)
.item("0 Skip") // don't save any result
.item("1 Easy") // increase delay
.item("2 Hard") // decrease delay
.item("3 Again") // delay for 5 minutes
.interact()?;
Ok(match res {
1 => Some(ReviewResult::Easy),
2 => Some(ReviewResult::Hard),
3 => Some(ReviewResult::Again),
_ => None,
})
}
fn review_note(note: &DbNote) -> Result<Option<ReviewResult>> {
let theme = ColorfulTheme::default();
println!("\n#{}", note.tags);
match ¬e.data {
NoteData::Text(txt) => {
println!("{}", txt);
get_review_result()
},
NoteData::Card(card) => {
println!("{}", card[0]);
let res = FuzzySelect::with_theme(&theme)
.default(0)
.item("1 Show the answer")
.item("2 That was easy")
.interact()?;
if res == 1 {
Ok(Some(ReviewResult::Easy))
} else {
for txt in &card[1..] {
println!("{}", txt);
}
get_review_result()
}
}
}
}
pub fn exec(tags: &[String]) -> Result<()> {
let cfg = read_config()
.context("Reading config")?;
let db = sqlite::open(&cfg.db_path)
.context("Opening database file")?;
init_schema(&db)
.context("Initializing database schema")?;
let notes = select_notes_for_review(&db, tags)?;
for note in notes.iter() {
if let Some(res) = review_note(note)? {
// FIXME: save result and schedule next review
}
}
Ok(())
}
|
use std::{error, fmt};
use crate::serde::SerializerError;
#[derive(Debug)]
pub enum Error {
SchemaDiffer,
SchemaMissing,
WordIndexMissing,
MissingDocumentId,
RocksdbError(rocksdb::Error),
FstError(fst::Error),
BincodeError(bincode::Error),
SerializerError(SerializerError),
}
impl From<rocksdb::Error> for Error {
fn from(error: rocksdb::Error) -> Error {
Error::RocksdbError(error)
}
}
impl From<fst::Error> for Error {
fn from(error: fst::Error) -> Error {
Error::FstError(error)
}
}
impl From<bincode::Error> for Error {
fn from(error: bincode::Error) -> Error {
Error::BincodeError(error)
}
}
impl From<SerializerError> for Error {
fn from(error: SerializerError) -> Error {
Error::SerializerError(error)
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use self::Error::*;
match self {
SchemaDiffer => write!(f, "schemas differ"),
SchemaMissing => write!(f, "this index does not have a schema"),
WordIndexMissing => write!(f, "this index does not have a word index"),
MissingDocumentId => write!(f, "document id is missing"),
RocksdbError(e) => write!(f, "RocksDB error; {}", e),
FstError(e) => write!(f, "fst error; {}", e),
BincodeError(e) => write!(f, "bincode error; {}", e),
SerializerError(e) => write!(f, "serializer error; {}", e),
}
}
}
impl error::Error for Error { }
|
pub fn generate_parenthesis(n: i32) -> Vec<String> {
let v1 = vec!["()".to_string()];
let v2 = vec!["()()".to_string(), "(())".to_string()];
match n {
0 => vec!["".to_string()],
1 => v1,
2 => v2,
_ => {
let mut comb = Vec::<Vec<String>>::new();
comb.push(v1);
comb.push(v2);
for i in 3..=n {
let mut result = Vec::<String>::new();
let m = i as usize-2;
for s in comb[m].iter() {
result.push("()".to_string() + s);
result.push("(".to_string() + s + ")");
}
for s in comb[m-1].iter() {
result.push("(".to_string() + s + ")()");
}
for j in 1..m {
for s1 in comb[j-1].iter() {
for s2 in comb[m-j].iter() {
result.push("(".to_string()+s1+")"+s2);
}
}
}
comb.push(result);
}
comb[n as usize-1].to_vec()
}
}
}
#[test]
fn test_generate_parenthesis() {
// assert_eq!(generate_parenthesis(3), vec![
// "((()))",
// "(()())",
// "(())()",
// "()(())",
// "()()()",
// ]);
assert_eq!(generate_parenthesis(4), vec!["(((())))","((()()))","((())())","((()))()","(()(()))","(()()())","(()())()","(())(())","(())()()","()((()))","()(()())","()(())()","()()(())","()()()()"])
} |
use tantivy::tokenizer::LowerCaser;
#[derive(Clone)]
pub struct LowerCaseFilterFactory {}
impl LowerCaseFilterFactory {
pub fn new() -> Self {
LowerCaseFilterFactory {}
}
pub fn create(self) -> LowerCaser {
LowerCaser {}
}
}
#[cfg(test)]
mod tests {
use tantivy::tokenizer::{SimpleTokenizer, TextAnalyzer};
use crate::tokenizer::lower_case_filter_factory::LowerCaseFilterFactory;
fn helper(text: &str) -> Vec<String> {
let factory = LowerCaseFilterFactory::new();
let filter = factory.create();
let mut tokens = vec![];
let mut token_stream = TextAnalyzer::from(SimpleTokenizer)
.filter(filter)
.token_stream(text);
while token_stream.advance() {
let token_text = token_stream.token().text.clone();
tokens.push(token_text);
}
tokens
}
#[test]
fn test_lower_case_filter() {
assert_eq!(vec!["bayard".to_string()], helper("Bayard"));
}
}
|
#[doc = "Reader of register CH_CTL"]
pub type R = crate::R<u32, super::CH_CTL>;
#[doc = "Writer for register CH_CTL"]
pub type W = crate::W<u32, super::CH_CTL>;
#[doc = "Register CH_CTL `reset()`'s with value 0x02"]
impl crate::ResetValue for super::CH_CTL {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0x02
}
}
#[doc = "Reader of field `P`"]
pub type P_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `P`"]
pub struct P_W<'a> {
w: &'a mut W,
}
impl<'a> P_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Reader of field `NS`"]
pub type NS_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `NS`"]
pub struct NS_W<'a> {
w: &'a mut W,
}
impl<'a> NS_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Reader of field `B`"]
pub type B_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B`"]
pub struct B_W<'a> {
w: &'a mut W,
}
impl<'a> B_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Reader of field `PC`"]
pub type PC_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `PC`"]
pub struct PC_W<'a> {
w: &'a mut W,
}
impl<'a> PC_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 4)) | (((value as u32) & 0x0f) << 4);
self.w
}
}
#[doc = "Reader of field `PRIO`"]
pub type PRIO_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `PRIO`"]
pub struct PRIO_W<'a> {
w: &'a mut W,
}
impl<'a> PRIO_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 16)) | (((value as u32) & 0x03) << 16);
self.w
}
}
#[doc = "Reader of field `PREEMPTABLE`"]
pub type PREEMPTABLE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `PREEMPTABLE`"]
pub struct PREEMPTABLE_W<'a> {
w: &'a mut W,
}
impl<'a> PREEMPTABLE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18);
self.w
}
}
#[doc = "Reader of field `ENABLED`"]
pub type ENABLED_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `ENABLED`"]
pub struct ENABLED_W<'a> {
w: &'a mut W,
}
impl<'a> ENABLED_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 31)) | (((value as u32) & 0x01) << 31);
self.w
}
}
impl R {
#[doc = "Bit 0 - User/privileged access control: '0': user mode. '1': privileged mode. This field is set with the user/privileged access control of the transaction that writes this register; i.e. the 'write data' is ignored and instead the access control is inherited from the write transaction (note the field attributes should be HW:RW, SW:R). All transactions for this channel use the P field for the user/privileged access control ('hprot\\[1\\]')."]
#[inline(always)]
pub fn p(&self) -> P_R {
P_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - Secure/on-secure access control: '0': secure. '1': non-secure. This field is set with the secure/non-secure access control of the transaction that writes this register; i.e. the 'write data' is ignored and instead the access control is inherited from the write transaction (note the field attributes should be HW:RW, SW:R). All transactions for this channel use the NS field for the secure/non-secure access control ('hprot\\[4\\]')."]
#[inline(always)]
pub fn ns(&self) -> NS_R {
NS_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - Non-bufferable/bufferable access control: '0': non-bufferable. '1': bufferable. This field is used to indicate to an AMBA bridge that a write transaction can complete without waiting for the destination to accept the write transaction data. All transactions for this channel uses the B field for the non-bufferable/bufferable access control ('hprot\\[2\\]')."]
#[inline(always)]
pub fn b(&self) -> B_R {
B_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bits 4:7 - Protection context. This field is set with the protection context of the transaction that writes this register; i.e. the 'write data' is ignored and instead the context is inherited from the write transaction (note the field attributes should be HW:RW, SW:R). All transactions for this channel uses the PC field for the protection context."]
#[inline(always)]
pub fn pc(&self) -> PC_R {
PC_R::new(((self.bits >> 4) & 0x0f) as u8)
}
#[doc = "Bits 16:17 - Channel priority: '0': highest priority. '1' '2' '3': lowest priority. Channels with the same priority constitute a priority group. Priority decoding determines the highest priority pending channel. This channel is determined as follows. First, the highest priority group with pending channels is identified. Second, within this priority group, roundrobin arbitration is applied. Roundrobin arbitration (within a priority group) gives the highest priority to the lower channel indices (within the priority group)."]
#[inline(always)]
pub fn prio(&self) -> PRIO_R {
PRIO_R::new(((self.bits >> 16) & 0x03) as u8)
}
#[doc = "Bit 18 - Specifies if the channel is preemptable. '0': Not preemptable. '1': Preemptable. This field allows higher priority pending channels (from a higer priority group; i.e. an active channel can NOT be preempted by a pending channel in the same priority group) to preempt the active channel in between 'single transfers' (a 1D transfer consists out of X_COUNT single transfers; a 2D transfer consists out of X_COUNT*Y_COUNT single transfers). Preemption will NOT affect the pending status of channel. As a result, after completion of a higher priority activated channel, the current channel may be reactivated."]
#[inline(always)]
pub fn preemptable(&self) -> PREEMPTABLE_R {
PREEMPTABLE_R::new(((self.bits >> 18) & 0x01) != 0)
}
#[doc = "Bit 31 - Channel enable: '0': Disabled. The channel's trigger is ignored and the channel cannot be made pending and therefore cannot be made active. If a pensding channel is disabled, the channel is made non pending. If the activate channel is disabled, the channel is de-activated (bus transactions are completed). '1': Enabled. SW sets this field to '1' to enable a specific channel. HW sets this field to '0' on an error interrupt cause (the specific error is specified by CH_STATUS.INTR_CAUSE)."]
#[inline(always)]
pub fn enabled(&self) -> ENABLED_R {
ENABLED_R::new(((self.bits >> 31) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - User/privileged access control: '0': user mode. '1': privileged mode. This field is set with the user/privileged access control of the transaction that writes this register; i.e. the 'write data' is ignored and instead the access control is inherited from the write transaction (note the field attributes should be HW:RW, SW:R). All transactions for this channel use the P field for the user/privileged access control ('hprot\\[1\\]')."]
#[inline(always)]
pub fn p(&mut self) -> P_W {
P_W { w: self }
}
#[doc = "Bit 1 - Secure/on-secure access control: '0': secure. '1': non-secure. This field is set with the secure/non-secure access control of the transaction that writes this register; i.e. the 'write data' is ignored and instead the access control is inherited from the write transaction (note the field attributes should be HW:RW, SW:R). All transactions for this channel use the NS field for the secure/non-secure access control ('hprot\\[4\\]')."]
#[inline(always)]
pub fn ns(&mut self) -> NS_W {
NS_W { w: self }
}
#[doc = "Bit 2 - Non-bufferable/bufferable access control: '0': non-bufferable. '1': bufferable. This field is used to indicate to an AMBA bridge that a write transaction can complete without waiting for the destination to accept the write transaction data. All transactions for this channel uses the B field for the non-bufferable/bufferable access control ('hprot\\[2\\]')."]
#[inline(always)]
pub fn b(&mut self) -> B_W {
B_W { w: self }
}
#[doc = "Bits 4:7 - Protection context. This field is set with the protection context of the transaction that writes this register; i.e. the 'write data' is ignored and instead the context is inherited from the write transaction (note the field attributes should be HW:RW, SW:R). All transactions for this channel uses the PC field for the protection context."]
#[inline(always)]
pub fn pc(&mut self) -> PC_W {
PC_W { w: self }
}
#[doc = "Bits 16:17 - Channel priority: '0': highest priority. '1' '2' '3': lowest priority. Channels with the same priority constitute a priority group. Priority decoding determines the highest priority pending channel. This channel is determined as follows. First, the highest priority group with pending channels is identified. Second, within this priority group, roundrobin arbitration is applied. Roundrobin arbitration (within a priority group) gives the highest priority to the lower channel indices (within the priority group)."]
#[inline(always)]
pub fn prio(&mut self) -> PRIO_W {
PRIO_W { w: self }
}
#[doc = "Bit 18 - Specifies if the channel is preemptable. '0': Not preemptable. '1': Preemptable. This field allows higher priority pending channels (from a higer priority group; i.e. an active channel can NOT be preempted by a pending channel in the same priority group) to preempt the active channel in between 'single transfers' (a 1D transfer consists out of X_COUNT single transfers; a 2D transfer consists out of X_COUNT*Y_COUNT single transfers). Preemption will NOT affect the pending status of channel. As a result, after completion of a higher priority activated channel, the current channel may be reactivated."]
#[inline(always)]
pub fn preemptable(&mut self) -> PREEMPTABLE_W {
PREEMPTABLE_W { w: self }
}
#[doc = "Bit 31 - Channel enable: '0': Disabled. The channel's trigger is ignored and the channel cannot be made pending and therefore cannot be made active. If a pensding channel is disabled, the channel is made non pending. If the activate channel is disabled, the channel is de-activated (bus transactions are completed). '1': Enabled. SW sets this field to '1' to enable a specific channel. HW sets this field to '0' on an error interrupt cause (the specific error is specified by CH_STATUS.INTR_CAUSE)."]
#[inline(always)]
pub fn enabled(&mut self) -> ENABLED_W {
ENABLED_W { w: self }
}
}
|
pub mod cpu;
pub mod opcodes;
pub mod rand;
|
use std::path::PathBuf;
pub trait Archive {
fn get_path(&self) -> PathBuf;
}
|
use std::fs::File;
use std::io::BufReader;
use std::io::BufRead;
const INPUT_DIR: &str = "inputs/";
pub fn load_input(name: &str) -> Vec<String> {
let path = format!("{}{}.txt", INPUT_DIR, name);
debug!("Opening path: {}", path);
let file = File::open(path).unwrap();
let mut file = BufReader::new(&file);
let mut result = Vec::new();
loop {
let mut line = String::new();
file.read_line(&mut line).unwrap();
if line.is_empty() {
break
} else {
result.push(line.trim().to_owned());
}
}
result
} |
use mockall::*;
use ssz_types::BitList;
use types::{
beacon_state::BeaconState,
config::Config,
helper_functions_types::Error,
primitives::*,
types::{Attestation, AttestationData, IndexedAttestation},
};
// ok
pub fn get_current_epoch<C: Config>(_state: &BeaconState<C>) -> Epoch {
23
}
// ok
pub fn get_previous_epoch<C: Config>(_state: &BeaconState<C>) -> Epoch {
0
}
// ok
pub fn get_block_root<C: Config>(_state: &BeaconState<C>, _epoch: Epoch) -> Result<H256, Error> {
Err(Error::IndexOutOfRange)
}
// ok
pub fn get_block_root_at_slot<C: Config>(
_state: &BeaconState<C>,
_slot: Slot,
) -> Result<H256, Error> {
Ok(H256::from([0; 32]))
}
// ok
pub fn get_randao_mix<C: Config>(_state: &BeaconState<C>, _epoch: Epoch) -> Result<H256, Error> {
Err(Error::IndexOutOfRange)
}
// ok
pub fn get_active_validator_indices<C: Config>(
_state: &BeaconState<C>,
_epoch: Epoch,
) -> impl Iterator<Item = &ValidatorIndex> {
[].iter()
}
// ok
pub fn get_validator_churn_limit<C: Config>(_state: &BeaconState<C>) -> u64 {
1
}
// ok
pub fn get_seed<C: Config>(
_state: &BeaconState<C>,
_epoch: Epoch,
_domain_type: DomainType,
) -> Result<H256, Error> {
Ok(H256::from([0; 32]))
}
// ok
pub fn get_committee_count_at_slot<C: Config>(
_state: &BeaconState<C>,
_slot: Slot,
) -> Result<u64, Error> {
Ok(1)
}
// ok
pub fn get_beacon_committee<C: Config>(
_state: &BeaconState<C>,
_slot: Slot,
_index: u64,
) -> Result<impl Iterator<Item = &ValidatorIndex>, Error> {
Ok([].iter())
}
// ok
pub fn get_beacon_proposer_index<C: Config>(
_state: &BeaconState<C>,
) -> Result<ValidatorIndex, Error> {
Ok(0)
}
// ok
pub fn get_total_balance<C: Config>(
_state: &BeaconState<C>,
_indices: &[ValidatorIndex],
) -> Result<u64, Error> {
Ok(1)
}
// ok
pub fn get_total_active_balance<C: Config>(_state: &BeaconState<C>) -> Result<u64, Error> {
Ok(1)
}
// ok
pub fn get_domain<C: Config>(
_state: &BeaconState<C>,
_domain_type: DomainType,
_message_epoch: Option<Epoch>,
) -> Domain {
0
}
//ok
pub fn get_indexed_attestation<C: Config>(
_state: &BeaconState<C>,
_attestation: &Attestation<C>,
) -> Result<IndexedAttestation<C>, Error> {
Err(Error::IndexOutOfRange)
}
//ok
pub fn get_attesting_indices<'a, C: Config>(
_state: &'a BeaconState<C>,
_attestation_data: &AttestationData,
_bitlist: &BitList<C::MaxValidatorsPerCommittee>,
) -> Result<impl Iterator<Item = &'a ValidatorIndex>, Error> {
Ok([].iter())
}
#[automock]
pub trait BeaconStateAccessor {
fn get_current_epoch(&self) -> Epoch;
fn get_previous_epoch(&self) -> Epoch;
fn get_block_root(&self, _epoch: Epoch) -> Result<H256, Error>;
fn get_block_root_at_slot(&self, _slot: Slot) -> Result<H256, Error>;
fn get_total_active_balance(&self) -> Result<u64, Error>;
}
impl<C> BeaconStateAccessor for BeaconState<C>
where
C: Config,
{
fn get_current_epoch(&self) -> Epoch {
get_current_epoch(self)
}
fn get_previous_epoch(&self) -> Epoch {
get_previous_epoch(self)
}
fn get_block_root(&self, _epoch: Epoch) -> Result<H256, Error> {
get_block_root(self, _epoch)
}
fn get_block_root_at_slot(&self, _slot: Slot) -> Result<H256, Error> {
get_block_root_at_slot(self, _slot)
}
fn get_total_active_balance(&self) -> Result<u64, Error> {
get_total_active_balance(self)
}
}
|
use std::io;
#[derive(PartialEq, Clone, Debug)]
struct House {
x: i32,
y: i32,
}
fn get_line() -> String {
let mut input = String::new();
let stdin = io::stdin();
stdin.read_line(&mut input).unwrap();
input
}
fn main() {
let input = get_line();
let mut houses: Vec<House> = Vec::new();
let mut unique_houses = 1;
let mut current_house = House { x: 0, y: 0 };
let mut robo_santa = House { x: 0, y: 0 };
let mut index = 0;
// Santa delivers a present to himself
houses.push(current_house.clone());
for letter in input.as_str().chars() {
// Follow drunk elf's instructions
if index % 2 == 0 {
match letter {
'^' => current_house.y += 1,
'v' => current_house.y -= 1,
'>' => current_house.x += 1,
'<' => current_house.x -= 1,
_ => (),
}
}
else {
match letter {
'^' => robo_santa.y += 1,
'v' => robo_santa.y -= 1,
'>' => robo_santa.x += 1,
'<' => robo_santa.x -= 1,
_ => (),
}
}
if !houses.contains(¤t_house) {
unique_houses += 1;
houses.push(current_house.clone());
}
if !houses.contains(&robo_santa) {
unique_houses += 1;
houses.push(robo_santa.clone());
}
index += 1;
}
println!("Unique houses: {}", unique_houses);
}
|
use bevy::prelude::*;
fn main() {
App::build()
.add_plugins(DefaultPlugins)
.insert_resource(WindowDescriptor {
title: "Untitled Space Sim!".to_string(),
width: 600.0,
height: 600.0,
..Default::default()
})
.insert_resource(ClearColor(Color::rgb(0.0, 0.01, 0.02)))
.init_resource::<Ship>()
// .add_startup_system(add_camera_for_star.system())
// .add_startup_system(add_star.system())
.add_startup_system(setup.system())
.add_system(add_grinder_parts.system())
.add_system(bevy::input::system::exit_on_esc_system.system())
.add_system(handle_key_press.system())
.run();
}
struct GrinderAssets {
head: Handle<Mesh>,
body: Handle<Mesh>,
handle: Handle<Mesh>,
cover: Handle<Mesh>,
nut: Handle<Mesh>,
washer: Handle<Mesh>,
rod: Handle<Mesh>,
trunnion: Handle<Mesh>,
flanges: Handle<Mesh>,
disc: Handle<Mesh>,
spindle: Handle<Mesh>,
bearing_cap: Handle<Mesh>,
gear_cover: Handle<Mesh>,
base: Handle<Mesh>,
fence: Handle<Mesh>,
}
fn setup(
mut commands: Commands,
asset_server: Res<AssetServer>,
meshes: Res<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
commands.insert_resource(GrinderAssets {
head: asset_server.load("stand-grinder.gltf#Mesh0/Primitive0"),
body: asset_server.load("stand-grinder.gltf#Mesh1/Primitive0"),
handle: asset_server.load("stand-grinder.gltf#Mesh2/Primitive0"),
cover: asset_server.load("stand-grinder.gltf#Mesh3/Primitive0"),
nut: asset_server.load("stand-grinder.gltf#Mesh4/Primitive0"),
washer: asset_server.load("stand-grinder.gltf#Mesh5/Primitive0"),
rod: asset_server.load("stand-grinder.gltf#Mesh6/Primitive0"),
trunnion: asset_server.load("stand-grinder.gltf#Mesh7/Primitive0"),
flanges: asset_server.load("stand-grinder.gltf#Mesh8/Primitive0"),
disc: asset_server.load("stand-grinder.gltf#Mesh9/Primitive0"),
spindle: asset_server.load("stand-grinder.gltf#Mesh10/Primitive0"),
bearing_cap: asset_server.load("stand-grinder.gltf#Mesh11/Primitive0"),
gear_cover: asset_server.load("stand-grinder.gltf#Mesh12/Primitive0"),
base: asset_server.load("stand-grinder.gltf#Mesh13/Primitive0"),
fence: asset_server.load("stand-grinder.gltf#Mesh14/Primitive0"),
});
commands.spawn_bundle(LightBundle {
transform: Transform::from_xyz(4.0, 5.0, 4.0),
..Default::default()
});
commands.spawn_bundle(PerspectiveCameraBundle {
transform: Transform::from_xyz(0.0, 0.3, 1.0).looking_at(Vec3::ZERO, Vec3::Y),
..Default::default()
});
}
fn add_grinder_parts(
mut commands: Commands,
grinder: Res<GrinderAssets>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
let material_handle = materials.add(StandardMaterial {
base_color: Color::rgb(0.9, 0.9, 0.9),
..Default::default()
});
commands.spawn_bundle(PbrBundle {
mesh: grinder.head.clone(),
material: material_handle.clone(),
transform: Transform::from_xyz(0.0, 0.0, 0.0),
..Default::default()
});
commands.spawn_bundle(PbrBundle {
mesh: grinder.handle.clone(),
material: material_handle.clone(),
transform: Transform::from_xyz(0.075, 0.0, 0.0),
..Default::default()
});
commands.spawn_bundle(PbrBundle {
mesh: grinder.body.clone(),
material: material_handle.clone(),
transform: Transform::from_xyz(0.1, 0.0, 0.0),
..Default::default()
});
commands.spawn_bundle(PbrBundle {
mesh: grinder.cover.clone(),
material: material_handle.clone(),
transform: Transform::from_xyz(0.3, 0.0, 0.0),
..Default::default()
});
commands.spawn_bundle(PbrBundle {
mesh: grinder.nut.clone(),
material: material_handle.clone(),
transform: Transform::from_xyz(0.4, 0.0, 0.0),
..Default::default()
});
commands.spawn_bundle(PbrBundle {
mesh: grinder.washer.clone(),
material: material_handle.clone(),
transform: Transform::from_xyz(0.4, 0.0, 0.0),
..Default::default()
});
commands.spawn_bundle(PbrBundle {
mesh: grinder.rod.clone(),
material: material_handle.clone(),
transform: Transform::from_xyz(0.4, 0.0, 0.0),
..Default::default()
});
commands.spawn_bundle(PbrBundle {
mesh: grinder.trunnion.clone(),
material: material_handle.clone(),
transform: Transform::from_xyz(-0.1, 0.0, 0.0),
..Default::default()
});
commands.spawn_bundle(PbrBundle {
mesh: grinder.flanges.clone(),
material: material_handle.clone(),
transform: Transform::from_xyz(-0.2, 0.0, 0.0),
..Default::default()
});
commands.spawn_bundle(PbrBundle {
mesh: grinder.disc.clone(),
material: material_handle.clone(),
transform: Transform::from_xyz(-0.2, 0.0, 0.0),
..Default::default()
});
commands.spawn_bundle(PbrBundle {
mesh: grinder.spindle.clone(),
material: material_handle.clone(),
transform: Transform::from_xyz(-0.2, 0.0, 0.0),
..Default::default()
});
commands.spawn_bundle(PbrBundle {
mesh: grinder.bearing_cap.clone(),
material: material_handle.clone(),
transform: Transform::from_xyz(-0.2, 0.0, 0.0),
..Default::default()
});
commands.spawn_bundle(PbrBundle {
mesh: grinder.gear_cover.clone(),
material: material_handle.clone(),
transform: Transform::from_xyz(-0.2, 0.0, 0.0),
..Default::default()
});
commands.spawn_bundle(PbrBundle {
mesh: grinder.base.clone(),
material: material_handle.clone(),
transform: Transform::from_xyz(-0.5, 0.0, 0.0),
..Default::default()
});
commands.spawn_bundle(PbrBundle {
mesh: grinder.fence.clone(),
material: material_handle.clone(),
transform: Transform::from_xyz(-0.7, 0.0, 0.0),
..Default::default()
});
}
fn add_star(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
commands.spawn().insert_bundle(PbrBundle {
mesh: meshes.add(Mesh::from(shape::Icosphere {
radius: 4.0,
subdivisions: 8,
})),
material: materials.add(StandardMaterial {
base_color: Color::hex("fff8c1").unwrap(),
unlit: true,
..Default::default()
}),
transform: Transform::from_translation(Vec3::new(4., 0., 4.)),
..Default::default()
});
}
fn add_camera_for_star(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
commands
// Camera
.spawn()
.insert_bundle(PerspectiveCameraBundle {
transform: Transform::from_matrix(Mat4::from_rotation_translation(
Quat::from_xyzw(-0.3, -0.5, -0.3, 0.5).normalize(),
Vec3::new(-7.0, 20.0, 4.0),
)),
..Default::default()
});
commands
// Light
.spawn()
.insert_bundle(LightBundle {
transform: Transform::from_translation(Vec3::new(4.0, 8.0, 4.0)),
..Default::default()
});
}
#[derive(Default)]
struct Ship {
entity: Option<Entity>,
i: usize,
j: usize,
}
fn handle_key_press(
mut commands: Commands,
keyboard_input: Res<Input<KeyCode>>,
mut ship: ResMut<Ship>,
mut transforms: Query<&mut Transform>,
) {
if keyboard_input.just_pressed(KeyCode::Up) {
info!("pitch down");
}
if keyboard_input.just_pressed(KeyCode::Down) {
info!("pitch up");
}
if keyboard_input.just_pressed(KeyCode::Right) {
info!("roll right");
}
if keyboard_input.just_pressed(KeyCode::Left) {
info!("roll left");
}
// let rotation = -std::f32::consts::FRAC_PI_2;
// *transforms.get_mut(game.player.entity.unwrap()).unwrap() = Transform {
// translation: Vec3::new(
// game.player.i as f32,
// game.board[game.player.j][game.player.i].height,
// game.player.j as f32,
// ),
// rotation: Quat::from_rotation_y(rotation),
// ..Default::default()
// };
}
|
use super::canvas::Canvas;
/// This trait allows an object to be drawn on a canvas like this:
///
/// ```ignore
/// canvas.draw(&object);
/// ```
///
/// If you are experienced with [html5 canvas element](https://www.html5canvastutorials.com/) you can get the
/// [WebSys canvas object](https://docs.rs/web-sys/0.3.35/web_sys/struct.CanvasRenderingContext2d.html) and draw on it directly.
pub trait Drawable {
/// This method is called by the [draw method](../canvas/struct.Canvas.html#method.draw).
fn draw_on_canvas(&self, canvas: &mut Canvas);
} |
use std::collections::HashSet;
use stringreader::StringReader;
use uvm_core::unity::v2::Manifest;
use uvm_core::unity::{Component};
use uvm_install_graph::{InstallGraph, InstallStatus, Walker};
mod fixures;
use itertools::Itertools;
#[test]
fn create_graph_from_manifest() {
let ini = fixures::UNITY_2019_INI;
let reader = StringReader::new(ini);
let version = Manifest::read_manifest_version(reader).unwrap();
let reader = StringReader::new(ini);
let manifest = Manifest::from_reader(&version, reader).expect("a manifest");
let _graph = InstallGraph::from(&manifest);
}
#[test]
fn retrieve_nodes() {
let ini = fixures::UNITY_2019_INI;
let reader = StringReader::new(ini);
let version = Manifest::read_manifest_version(reader).unwrap();
let reader = StringReader::new(ini);
let manifest = Manifest::from_reader(&version, reader).expect("a manifest");
let graph = InstallGraph::from(&manifest);
let node_idx = graph.get_node_id(Component::Android).unwrap();
assert_eq!(*graph.component(node_idx).unwrap(), Component::Android);
}
#[test]
fn install_status() {
let ini = fixures::UNITY_2019_INI;
let reader = StringReader::new(ini);
let version = Manifest::read_manifest_version(reader).unwrap();
let reader = StringReader::new(ini);
let manifest = Manifest::from_reader(&version, reader).expect("a manifest");
let mut graph = InstallGraph::from(&manifest);
let node_android = graph.get_node_id(Component::Android).unwrap();
let node_ios = graph.get_node_id(Component::Ios).unwrap();
let node_webgl = graph.get_node_id(Component::WebGl).unwrap();
let node_editor = graph.get_node_id(Component::Editor).unwrap();
assert_eq!(
graph.install_status(node_android),
Some(&InstallStatus::Unknown)
);
assert_eq!(
graph.install_status(node_ios),
Some(&InstallStatus::Unknown)
);
assert_eq!(
graph.install_status(node_webgl),
Some(&InstallStatus::Unknown)
);
assert_eq!(
graph.install_status(node_editor),
Some(&InstallStatus::Unknown)
);
let mut installed_set: HashSet<Component> = HashSet::new();
installed_set.insert(Component::Editor);
installed_set.insert(Component::Android);
graph.mark_installed(&installed_set);
assert_eq!(
graph.install_status(node_android),
Some(&InstallStatus::Installed)
);
assert_eq!(
graph.install_status(node_ios),
Some(&InstallStatus::Missing)
);
assert_eq!(
graph.install_status(node_webgl),
Some(&InstallStatus::Missing)
);
assert_eq!(
graph.install_status(node_editor),
Some(&InstallStatus::Installed)
);
graph.mark_all_missing();
assert_eq!(
graph.install_status(node_android),
Some(&InstallStatus::Missing)
);
assert_eq!(
graph.install_status(node_ios),
Some(&InstallStatus::Missing)
);
assert_eq!(
graph.install_status(node_webgl),
Some(&InstallStatus::Missing)
);
assert_eq!(
graph.install_status(node_editor),
Some(&InstallStatus::Missing)
);
graph.mark_all(InstallStatus::Installed);
assert_eq!(
graph.install_status(node_android),
Some(&InstallStatus::Installed)
);
assert_eq!(
graph.install_status(node_ios),
Some(&InstallStatus::Installed)
);
assert_eq!(
graph.install_status(node_webgl),
Some(&InstallStatus::Installed)
);
assert_eq!(
graph.install_status(node_editor),
Some(&InstallStatus::Installed)
);
}
#[test]
fn modules_dependencies() {
let ini = fixures::UNITY_2019_INI;
let reader = StringReader::new(ini);
let version = Manifest::read_manifest_version(reader).unwrap();
let reader = StringReader::new(ini);
let manifest = Manifest::from_reader(&version, reader).expect("a manifest");
let graph = InstallGraph::from(&manifest);
let node_android = graph.get_node_id(Component::Android).unwrap();
let node_android_sdk_ndk_tools = graph.get_node_id(Component::AndroidSdkNdkTools).unwrap();
let node_android_ndk = graph.get_node_id(Component::AndroidNdk).unwrap();
let node_editor = graph.get_node_id(Component::Editor).unwrap();
let depended = graph.get_dependend_modules(node_android_ndk);
let mut iter = depended.iter();
assert_eq!(
iter.next(),
Some(&(
(Component::AndroidSdkNdkTools, InstallStatus::Unknown),
node_android_sdk_ndk_tools
))
);
assert_eq!(
iter.next(),
Some(&((Component::Android, InstallStatus::Unknown), node_android))
);
assert_eq!(
iter.next(),
Some(&((Component::Editor, InstallStatus::Unknown), node_editor))
);
assert_eq!(iter.next(), None);
}
#[test]
fn sub_modules() {
let ini = fixures::UNITY_2019_INI;
let reader = StringReader::new(ini);
let version = Manifest::read_manifest_version(reader).unwrap();
let reader = StringReader::new(ini);
let manifest = Manifest::from_reader(&version, reader).expect("a manifest");
let graph = InstallGraph::from(&manifest);
let node_android = graph.get_node_id(Component::Android).unwrap();
let node_open_jdk = graph.get_node_id(Component::AndroidOpenJdk).unwrap();
let node_android_sdk_ndk_tools = graph.get_node_id(Component::AndroidSdkNdkTools).unwrap();
let node_android_sdk_platforms = graph.get_node_id(Component::AndroidSdkPlatforms).unwrap();
let node_android_sdk_platform_tools = graph
.get_node_id(Component::AndroidSdkPlatformTools)
.unwrap();
let node_android_sdk_build_tools = graph.get_node_id(Component::AndroidSdkBuildTools).unwrap();
let node_android_ndk = graph.get_node_id(Component::AndroidNdk).unwrap();
let depended = graph.get_sub_modules(node_android);
let mut iter = depended
.iter()
.sorted_by(|((a, _), _), ((b, _), _)| b.to_string().cmp(&a.to_string()));
assert_eq!(
iter.next(),
Some(&(
(Component::AndroidSdkPlatforms, InstallStatus::Unknown),
node_android_sdk_platforms
))
);
assert_eq!(
iter.next(),
Some(&(
(Component::AndroidSdkPlatformTools, InstallStatus::Unknown),
node_android_sdk_platform_tools
))
);
assert_eq!(
iter.next(),
Some(&(
(Component::AndroidSdkNdkTools, InstallStatus::Unknown),
node_android_sdk_ndk_tools
))
);
assert_eq!(
iter.next(),
Some(&(
(Component::AndroidSdkBuildTools, InstallStatus::Unknown),
node_android_sdk_build_tools
))
);
assert_eq!(
iter.next(),
Some(&(
(Component::AndroidOpenJdk, InstallStatus::Unknown),
node_open_jdk
))
);
assert_eq!(
iter.next(),
Some(&(
(Component::AndroidNdk, InstallStatus::Unknown),
node_android_ndk
))
);
assert_eq!(iter.next(), None);
}
#[test]
fn topo() {
let ini = fixures::UNITY_2019_INI;
let reader = StringReader::new(ini);
let version = Manifest::read_manifest_version(reader).unwrap();
let reader = StringReader::new(ini);
let manifest = Manifest::from_reader(&version, reader).expect("a manifest");
let mut graph = InstallGraph::from(&manifest);
let node_android_ndk = graph.get_node_id(Component::AndroidNdk).unwrap();
let ndk_dependencies = graph.get_dependend_modules(node_android_ndk);
let mut keep: HashSet<Component> = ndk_dependencies
.into_iter()
.map(|((component, _), _)| component)
.collect();
keep.insert(Component::AndroidNdk);
graph.keep(&keep);
let mut topo = graph.topo();
assert_eq!(
topo.walk_next(graph.context()),
graph.get_node_id(Component::Editor)
);
assert_eq!(
topo.walk_next(graph.context()),
graph.get_node_id(Component::Android)
);
assert_eq!(
topo.walk_next(graph.context()),
graph.get_node_id(Component::AndroidSdkNdkTools)
);
assert_eq!(
topo.walk_next(graph.context()),
graph.get_node_id(Component::AndroidNdk)
);
assert_eq!(topo.walk_next(graph.context()), None);
}
#[test]
fn keep() {
let ini = fixures::UNITY_2019_INI;
let reader = StringReader::new(ini);
let version = Manifest::read_manifest_version(reader).unwrap();
let reader = StringReader::new(ini);
let manifest = Manifest::from_reader(&version, reader).expect("a manifest");
let mut graph = InstallGraph::from(&manifest);
assert!(graph.node_count() >= 2);
let mut keep_set: HashSet<Component> = HashSet::new();
keep_set.insert(Component::Editor);
keep_set.insert(Component::Android);
graph.keep(&keep_set);
assert!(graph.node_count() == 2);
}
|
// This modules returns an appropirate color_map for a configuration
// Currently only the num_states is taken into account
static BASE_COLORMAP: [u8; 18] = [
0xB2, 0x1F, 0x35,
0xFF, 0x74, 0x35,
0xFF, 0xF7, 0x35,
0x16, 0xDD, 0x36,
0x00, 0x79, 0xE7,
0xBD, 0x7A, 0xF6,
];
pub fn get_colormap(num_states: u8) -> Vec<u8> {
let mut colormap = vec![0; (num_states * 3) as usize];
let base_num_states = BASE_COLORMAP.len();
for i in 0..num_states {
for j in 0..3 {
let index = (i * 3 + j) as usize;
colormap[index] = BASE_COLORMAP[index % base_num_states];
}
}
colormap
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_get_colormap() {
let ground_truth: Vec<u8> = vec![
0xB2, 0x1F, 0x35,
0xFF, 0x74, 0x35,
0xFF, 0xF7, 0x35];
let colormap = get_colormap(3);
assert_eq!(ground_truth, colormap);
let ground_truth: Vec<u8> = vec![
0xB2, 0x1F, 0x35,
0xFF, 0x74, 0x35,
0xFF, 0xF7, 0x35,
0x16, 0xDD, 0x36,
0x00, 0x79, 0xE7,
0xBD, 0x7A, 0xF6];
let colormap = get_colormap(6);
assert_eq!(ground_truth, colormap);
let ground_truth: Vec<u8> = vec![];
let colormap = get_colormap(0);
assert_eq!(ground_truth, colormap);
}
}
|
pub mod server;
pub use server::start_ntp_server;
|
/*
same structures as in transpiler grammar, but identifiers are stored as (u8,u8,u8) colors,
transformed into usize for simplicity
*/
#[derive(Debug)]
pub enum Stmt {
Define(usize),
Assign(usize, Box<Expr>),
PrintStmt(Box<Expr>)
}
#[derive(Debug)]
pub enum Expr {
Number(i64),
Variable(usize),
Binary(Op, Box<Expr>, Box<Expr>)
}
#[derive(Debug)]
pub enum Op {
Mul,
Div,
Add,
Sub,
}
pub type Program = Vec<Stmt>; |
use crate::*;
use std::rc::Rc;
use std::cell::RefCell;
use shoji::*;
// a button that user can click
// contains a label in the middle
// TODO
// how to do a callback / even when the button is clicked/released/enter/leave
// FUTURE
// image button
// link button
// toggle button
// switch
// checkbox
// radio
pub struct Button {
layout: Option<UILayout>,
xalign: f64,
yalign: f64,
label: Label
background_color: Color
}
impl Button {
pub fn new() -> Self {
label : Label:new(),
xalign: 0.5,
yalign: 0.5,
background_color: Color:new()
}
pub fn is_button_pressed() -> bool {
panic!("this should be implemented")
return false;
}
pub fn is_button_released() -> bool {
panic!("this should be implemented")
return false;
}
pub fn set_label_text(&mut self, text: &String) {
panic!("this should be implemented")
}
pub fn get_label(self) -> Label {
// todo retun a reference to the label inside the button
// is this a good idea?
panic!("this should be implemented")
}
}
impl Element for Button {
fn render(&self, renderer: &dyn Renderer) {
if let Some(layout) = &self.layout {
renderer.draw_rectangle(&layout.as_rect());
// render the children
for child in &self.children {
child.render(renderer);
}
}
}
fn attach_layout(&mut self,layout_manager:Option<Rc<RefCell<Shoji>>>, parent_node:Option<NodeIndex>) {
if layout_manager.is_some() {
self.layout = Some(UILayout::new(layout_manager, parent_node, LayoutStyle::default(),&vec![]));
}
}
fn on_keyboard(&self, key: u32, scancode: u32, action: u32, modifiers: u32) {
panic!("this should be implemented")
}
fn on_character(&self, codepoint: u32) {
panic!("this should be implemented")
}
fn on_mouse_move(&self, xpos: f64, ypos: f64) {
panic!("this should be implemented")
}
fn on_mouse_enter_exit(&self, entered: bool) {
panic!("this should be implemented")
}
fn on_mouse_button(&self, button: i32, action: i32, mods: i32) {
panic!("this should be implemented")
}
fn on_mouse_wheel(&self, xoffset: f64, yoffset: f64) {
panic!("this should be implemented")
}
}
|
#[derive(Debug)]
#[repr(packed)] // repr(C) would add unwanted padding before first_section
pub struct BootLoaderNameTag {
typ: u32,
size: u32,
string: u8,
}
impl BootLoaderNameTag {
pub fn name(&self) -> &str {
unsafe { ::core::str::from_utf8_unchecked(::core::slice::from_raw_parts((&self.string) as *const u8, self.size as usize - 8)) }
}
}
|
fn div_by_three(num: usize) -> bool {
num % 3 == 0
}
fn div_by_five(num: usize) -> bool {
num % 5 == 0
}
fn div_by_fifteen(num: usize) -> bool {
div_by_three(num) && div_by_five(num)
}
fn main() {
for num in (1..101) {
println!("{}",
if div_by_fifteen(num) { "FizzBuzz" }
else if div_by_three(num) { "Fizz" }
else if div_by_five(num) { "Buzz" }
else { "" }
);
}
}
#[test]
fn test_div_by_three() {
if div_by_three(1) {
panic!("One is not three");
}
}
#[test]
fn test_div_by_three_with_three() {
assert!(div_by_three(3), "Three should be three");
}
#[test]
fn test_div_by_five() {
if div_by_five(3) {
panic!("Three is not five");
}
}
#[test]
fn test_div_by_five_with_five() {
assert!(div_by_five(5), "Five should be five");
}
#[test]
fn test_div_by_fifteen() {
if div_by_fifteen(5) {
panic!("Five is not fifteen");
}
}
#[test]
fn test_div_by_fifteen_with_fifteen() {
assert!(div_by_fifteen(15), "Fifteen should be fifteen");
}
|
use std::fs;
use std::io;
use rand::prelude::*;
#[allow(non_snake_case)]
#[derive(Debug)]
struct Registers {
V0: u8, V1: u8, V2: u8, V3: u8, V4: u8, V5: u8, V6: u8, V7: u8,
V8: u8, V9: u8, VA: u8, VB: u8, VC: u8, VD: u8, VE: u8, VF: u8,
I: u16, PC: u16,
}
impl Registers {
fn new() -> Registers {
Registers {
V0: 0, V1: 0, V2: 0, V3: 0, V4: 0, V5: 0, V6: 0, V7: 0,
V8: 0, V9: 0, VA: 0, VB: 0, VC: 0, VD: 0, VE: 0, VF: 0,
I: 0, PC: 0,
}
}
}
#[allow(dead_code)]
#[derive(Debug)]
enum Target_Register {
V0, V1, V2, V3, V4, V5, V6, V7,
V8, V9, VA, VB, VC, VD, VE, VF,
I, PC,
}
impl Target_Register {
fn u8_to_register(value: u8) -> Target_Register {
match value {
0x0 => Target_Register::V0,
0x1 => Target_Register::V1,
0x2 => Target_Register::V2,
0x3 => Target_Register::V3,
0x4 => Target_Register::V4,
0x5 => Target_Register::V5,
0x6 => Target_Register::V6,
0x7 => Target_Register::V7,
0x8 => Target_Register::V8,
0x9 => Target_Register::V9,
0xA => Target_Register::VA,
0xB => Target_Register::VB,
0xC => Target_Register::VC,
0xD => Target_Register::VD,
0xE => Target_Register::VE,
0xF => Target_Register::VF,
_ => Target_Register::PC, // TODO: Handle values outside of 0-F
}
}
}
struct Timers {
// TODO: Implement their automatic decrement
delay: u8,
sound: u8,
}
impl Timers {
fn new() -> Timers {
Timers {
delay: 0,
sound: 0,
}
}
}
#[allow(dead_code)]
#[derive(Debug)]
enum Instruction {
// X, Y represent registers
// N represents values
NOP,
_Call { address: u16 }, // 0NNN
Display, // 00E0 - Clear Screen
Return, // 00EE - Return from subroutine
JUMP { address: u16 }, // 1NNN - Jump to
Call { address: u16 }, // 2NNN - Call subroutine
SKEQ { register: Target_Register, value: u8 }, // 3XNN - Skip next instruction if equal
SKNEQ { register: Target_Register, value: u8 }, // 4XNN - Skip next instruction if not equal
SKREQ { register1: Target_Register, register2: Target_Register }, // 5XY0 - Skip next instruction if X and Y registers are equal
SET { register: Target_Register, value: u8 }, // 6XNN - Sets X to NN
ADD { register: Target_Register, value: u8 }, // 7XNN - Adds NN to X, doesn't affect carry flag
COPYR { register1: Target_Register, register2: Target_Register }, // 8XY0 - Copy Y to X
OR { register1: Target_Register, register2: Target_Register }, // 8XY1 - Set X to X | Y (Bitwise OR)
AND { register1: Target_Register, register2: Target_Register }, // 8XY2 - Set X to X & Y (Bitwise AND)
XOR { register1: Target_Register, register2: Target_Register }, // 8XY3 - Set X to X ^ Y (Bitwise XOR)
ADDR { register1: Target_Register, register2: Target_Register }, // 8XY4 - Add Y to X, affects carry flag
SUBX { register1: Target_Register, register2: Target_Register }, // 8XY5 - Subtract Y from X in X, affects borrow flag
SHFTR { register1: Target_Register, register2: Target_Register }, // 8XY6 - Stores LSB in flag register then shifts X to the right 1
SUBY { register1: Target_Register, register2: Target_Register }, // 8XY7 - Subtract X from Y in X, affects borrow flag
SHFTL { register1: Target_Register, register2: Target_Register }, // 8XYE - Stores MSB in flag register then shifts X to the left 1
SKRNEQ { register1: Target_Register, register2: Target_Register }, // 9XY0 - Skip next instruction if X and Y registers are not equal
SETI { value: u16 }, // ANNN - Set I register to NNN
JMP0 { address: u16 }, // BNNN - Jump to NNN plus V0 register
RAND { register: Target_Register, value: u8 }, // CXNN - Set X to random number & NN
DRAW { register1: Target_Register, register2: Target_Register, height: u8 }, // DXYN - Draw sprite at coords X register, Y register, of N height. Width fixed at 8 pixels. Check documentation for this.
SKKEQ { register: Target_Register }, // EX9E - Skip next instruction if key stored in X is pressed
SKKNEQ { register: Target_Register }, // EXA1 - Skip next instruction if key stored in X isn't pressed
SETXD { register: Target_Register }, // FX07 - Set X to value of delay timer
STORE { register: Target_Register }, // FX0A - Store key press in X (Blocks until key press)
SETD { register: Target_Register }, // FX15 - Set delay timer to X
SETS { register: Target_Register }, // FX18 - Set sound timer to X
ADDI { register: Target_Register }, // FX1E - Add X to I
SPRITE { register: Target_Register }, // FX29 - Set I to address of X for character sprite (Chars 0-F in hex are represented by 4x5 font)
BCD { register: Target_Register }, // FX33 - Binary-Coded Decimal. Check documentation for this.
DUMP { register: Target_Register }, // FX55 - Dumps registers, starting from V0 to X, beginning at memory address in I
LOAD { register: Target_Register }, // FX65 - Fills registers, starting from V0 to X, with values beginning at memory address in I
}
struct CPU {
registers: Registers,
memory: [u8; 4096],
stack: Vec<u16>,
timers: Timers,
}
#[allow(non_snake_case)]
#[allow(dead_code)]
impl CPU {
fn load_rom(&mut self, rom: &String) -> Result<&str, io::Error> {
match fs::read(rom.trim()) {
Ok(x) => {
for y in 0..x.len() {
self.memory[0x200 + y] = x[y];
};
self.registers.PC = 0x200; //Programs begin at this address
Ok("ROM loaded successfully.")
},
Err(e) => Err(e),
}
}
fn fetch_instruction(&mut self) -> u16 {
let mut opcode: u16 = self.memory[self.registers.PC as usize] as u16;
opcode = opcode << 8;
self.registers.PC += 1;
opcode = opcode | self.memory[self.registers.PC as usize] as u16;
self.registers.PC += 1;
opcode
}
fn new() -> CPU {
CPU {
registers: Registers::new(),
memory: [0u8; 4096],
stack: vec![0u16; 16],
timers: Timers::new(),
}
}
fn initialize(&mut self) {
self.registers.V0 = self.registers.V0 ^ self.registers.V0;
self.registers.V1 = self.registers.V1 ^ self.registers.V1;
self.registers.V2 = self.registers.V2 ^ self.registers.V2;
self.registers.V3 = self.registers.V3 ^ self.registers.V3;
self.registers.V4 = self.registers.V4 ^ self.registers.V4;
self.registers.V5 = self.registers.V5 ^ self.registers.V5;
self.registers.V6 = self.registers.V6 ^ self.registers.V6;
self.registers.V7 = self.registers.V7 ^ self.registers.V7;
self.registers.V8 = self.registers.V8 ^ self.registers.V8;
self.registers.V9 = self.registers.V9 ^ self.registers.V9;
self.registers.VA = self.registers.VA ^ self.registers.VA;
self.registers.VB = self.registers.VB ^ self.registers.VB;
self.registers.VC = self.registers.VC ^ self.registers.VC;
self.registers.VD = self.registers.VD ^ self.registers.VD;
self.registers.VE = self.registers.VE ^ self.registers.VE;
self.registers.VF = self.registers.VF ^ self.registers.VF;
self.registers.I = self.registers.I ^ self.registers.I;
self.registers.PC = self.registers.PC ^ self.registers.PC;
self.memory = [0u8; 4096];
self.stack = vec![0u16; 16];
}
fn cycle(&mut self) {
let opcode = self.fetch_instruction();
let instruction = self.parse_opcode(opcode);
self.execute(instruction);
}
fn debug_cycle(&mut self) {
let opcode = self.fetch_instruction();
println!("opcode: {:X}", opcode);
let instruction = self.parse_opcode(opcode);
println!("instruction: {:?}\n", instruction);
self.execute(instruction);
}
fn print_registers_state(&self) {
println!("Current CPU registers
{:?}", self.registers);
}
fn parse_opcode(&mut self, opcode: u16) -> Instruction {
// Decipher opcode and prepare registers accordingly
let mut instruction = Instruction::JUMP { address: 0x200 };
match opcode & 0xF000 {
0x0000 => {
match opcode {
0x0000 => instruction = Instruction::NOP,
0x00E0 => instruction = Instruction::Display,
0x00EE => instruction = Instruction::Return,
_ => eprintln!("Unexpected opcode: {:X}", opcode),
}
},
0x1000 => instruction = Instruction::JUMP { address: opcode & 0x0FFF },
0x2000 => instruction = Instruction::Call { address: opcode & 0x0FFF },
0x3000 => instruction = Instruction::SKEQ { register: Target_Register::u8_to_register(((opcode >> 8) & 0x0F) as u8), value: (opcode & 0x00FF) as u8 },
0x4000 => instruction = Instruction::SKNEQ { register: Target_Register::u8_to_register(((opcode >> 8) & 0x0F) as u8), value: (opcode & 0x00FF) as u8},
0x5000 => instruction = Instruction::SKREQ { register1: Target_Register::u8_to_register(((opcode >> 8) & 0x0F) as u8), register2: Target_Register::u8_to_register(((opcode >> 4) & 0x0F) as u8)},
0x6000 => instruction = Instruction::SET { register: Target_Register::u8_to_register(((opcode >> 8) & 0x0F) as u8), value: (opcode & 0x00FF) as u8},
0x7000 => instruction = Instruction::ADD { register: Target_Register::u8_to_register(((opcode >> 8) & 0x0F) as u8), value: (opcode & 0x00FF) as u8},
0x8000 => {
match opcode & 0xF00F {
0x8000 => instruction = Instruction::COPYR { register1: Target_Register::u8_to_register(((opcode >> 8) & 0x0F) as u8), register2: Target_Register::u8_to_register(((opcode >> 4) & 0x0F) as u8) },
0x8001 => instruction = Instruction::OR { register1: Target_Register::u8_to_register(((opcode >> 8) & 0x0F) as u8), register2: Target_Register::u8_to_register(((opcode >> 4) & 0x0F) as u8) },
0x8002 => instruction = Instruction::AND { register1: Target_Register::u8_to_register(((opcode >> 8) & 0x0F) as u8), register2: Target_Register::u8_to_register(((opcode >> 4) & 0x0F) as u8) },
0x8003 => instruction = Instruction::XOR { register1: Target_Register::u8_to_register(((opcode >> 8) & 0x0F) as u8), register2: Target_Register::u8_to_register(((opcode >> 4) & 0x0F) as u8) },
0x8004 => instruction = Instruction::ADDR { register1: Target_Register::u8_to_register(((opcode >> 8) & 0x0F) as u8), register2: Target_Register::u8_to_register(((opcode >> 4) & 0x0F) as u8) },
0x8005 => instruction = Instruction::SUBX { register1: Target_Register::u8_to_register(((opcode >> 8) & 0x0F) as u8), register2: Target_Register::u8_to_register(((opcode >> 4) & 0x0F) as u8) },
0x8006 => instruction = Instruction::SHFTR { register1: Target_Register::u8_to_register(((opcode >> 8) & 0x0F) as u8), register2: Target_Register::u8_to_register(((opcode >> 4) & 0x0F) as u8) },
0x8007 => instruction = Instruction::SUBY { register1: Target_Register::u8_to_register(((opcode >> 8) & 0x0F) as u8), register2: Target_Register::u8_to_register(((opcode >> 4) & 0x0F) as u8) },
0x800E => instruction = Instruction::SHFTL { register1: Target_Register::u8_to_register(((opcode >> 8) & 0x0F) as u8), register2: Target_Register::u8_to_register(((opcode >> 4) & 0x0F) as u8) },
_ => eprintln!("Unexpected opcode: {:X}", opcode),
}
},
0x9000 => instruction = Instruction::SKRNEQ { register1: Target_Register::u8_to_register(((opcode >> 8) & 0x0F) as u8), register2: Target_Register::u8_to_register(((opcode >> 4) & 0x0F) as u8)},
0xA000 => instruction = Instruction::SETI { value: opcode & 0x0FFF },
0xB000 => instruction = Instruction::JMP0 { address: opcode & 0x0FFF},
0xC000 => instruction = Instruction::RAND { register: Target_Register::u8_to_register(((opcode >> 8) & 0x0F) as u8), value: (opcode & 0x00FF) as u8},
0xD000 => instruction = Instruction::DRAW { register1: Target_Register::u8_to_register(((opcode >> 8) & 0x0F) as u8), register2: Target_Register::u8_to_register(((opcode >> 4) & 0x0F) as u8), height: (opcode & 0x000F) as u8},
0xE000 => {
match opcode & 0xF0FF {
0xE09E => instruction = Instruction::SKKEQ { register: Target_Register::u8_to_register(((opcode >> 8) & 0x0F) as u8) },
0xE0A1 => instruction = Instruction::SKKNEQ { register: Target_Register::u8_to_register(((opcode >> 8) & 0x0F) as u8) },
_ => eprintln!("Unexpected opcode: {:X}", opcode),
}
},
0xF000 => {
match opcode & 0xF0FF {
0xF007 => instruction = Instruction::SETXD { register: Target_Register::u8_to_register(((opcode >> 8) & 0x0F) as u8) },
0xF00A => instruction = Instruction::STORE { register: Target_Register::u8_to_register(((opcode >> 8) & 0x0F) as u8) },
0xF015 => instruction = Instruction::SETD { register: Target_Register::u8_to_register(((opcode >> 8) & 0x0F) as u8) },
0xF018 => instruction = Instruction::SETS { register: Target_Register::u8_to_register(((opcode >> 8) & 0x0F) as u8) },
0xF01E => instruction = Instruction::ADDI { register: Target_Register::u8_to_register(((opcode >> 8) & 0x0F) as u8) },
0xF029 => instruction = Instruction::SPRITE { register: Target_Register::u8_to_register(((opcode >> 8) & 0x0F) as u8) },
0xF033 => instruction = Instruction::BCD { register: Target_Register::u8_to_register(((opcode >> 8) & 0x0F) as u8) },
0xF055 => instruction = Instruction::DUMP { register: Target_Register::u8_to_register(((opcode >> 8) & 0x0F) as u8) },
0xF065 => instruction = Instruction::LOAD { register: Target_Register::u8_to_register(((opcode >> 8) & 0x0F) as u8) },
_ => eprintln!("Unexpected opcode: {:X}", opcode),
}
},
_ => eprintln!("Unexpected opcode: {:X}", opcode),
};
instruction
}
fn execute(&mut self, instruction: Instruction) {
match instruction {
Instruction::NOP => (),
Instruction::_Call { address: a } => self._Call(a),
Instruction::Display => self.Display(),
Instruction::Return => self.Return(),
Instruction::JUMP { address: a } => self.JUMP(a),
Instruction::Call { address: a } => self.Call(a),
Instruction::SKEQ { register: r, value: v } => self.SKEQ(r, v),
Instruction::SKNEQ { register: r, value: v } => self.SKNEQ(r, v),
Instruction::SKREQ { register1: r1, register2: r2 } => self.SKREQ(r1, r2),
Instruction::SET { register: r, value: v } => self.SET(r, v),
Instruction::ADD { register: r, value: v } => self.ADD(r, v),
Instruction::COPYR { register1: r1, register2: r2 } => self.COPYR(r1, r2),
Instruction::OR { register1: r1, register2: r2 } => self.OR(r1, r2),
Instruction::AND { register1: r1, register2: r2 } => self.AND(r1, r2),
Instruction::XOR { register1: r1, register2: r2 } => self.XOR(r1, r2),
Instruction::ADDR { register1: r1, register2: r2 } => self.ADDR(r1, r2),
Instruction::SUBX { register1: r1, register2: r2 } => self.SUBX(r1, r2),
Instruction::SHFTR { register1: r1, register2: r2 } => self.SHFTR(r1, r2),
Instruction::SUBY { register1: r1, register2: r2 } => self.SUBY(r1, r2),
Instruction::SHFTL { register1: r1, register2: r2 } => self.SHFTL(r1, r2),
Instruction::SKRNEQ { register1: r1, register2: r2 } => self.SKRNEQ(r1, r2),
Instruction::SETI { value: v } => self.SETI(v),
Instruction::JMP0 { address: a } => self.JMP0(a),
Instruction::RAND { register: r, value: v } => self.RAND(r, v),
Instruction::DRAW { register1: r1, register2: r2, height: h } => self.DRAW(r1, r2, h),
Instruction::SKKEQ { register: r } => self.SKKEQ(r),
Instruction::SKKNEQ { register: r } => self.SKKNEQ(r),
Instruction::SETXD { register: r } => self.SETXD(r),
Instruction::STORE { register: r } => self.STORE(r),
Instruction::SETD { register: r } => self.SETD(r),
Instruction::SETS { register: r } => self.SETS(r),
Instruction::ADDI { register: r } => self.ADDI(r),
Instruction::SPRITE { register: r } => self.SPRITE(r),
Instruction::BCD { register: r } => self.BCD(r),
Instruction::DUMP { register: r } => self.DUMP(r),
Instruction::LOAD { register: r } => self.LOAD(r),
_ => eprintln!("Unexpected instruction. Last instruction received: {:?}", instruction),
};
}
fn _Call(&mut self, address: u16) {
// TODO: Implement function
// This function calls an RCA 1802 program at an address
}
fn Display(&mut self) {
// TODO: Implement Function
// Clears the screen when called
}
fn Return(&mut self) {
// Handle this better than unwrapping
self.registers.PC = self.stack.pop().unwrap();
}
fn JUMP(&mut self, address: u16) {
self.registers.PC = address;
}
fn Call(&mut self, address: u16) {
self.stack.push(self.registers.PC);
self.registers.PC = address;
}
fn SKEQ(&mut self, register: Target_Register, value: u8) {
// Skip the next instruction if Register == Value
let comp_val = match register {
Target_Register::V0 => if self.registers.V0 == value { true } else { false },
Target_Register::V1 => if self.registers.V1 == value { true } else { false },
Target_Register::V2 => if self.registers.V2 == value { true } else { false },
Target_Register::V3 => if self.registers.V3 == value { true } else { false },
Target_Register::V4 => if self.registers.V4 == value { true } else { false },
Target_Register::V5 => if self.registers.V5 == value { true } else { false },
Target_Register::V6 => if self.registers.V6 == value { true } else { false },
Target_Register::V7 => if self.registers.V7 == value { true } else { false },
Target_Register::V8 => if self.registers.V8 == value { true } else { false },
Target_Register::V9 => if self.registers.V9 == value { true } else { false },
Target_Register::VA => if self.registers.VA == value { true } else { false },
Target_Register::VB => if self.registers.VB == value { true } else { false },
Target_Register::VC => if self.registers.VC == value { true } else { false },
Target_Register::VD => if self.registers.VD == value { true } else { false },
Target_Register::VE => if self.registers.VE == value { true } else { false },
Target_Register::VF => if self.registers.VF == value { true } else { false },
Target_Register::I => if self.registers.I == value as u16 { true } else { false },
Target_Register::PC => if self.registers.PC == value as u16 { true } else { false },
};
if comp_val {
self.registers.PC += 2;
};
}
fn SKNEQ(&mut self, register: Target_Register, value: u8) {
let comp_val = match register {
Target_Register::V0 => if self.registers.V0 != value { true } else { false },
Target_Register::V1 => if self.registers.V1 != value { true } else { false },
Target_Register::V2 => if self.registers.V2 != value { true } else { false },
Target_Register::V3 => if self.registers.V3 != value { true } else { false },
Target_Register::V4 => if self.registers.V4 != value { true } else { false },
Target_Register::V5 => if self.registers.V5 != value { true } else { false },
Target_Register::V6 => if self.registers.V6 != value { true } else { false },
Target_Register::V7 => if self.registers.V7 != value { true } else { false },
Target_Register::V8 => if self.registers.V8 != value { true } else { false },
Target_Register::V9 => if self.registers.V9 != value { true } else { false },
Target_Register::VA => if self.registers.VA != value { true } else { false },
Target_Register::VB => if self.registers.VB != value { true } else { false },
Target_Register::VC => if self.registers.VC != value { true } else { false },
Target_Register::VD => if self.registers.VD != value { true } else { false },
Target_Register::VE => if self.registers.VE != value { true } else { false },
Target_Register::VF => if self.registers.VF != value { true } else { false },
Target_Register::I => if self.registers.I != value as u16 { true } else { false },
Target_Register::PC => if self.registers.PC != value as u16 { true } else { false },
};
if comp_val {
self.registers.PC += 2;
};
}
fn SKREQ(&mut self, register1: Target_Register, register2: Target_Register) {
// Skip next instruction if specified registers are equal
let r1 = match register1 {
Target_Register::V0 => self.registers.V0,
Target_Register::V1 => self.registers.V1,
Target_Register::V2 => self.registers.V2,
Target_Register::V3 => self.registers.V3,
Target_Register::V4 => self.registers.V4,
Target_Register::V5 => self.registers.V5,
Target_Register::V6 => self.registers.V6,
Target_Register::V7 => self.registers.V7,
Target_Register::V8 => self.registers.V8,
Target_Register::V9 => self.registers.V9,
Target_Register::VA => self.registers.VA,
Target_Register::VB => self.registers.VB,
Target_Register::VC => self.registers.VC,
Target_Register::VD => self.registers.VD,
Target_Register::VE => self.registers.VE,
Target_Register::VF => self.registers.VF,
//Target_Register::I => self.registers.I = value as u16,
//Target_Register::PC => self.registers.PC = value as u16,
// TODO: Handle this case properly
_ => 0,
};
let r2 = match register2 {
Target_Register::V0 => self.registers.V0,
Target_Register::V1 => self.registers.V1,
Target_Register::V2 => self.registers.V2,
Target_Register::V3 => self.registers.V3,
Target_Register::V4 => self.registers.V4,
Target_Register::V5 => self.registers.V5,
Target_Register::V6 => self.registers.V6,
Target_Register::V7 => self.registers.V7,
Target_Register::V8 => self.registers.V8,
Target_Register::V9 => self.registers.V9,
Target_Register::VA => self.registers.VA,
Target_Register::VB => self.registers.VB,
Target_Register::VC => self.registers.VC,
Target_Register::VD => self.registers.VD,
Target_Register::VE => self.registers.VE,
Target_Register::VF => self.registers.VF,
//Target_Register::I => self.registers.I = value as u16,
//Target_Register::PC => self.registers.PC = value as u16,
// TODO: Handle this case properly
_ => 0,
};
if r1 == r2 {
self.registers.PC += 2;
};
}
fn SET(&mut self, register: Target_Register, value: u8) {
match register {
Target_Register::V0 => self.registers.V0 = value,
Target_Register::V1 => self.registers.V1 = value,
Target_Register::V2 => self.registers.V2 = value,
Target_Register::V3 => self.registers.V3 = value,
Target_Register::V4 => self.registers.V4 = value,
Target_Register::V5 => self.registers.V5 = value,
Target_Register::V6 => self.registers.V6 = value,
Target_Register::V7 => self.registers.V7 = value,
Target_Register::V8 => self.registers.V8 = value,
Target_Register::V9 => self.registers.V9 = value,
Target_Register::VA => self.registers.VA = value,
Target_Register::VB => self.registers.VB = value,
Target_Register::VC => self.registers.VC = value,
Target_Register::VD => self.registers.VD = value,
Target_Register::VE => self.registers.VE = value,
Target_Register::VF => self.registers.VF = value,
Target_Register::I => self.registers.I = value as u16,
Target_Register::PC => self.registers.PC = value as u16,
};
}
fn ADD(&mut self, register: Target_Register, value: u8) {
// Carry flag is not taken into account with this instruction
match register {
Target_Register::V0 => self.registers.V0 = self.registers.V0.wrapping_add(value),
Target_Register::V1 => self.registers.V1 = self.registers.V1.wrapping_add(value),
Target_Register::V2 => self.registers.V2 = self.registers.V2.wrapping_add(value),
Target_Register::V3 => self.registers.V3 = self.registers.V3.wrapping_add(value),
Target_Register::V4 => self.registers.V4 = self.registers.V4.wrapping_add(value),
Target_Register::V5 => self.registers.V5 = self.registers.V5.wrapping_add(value),
Target_Register::V6 => self.registers.V6 = self.registers.V6.wrapping_add(value),
Target_Register::V7 => self.registers.V7 = self.registers.V7.wrapping_add(value),
Target_Register::V8 => self.registers.V8 = self.registers.V8.wrapping_add(value),
Target_Register::V9 => self.registers.V9 = self.registers.V9.wrapping_add(value),
Target_Register::VA => self.registers.VA = self.registers.VA.wrapping_add(value),
Target_Register::VB => self.registers.VB = self.registers.VB.wrapping_add(value),
Target_Register::VC => self.registers.VC = self.registers.VC.wrapping_add(value),
Target_Register::VD => self.registers.VD = self.registers.VD.wrapping_add(value),
Target_Register::VE => self.registers.VE = self.registers.VE.wrapping_add(value),
Target_Register::VF => self.registers.VF = self.registers.VF.wrapping_add(value),
Target_Register::I => self.registers.I += value as u16,
Target_Register::PC => self.registers.PC += value as u16,
};
}
fn COPYR(&mut self, register1: Target_Register, register2: Target_Register) {
// Copy value from register2 to register1
let r2 = match register2 {
Target_Register::V0 => self.registers.V0,
Target_Register::V1 => self.registers.V1,
Target_Register::V2 => self.registers.V2,
Target_Register::V3 => self.registers.V3,
Target_Register::V4 => self.registers.V4,
Target_Register::V5 => self.registers.V5,
Target_Register::V6 => self.registers.V6,
Target_Register::V7 => self.registers.V7,
Target_Register::V8 => self.registers.V8,
Target_Register::V9 => self.registers.V9,
Target_Register::VA => self.registers.VA,
Target_Register::VB => self.registers.VB,
Target_Register::VC => self.registers.VC,
Target_Register::VD => self.registers.VD,
Target_Register::VE => self.registers.VE,
Target_Register::VF => self.registers.VF,
//Target_Register::I => self.registers.I = value as u16,
//Target_Register::PC => self.registers.PC = value as u16,
// TODO: Handle this case properly
_ => 0,
};
match register1 {
Target_Register::V0 => self.registers.V0 = r2,
Target_Register::V1 => self.registers.V1 = r2,
Target_Register::V2 => self.registers.V2 = r2,
Target_Register::V3 => self.registers.V3 = r2,
Target_Register::V4 => self.registers.V4 = r2,
Target_Register::V5 => self.registers.V5 = r2,
Target_Register::V6 => self.registers.V6 = r2,
Target_Register::V7 => self.registers.V7 = r2,
Target_Register::V8 => self.registers.V8 = r2,
Target_Register::V9 => self.registers.V9 = r2,
Target_Register::VA => self.registers.VA = r2,
Target_Register::VB => self.registers.VB = r2,
Target_Register::VC => self.registers.VC = r2,
Target_Register::VD => self.registers.VD = r2,
Target_Register::VE => self.registers.VE = r2,
Target_Register::VF => self.registers.VF = r2,
//Target_Register::I => self.registers.I = value as u16,
//Target_Register::PC => self.registers.PC = value as u16,
// TODO: Handle this case properly
_ => (),
};
}
fn OR(&mut self, register1: Target_Register, register2: Target_Register) {
// Register1 = Register1 | Register2
let r2 = match register2 {
Target_Register::V0 => self.registers.V0,
Target_Register::V1 => self.registers.V1,
Target_Register::V2 => self.registers.V2,
Target_Register::V3 => self.registers.V3,
Target_Register::V4 => self.registers.V4,
Target_Register::V5 => self.registers.V5,
Target_Register::V6 => self.registers.V6,
Target_Register::V7 => self.registers.V7,
Target_Register::V8 => self.registers.V8,
Target_Register::V9 => self.registers.V9,
Target_Register::VA => self.registers.VA,
Target_Register::VB => self.registers.VB,
Target_Register::VC => self.registers.VC,
Target_Register::VD => self.registers.VD,
Target_Register::VE => self.registers.VE,
Target_Register::VF => self.registers.VF,
//Target_Register::I => self.registers.I = value as u16,
//Target_Register::PC => self.registers.PC = value as u16,
// TODO: Handle this case properly
_ => 0,
};
match register1 {
Target_Register::V0 => self.registers.V0 |= r2,
Target_Register::V1 => self.registers.V1 |= r2,
Target_Register::V2 => self.registers.V2 |= r2,
Target_Register::V3 => self.registers.V3 |= r2,
Target_Register::V4 => self.registers.V4 |= r2,
Target_Register::V5 => self.registers.V5 |= r2,
Target_Register::V6 => self.registers.V6 |= r2,
Target_Register::V7 => self.registers.V7 |= r2,
Target_Register::V8 => self.registers.V8 |= r2,
Target_Register::V9 => self.registers.V9 |= r2,
Target_Register::VA => self.registers.VA |= r2,
Target_Register::VB => self.registers.VB |= r2,
Target_Register::VC => self.registers.VC |= r2,
Target_Register::VD => self.registers.VD |= r2,
Target_Register::VE => self.registers.VE |= r2,
Target_Register::VF => self.registers.VF |= r2,
//Target_Register::I => self.registers.I = value as u16,
//Target_Register::PC => self.registers.PC = value as u16,
// TODO: Handle this case properly
_ => (),
};
}
fn AND(&mut self, register1: Target_Register, register2: Target_Register) {
// Register1 = Register1 & Register2
let r2 = match register2 {
Target_Register::V0 => self.registers.V0,
Target_Register::V1 => self.registers.V1,
Target_Register::V2 => self.registers.V2,
Target_Register::V3 => self.registers.V3,
Target_Register::V4 => self.registers.V4,
Target_Register::V5 => self.registers.V5,
Target_Register::V6 => self.registers.V6,
Target_Register::V7 => self.registers.V7,
Target_Register::V8 => self.registers.V8,
Target_Register::V9 => self.registers.V9,
Target_Register::VA => self.registers.VA,
Target_Register::VB => self.registers.VB,
Target_Register::VC => self.registers.VC,
Target_Register::VD => self.registers.VD,
Target_Register::VE => self.registers.VE,
Target_Register::VF => self.registers.VF,
//Target_Register::I => self.registers.I = value as u16,
//Target_Register::PC => self.registers.PC = value as u16,
// TODO: Handle this case properly
_ => 0,
};
match register1 {
Target_Register::V0 => self.registers.V0 &= r2,
Target_Register::V1 => self.registers.V1 &= r2,
Target_Register::V2 => self.registers.V2 &= r2,
Target_Register::V3 => self.registers.V3 &= r2,
Target_Register::V4 => self.registers.V4 &= r2,
Target_Register::V5 => self.registers.V5 &= r2,
Target_Register::V6 => self.registers.V6 &= r2,
Target_Register::V7 => self.registers.V7 &= r2,
Target_Register::V8 => self.registers.V8 &= r2,
Target_Register::V9 => self.registers.V9 &= r2,
Target_Register::VA => self.registers.VA &= r2,
Target_Register::VB => self.registers.VB &= r2,
Target_Register::VC => self.registers.VC &= r2,
Target_Register::VD => self.registers.VD &= r2,
Target_Register::VE => self.registers.VE &= r2,
Target_Register::VF => self.registers.VF &= r2,
//Target_Register::I => self.registers.I = value as u16,
//Target_Register::PC => self.registers.PC = value as u16,
// TODO: Handle this case properly
_ => (),
};
}
fn XOR(&mut self, register1: Target_Register, register2: Target_Register) {
// Register1 = Register1 ^ Register2
let r2 = match register2 {
Target_Register::V0 => self.registers.V0,
Target_Register::V1 => self.registers.V1,
Target_Register::V2 => self.registers.V2,
Target_Register::V3 => self.registers.V3,
Target_Register::V4 => self.registers.V4,
Target_Register::V5 => self.registers.V5,
Target_Register::V6 => self.registers.V6,
Target_Register::V7 => self.registers.V7,
Target_Register::V8 => self.registers.V8,
Target_Register::V9 => self.registers.V9,
Target_Register::VA => self.registers.VA,
Target_Register::VB => self.registers.VB,
Target_Register::VC => self.registers.VC,
Target_Register::VD => self.registers.VD,
Target_Register::VE => self.registers.VE,
Target_Register::VF => self.registers.VF,
//Target_Register::I => self.registers.I = value as u16,
//Target_Register::PC => self.registers.PC = value as u16,
// TODO: Handle this case properly
_ => 0,
};
match register1 {
Target_Register::V0 => self.registers.V0 ^= r2,
Target_Register::V1 => self.registers.V1 ^= r2,
Target_Register::V2 => self.registers.V2 ^= r2,
Target_Register::V3 => self.registers.V3 ^= r2,
Target_Register::V4 => self.registers.V4 ^= r2,
Target_Register::V5 => self.registers.V5 ^= r2,
Target_Register::V6 => self.registers.V6 ^= r2,
Target_Register::V7 => self.registers.V7 ^= r2,
Target_Register::V8 => self.registers.V8 ^= r2,
Target_Register::V9 => self.registers.V9 ^= r2,
Target_Register::VA => self.registers.VA ^= r2,
Target_Register::VB => self.registers.VB ^= r2,
Target_Register::VC => self.registers.VC ^= r2,
Target_Register::VD => self.registers.VD ^= r2,
Target_Register::VE => self.registers.VE ^= r2,
Target_Register::VF => self.registers.VF ^= r2,
//Target_Register::I => self.registers.I = value as u16,
//Target_Register::PC => self.registers.PC = value as u16,
// TODO: Handle this case properly
_ => (),
};
}
fn ADDR(&mut self, register1: Target_Register, register2: Target_Register) {
// Register1 += Register2 Affects the carry flag (set VF to 1)
let r2 = match register2 {
Target_Register::V0 => self.registers.V0,
Target_Register::V1 => self.registers.V1,
Target_Register::V2 => self.registers.V2,
Target_Register::V3 => self.registers.V3,
Target_Register::V4 => self.registers.V4,
Target_Register::V5 => self.registers.V5,
Target_Register::V6 => self.registers.V6,
Target_Register::V7 => self.registers.V7,
Target_Register::V8 => self.registers.V8,
Target_Register::V9 => self.registers.V9,
Target_Register::VA => self.registers.VA,
Target_Register::VB => self.registers.VB,
Target_Register::VC => self.registers.VC,
Target_Register::VD => self.registers.VD,
Target_Register::VE => self.registers.VE,
Target_Register::VF => self.registers.VF,
//Target_Register::I => self.registers.I = value as u16,
//Target_Register::PC => self.registers.PC = value as u16,
// TODO: Handle this case properly
_ => 0,
};
match register1 {
Target_Register::V0 => {
let (value, flag) = self.registers.V0.overflowing_add(r2);
self.registers.V0 = value;
if flag {
self.registers.VF = 1;
};
},
Target_Register::V1 => {
let (value, flag) = self.registers.V1.overflowing_add(r2);
self.registers.V1 = value;
if flag {
self.registers.VF = 1;
};
},
Target_Register::V2 => {
let (value, flag) = self.registers.V2.overflowing_add(r2);
self.registers.V2 = value;
if flag {
self.registers.VF = 1;
};
},
Target_Register::V3 => {
let (value, flag) = self.registers.V3.overflowing_add(r2);
self.registers.V3 = value;
if flag {
self.registers.VF = 1;
};
},
Target_Register::V4 => {
let (value, flag) = self.registers.V4.overflowing_add(r2);
self.registers.V4 = value;
if flag {
self.registers.VF = 1;
};
},
Target_Register::V5 => {
let (value, flag) = self.registers.V5.overflowing_add(r2);
self.registers.V5 = value;
if flag {
self.registers.VF = 1;
};
},
Target_Register::V6 => {
let (value, flag) = self.registers.V6.overflowing_add(r2);
self.registers.V6 = value;
if flag {
self.registers.VF = 1;
};
},
Target_Register::V7 => {
let (value, flag) = self.registers.V7.overflowing_add(r2);
self.registers.V7 = value;
if flag {
self.registers.VF = 1;
};
},
Target_Register::V8 => {
let (value, flag) = self.registers.V8.overflowing_add(r2);
self.registers.V8 = value;
if flag {
self.registers.VF = 1;
};
},
Target_Register::V9 => {
let (value, flag) = self.registers.V9.overflowing_add(r2);
self.registers.V9 = value;
if flag {
self.registers.VF = 1;
};
},
Target_Register::VA => {
let (value, flag) = self.registers.VA.overflowing_add(r2);
self.registers.VA = value;
if flag {
self.registers.VF = 1;
};
},
Target_Register::VB => {
let (value, flag) = self.registers.VB.overflowing_add(r2);
self.registers.VB = value;
if flag {
self.registers.VF = 1;
};
},
Target_Register::VC => {
let (value, flag) = self.registers.VC.overflowing_add(r2);
self.registers.VC = value;
if flag {
self.registers.VF = 1;
};
},
Target_Register::VD => {
let (value, flag) = self.registers.VD.overflowing_add(r2);
self.registers.VD = value;
if flag {
self.registers.VF = 1;
};
},
Target_Register::VE => {
let (value, flag) = self.registers.VE.overflowing_add(r2);
self.registers.VE = value;
if flag {
self.registers.VF = 1;
};
},
//Target_Register::VF => self.registers.VF,
//Target_Register::I => self.registers.I = value as u16,
//Target_Register::PC => self.registers.PC = value as u16,
// TODO: Handle this case properly
_ => (),
};
}
fn SUBX(&mut self, register1: Target_Register, register2: Target_Register) {
// Register1 -= Register2 Affects Borrow flag
let r2 = match register2 {
Target_Register::V0 => self.registers.V0,
Target_Register::V1 => self.registers.V1,
Target_Register::V2 => self.registers.V2,
Target_Register::V3 => self.registers.V3,
Target_Register::V4 => self.registers.V4,
Target_Register::V5 => self.registers.V5,
Target_Register::V6 => self.registers.V6,
Target_Register::V7 => self.registers.V7,
Target_Register::V8 => self.registers.V8,
Target_Register::V9 => self.registers.V9,
Target_Register::VA => self.registers.VA,
Target_Register::VB => self.registers.VB,
Target_Register::VC => self.registers.VC,
Target_Register::VD => self.registers.VD,
Target_Register::VE => self.registers.VE,
//Target_Register::VF => self.registers.VF,
// TODO: Handle this case properly
_ => 0,
};
match register1 {
Target_Register::V0 => {
let (value, flag) = self.registers.V0.overflowing_sub(r2);
self.registers.V0 = value;
if flag {
self.registers.VF = 1;
};
},
Target_Register::V1 => {
let (value, flag) = self.registers.V1.overflowing_sub(r2);
self.registers.V1 = value;
if flag {
self.registers.VF = 1;
};
},
Target_Register::V2 => {
let (value, flag) = self.registers.V2.overflowing_sub(r2);
self.registers.V2 = value;
if flag {
self.registers.VF = 1;
};
},
Target_Register::V3 => {
let (value, flag) = self.registers.V3.overflowing_sub(r2);
self.registers.V3 = value;
if flag {
self.registers.VF = 1;
};
},
Target_Register::V4 => {
let (value, flag) = self.registers.V4.overflowing_sub(r2);
self.registers.V4 = value;
if flag {
self.registers.VF = 1;
};
},
Target_Register::V5 => {
let (value, flag) = self.registers.V5.overflowing_sub(r2);
self.registers.V5 = value;
if flag {
self.registers.VF = 1;
};
},
Target_Register::V6 => {
let (value, flag) = self.registers.V6.overflowing_sub(r2);
self.registers.V6 = value;
if flag {
self.registers.VF = 1;
};
},
Target_Register::V7 => {
let (value, flag) = self.registers.V7.overflowing_sub(r2);
self.registers.V7 = value;
if flag {
self.registers.VF = 1;
};
},
Target_Register::V8 => {
let (value, flag) = self.registers.V8.overflowing_sub(r2);
self.registers.V8 = value;
if flag {
self.registers.VF = 1;
};
},
Target_Register::V9 => {
let (value, flag) = self.registers.V9.overflowing_sub(r2);
self.registers.V9 = value;
if flag {
self.registers.VF = 1;
};
},
Target_Register::VA => {
let (value, flag) = self.registers.VA.overflowing_sub(r2);
self.registers.VA = value;
if flag {
self.registers.VF = 1;
};
},
Target_Register::VB => {
let (value, flag) = self.registers.VB.overflowing_sub(r2);
self.registers.VB = value;
if flag {
self.registers.VF = 1;
};
},
Target_Register::VC => {
let (value, flag) = self.registers.VC.overflowing_sub(r2);
self.registers.VC = value;
if flag {
self.registers.VF = 1;
};
},
Target_Register::VD => {
let (value, flag) = self.registers.VD.overflowing_sub(r2);
self.registers.VD = value;
if flag {
self.registers.VF = 1;
};
},
Target_Register::VE => {
let (value, flag) = self.registers.VE.overflowing_sub(r2);
self.registers.VE = value;
if flag {
self.registers.VF = 1;
};
},
//Target_Register::VF => self.registers.VF,
// TODO: Handle this case properly
_ => (),
};
}
fn SHFTR(&mut self, register1: Target_Register, register2: Target_Register) {
// TODO: Implement Function
// Store LeastSignificantBit in flag register then shift register1 to the right by 1
}
fn SUBY(&mut self, register1: Target_Register, register2: Target_Register) {
// TODO: Implement Function
// Register1 = Register2 - Register1 Affects Borrow flag
}
fn SHFTL(&mut self, register1: Target_Register, register2: Target_Register) {
// TODO: Implement Function
// Store MostSignificantBit in flag register then shift register1 to the left by 1
}
fn SKRNEQ(&mut self, register1: Target_Register, register2: Target_Register) {
// Skip next instruction if register1 and register2 are not equal
let r1 = match register1 {
Target_Register::V0 => self.registers.V0,
Target_Register::V1 => self.registers.V1,
Target_Register::V2 => self.registers.V2,
Target_Register::V3 => self.registers.V3,
Target_Register::V4 => self.registers.V4,
Target_Register::V5 => self.registers.V5,
Target_Register::V6 => self.registers.V6,
Target_Register::V7 => self.registers.V7,
Target_Register::V8 => self.registers.V8,
Target_Register::V9 => self.registers.V9,
Target_Register::VA => self.registers.VA,
Target_Register::VB => self.registers.VB,
Target_Register::VC => self.registers.VC,
Target_Register::VD => self.registers.VD,
Target_Register::VE => self.registers.VE,
Target_Register::VF => self.registers.VF,
//Target_Register::I => self.registers.I = value as u16,
//Target_Register::PC => self.registers.PC = value as u16,
// TODO: Handle this case properly
_ => 0,
};
let r2 = match register2 {
Target_Register::V0 => self.registers.V0,
Target_Register::V1 => self.registers.V1,
Target_Register::V2 => self.registers.V2,
Target_Register::V3 => self.registers.V3,
Target_Register::V4 => self.registers.V4,
Target_Register::V5 => self.registers.V5,
Target_Register::V6 => self.registers.V6,
Target_Register::V7 => self.registers.V7,
Target_Register::V8 => self.registers.V8,
Target_Register::V9 => self.registers.V9,
Target_Register::VA => self.registers.VA,
Target_Register::VB => self.registers.VB,
Target_Register::VC => self.registers.VC,
Target_Register::VD => self.registers.VD,
Target_Register::VE => self.registers.VE,
Target_Register::VF => self.registers.VF,
//Target_Register::I => self.registers.I = value as u16,
//Target_Register::PC => self.registers.PC = value as u16,
// TODO: Handle this case properly
_ => 0,
};
if r1 != r2 {
self.registers.PC += 2;
};
}
fn SETI(&mut self, value: u16) {
self.registers.I = value;
}
fn JMP0(&mut self, address: u16) {
// TODO: Implement Function
// PC = address + V0 register
}
fn RAND(&mut self, register: Target_Register, value: u8) {
// Generate random number then call SET()
let mut number: u8 = random();
number &= value;
self.SET(register, number);
}
fn DRAW(&mut self, register1: Target_Register, register2: Target_Register, height: u8) {
// TODO: Graphics
// pull value from register1 and register 2 to use as X and Y coords
}
fn SKKEQ(&mut self, register: Target_Register) {
// TODO: Implement Function
// Skip next instruction if key stored in register is pressed
}
fn SKKNEQ(&mut self, register: Target_Register) {
// TODO: Implement Function
// Skip next instruction if key stored in register is not pressed
}
fn SETXD(&mut self, register: Target_Register) {
// register = delay timer
match register {
Target_Register::V0 => self.registers.V0 = self.timers.delay,
Target_Register::V1 => self.registers.V1 = self.timers.delay,
Target_Register::V2 => self.registers.V2 = self.timers.delay,
Target_Register::V3 => self.registers.V3 = self.timers.delay,
Target_Register::V4 => self.registers.V4 = self.timers.delay,
Target_Register::V5 => self.registers.V5 = self.timers.delay,
Target_Register::V6 => self.registers.V6 = self.timers.delay,
Target_Register::V7 => self.registers.V7 = self.timers.delay,
Target_Register::V8 => self.registers.V8 = self.timers.delay,
Target_Register::V9 => self.registers.V9 = self.timers.delay,
Target_Register::VA => self.registers.VA = self.timers.delay,
Target_Register::VB => self.registers.VB = self.timers.delay,
Target_Register::VC => self.registers.VC = self.timers.delay,
Target_Register::VD => self.registers.VD = self.timers.delay,
Target_Register::VE => self.registers.VE = self.timers.delay,
// TODO: Handle this case properly
_ => (),
};
}
fn STORE(&mut self, register: Target_Register) {
// TODO: Implement Function
// Store key press in register, blocks until key press
}
fn SETD(&mut self, register: Target_Register) {
// Set delay time to register
self.timers.delay = match register {
Target_Register::V0 => self.registers.V0,
Target_Register::V1 => self.registers.V1,
Target_Register::V2 => self.registers.V2,
Target_Register::V3 => self.registers.V3,
Target_Register::V4 => self.registers.V4,
Target_Register::V5 => self.registers.V5,
Target_Register::V6 => self.registers.V6,
Target_Register::V7 => self.registers.V7,
Target_Register::V8 => self.registers.V8,
Target_Register::V9 => self.registers.V9,
Target_Register::VA => self.registers.VA,
Target_Register::VB => self.registers.VB,
Target_Register::VC => self.registers.VC,
Target_Register::VD => self.registers.VD,
Target_Register::VE => self.registers.VE,
// TODO: Handle this case properly
_ => 0,
};
}
fn SETS(&mut self, register: Target_Register) {
// Set sound timer to register
self.timers.sound = match register {
Target_Register::V0 => self.registers.V0,
Target_Register::V1 => self.registers.V1,
Target_Register::V2 => self.registers.V2,
Target_Register::V3 => self.registers.V3,
Target_Register::V4 => self.registers.V4,
Target_Register::V5 => self.registers.V5,
Target_Register::V6 => self.registers.V6,
Target_Register::V7 => self.registers.V7,
Target_Register::V8 => self.registers.V8,
Target_Register::V9 => self.registers.V9,
Target_Register::VA => self.registers.VA,
Target_Register::VB => self.registers.VB,
Target_Register::VC => self.registers.VC,
Target_Register::VD => self.registers.VD,
Target_Register::VE => self.registers.VE,
// TODO: Handle this case properly
_ => 0,
};
}
fn ADDI(&mut self, register: Target_Register) {
// Add value in register X to register I
match register {
Target_Register::V0 => self.registers.I += self.registers.V0 as u16,
Target_Register::V1 => self.registers.I += self.registers.V1 as u16,
Target_Register::V2 => self.registers.I += self.registers.V2 as u16,
Target_Register::V3 => self.registers.I += self.registers.V3 as u16,
Target_Register::V4 => self.registers.I += self.registers.V4 as u16,
Target_Register::V5 => self.registers.I += self.registers.V5 as u16,
Target_Register::V6 => self.registers.I += self.registers.V6 as u16,
Target_Register::V7 => self.registers.I += self.registers.V7 as u16,
Target_Register::V8 => self.registers.I += self.registers.V8 as u16,
Target_Register::V9 => self.registers.I += self.registers.V9 as u16,
Target_Register::VA => self.registers.I += self.registers.VA as u16,
Target_Register::VB => self.registers.I += self.registers.VB as u16,
Target_Register::VC => self.registers.I += self.registers.VC as u16,
Target_Register::VD => self.registers.I += self.registers.VD as u16,
Target_Register::VE => self.registers.I += self.registers.VE as u16,
Target_Register::VF => self.registers.I += self.registers.VF as u16,
Target_Register::I => self.registers.I += self.registers.I,
Target_Register::PC => self.registers.I += self.registers.PC,
};
}
fn SPRITE(&mut self, register: Target_Register) {
// TODO: Implement Function
// Set register I to address of register (Chars 0-F in hex represented by 4x5 font)
}
fn BCD(&mut self, register: Target_Register) {
// TODO: Implement Function
// Check documentation for this
}
fn DUMP(&mut self, register: Target_Register) {
// TODO: Implement Function
// Dump registers from V0 to register specified at mem address in register I
}
fn LOAD(&mut self, register: Target_Register) {
// TODO: Implement Function
// Load registers from V0 to register specified at mem address in register I
}
}
fn main() {
let mut chip8 = CPU::new();
let mut input = String::new();
println!("Name of file: ");
let input_result = io::stdin().read_line(&mut input);
if let Ok(x) = input_result {
println!("Input grabbed successfully: return value - {}", x);
};
match input_result {
Ok(x) => {
if let Ok(x) = chip8.load_rom(&input) {
// Loop in here
debug_loop(&mut chip8);
} else {
eprintln!("Error opening the file.");
};
},
Err(e) => eprintln!("Something went wrong with your input. Please try again."),
};
}
fn debug_loop(chip8: &mut CPU) {
let mut input = String::new();
let mut sentinel = true;
while sentinel {
println!("Enter c to run CPU cycle, s to skip through 10 cycles, p to print the current state of the registers, or b to break and terminate the program.");
input.clear();
if let Ok(_x) = io::stdin().read_line(&mut input) {
// TODO: Handle this better
match input.trim() {
"c" => chip8.debug_cycle(),
"p" => chip8.print_registers_state(),
"b" => sentinel = false,
"s" => {
for _ in 0..10 {
chip8.cycle();
};
},
_ => println!("Please enter correct c, p, or b"),
};
};
};
}
|
#[macro_use]
extern crate cfg_if;
extern crate failure;
extern crate libc;
extern crate object;
extern crate uuid;
#[cfg(target_os="macos")]
#[macro_use]
extern crate core_foundation;
#[cfg(target_os="macos")]
extern crate core_foundation_sys;
use failure::Error;
use object::{File, Object};
use std::fmt::Write;
use std::fs;
use std::path::{Path, PathBuf};
use uuid::Uuid;
cfg_if! {
if #[cfg(unix)] {
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
fn path_from_bytes(bytes: &[u8]) -> Result<&OsStr, Error> {
Ok(OsStr::from_bytes(bytes))
}
} else {
use std::str;
fn path_from_bytes(bytes: &[u8]) -> Result<&str, str::Utf8Error> {
str::from_utf8(bytes)
}
}
}
#[cfg(target_os="macos")]
mod dsym {
use core_foundation::array::{CFArray, CFArrayRef};
use core_foundation::base::{CFType, CFTypeRef, TCFType};
use core_foundation::string::CFString;
use core_foundation_sys::base::{CFAllocatorRef, CFIndex, CFOptionFlags, CFRelease, CFTypeID,
kCFAllocatorDefault};
use core_foundation_sys::string::CFStringRef;
use failure::{self, Error};
use libc::c_void;
use std::path::{Path, PathBuf};
use std::ptr;
use uuid::Uuid;
type Boolean = ::std::os::raw::c_uchar;
//const TRUE: Boolean = 1;
const FALSE: Boolean = 0;
#[repr(C)]
struct __MDQuery(c_void);
type MDQueryRef = *mut __MDQuery;
#[repr(C)]
struct __MDItem(c_void);
type MDItemRef = *mut __MDItem;
#[allow(non_upper_case_globals)]
const kMDQuerySynchronous: CFOptionFlags = 1;
#[link(name = "CoreServices", kind = "framework")]
extern "C" {
#[link_name="\u{1}_MDQueryCreate"]
fn MDQueryCreate(allocator: CFAllocatorRef,
queryString: CFStringRef,
valueListAttrs: CFArrayRef,
sortingAttrs: CFArrayRef)
-> MDQueryRef;
#[link_name = "\u{1}_MDQueryGetTypeID"]
fn MDQueryGetTypeID() -> CFTypeID;
#[link_name = "\u{1}_MDQueryExecute"]
fn MDQueryExecute(query: MDQueryRef,
optionFlags: CFOptionFlags)
-> Boolean;
#[link_name = "\u{1}_MDQueryGetResultCount"]
fn MDQueryGetResultCount(query: MDQueryRef) -> CFIndex;
#[link_name = "\u{1}_MDQueryGetResultAtIndex"]
fn MDQueryGetResultAtIndex(query: MDQueryRef,
idx: CFIndex)
-> *const ::std::os::raw::c_void;
#[link_name = "\u{1}_MDItemCreate"]
fn MDItemCreate(allocator: CFAllocatorRef, path: CFStringRef) -> MDItemRef;
#[link_name = "\u{1}_MDItemGetTypeID"]
pub fn MDItemGetTypeID() -> CFTypeID;
#[link_name = "\u{1}_MDItemCopyAttribute"]
fn MDItemCopyAttribute(item: MDItemRef,
name: CFStringRef)
-> CFTypeRef;
#[link_name = "\u{1}_kMDItemPath"]
static mut kMDItemPath: CFStringRef;
}
struct MDQuery(MDQueryRef);
impl MDQuery {
pub fn create(query_string: &str) -> Result<MDQuery, Error> {
let cf_query_string = CFString::new(&query_string);
let query = unsafe {
MDQueryCreate(kCFAllocatorDefault,
ctref(&cf_query_string),
ptr::null(),
ptr::null())
};
if query == ptr::null_mut() {
return Err(failure::err_msg("MDQueryCreate failed"));
}
unsafe { Ok(MDQuery::wrap_under_create_rule(query)) }
}
pub fn execute(&self) -> Result<CFIndex, Error> {
if unsafe { MDQueryExecute(ctref(self), kMDQuerySynchronous) } == FALSE {
return Err(failure::err_msg("MDQueryExecute failed"));
}
unsafe { Ok(MDQueryGetResultCount(ctref(self))) }
}
}
impl Drop for MDQuery {
fn drop(&mut self) {
unsafe {
CFRelease(self.as_CFTypeRef())
}
}
}
impl_TCFType!(MDQuery, MDQueryRef, MDQueryGetTypeID);
struct MDItem(MDItemRef);
impl Drop for MDItem {
fn drop(&mut self) {
unsafe {
CFRelease(self.as_CFTypeRef())
}
}
}
impl_TCFType!(MDItem, MDItemRef, MDItemGetTypeID);
#[inline]
fn ctref<T, C>(t: &T) -> C
where T: TCFType<C>
{
t.as_concrete_TypeRef()
}
fn cftype_to_string(cft: CFType) -> Result<String, Error> {
if !cft.instance_of::<_, CFString>() {
return Err(failure::err_msg("Not a string"));
}
let cf_string = unsafe {
CFString::wrap_under_get_rule(ctref(&cft) as CFStringRef)
};
Ok(cf_string.to_string())
}
/// Attempt to locate the Mach-O file inside a dSYM matching `uuid` using spotlight.
fn spotlight_locate_dsym_bundle(uuid: Uuid) -> Result<String, Error> {
let uuid = uuid.to_hyphenated().to_string().to_uppercase();
let query_string = format!("com_apple_xcode_dsym_uuids == {}", uuid);
let query = MDQuery::create(&query_string)?;
let count = query.execute()?;
for i in 0..count {
let item = unsafe { MDQueryGetResultAtIndex(ctref(&query), i) as MDItemRef };
let attr = unsafe { CFString::wrap_under_get_rule(kMDItemPath) };
let cf_attr = unsafe { MDItemCopyAttribute(item, ctref(&attr)) };
if cf_attr == ptr::null_mut() {
return Err(failure::err_msg("MDItemCopyAttribute failed"));
}
let cf_attr = unsafe { CFType::wrap_under_get_rule(cf_attr) };
if let Ok(path) = cftype_to_string(cf_attr) {
return Ok(path);
}
}
return Err(failure::err_msg("dSYM not found"));
}
/// Get the path to the Mach-O file containing DWARF debug info inside `bundle`.
fn spotlight_get_dsym_path(bundle: &str) -> Result<String, Error> {
let cf_bundle_string = CFString::new(bundle);
let bundle_item = unsafe { MDItemCreate(kCFAllocatorDefault,
ctref(&cf_bundle_string)) };
if bundle_item == ptr::null_mut() {
return Err(failure::err_msg("MDItemCreate failed"));
}
let bundle_item = unsafe { MDItem::wrap_under_create_rule(bundle_item) };
let attr = CFString::from_static_string("com_apple_xcode_dsym_paths");
let cf_attr = unsafe {
CFType::wrap_under_get_rule(MDItemCopyAttribute(ctref(&bundle_item),
ctref(&attr)))
};
if !cf_attr.instance_of::<_, CFArray>() {
return Err(failure::err_msg("dsym_paths attribute not an array"));
}
let cf_array = unsafe {
CFArray::wrap_under_get_rule(ctref(&cf_attr) as CFArrayRef)
};
if let Some(cf_item) = cf_array.iter().nth(0) {
let cf_item = unsafe { CFType::wrap_under_get_rule(cf_item) };
return cftype_to_string(cf_item);
}
return Err(failure::err_msg("dsym_paths array is empty"));
}
pub fn locate(_path: &Path, uuid: Uuid) -> Result<PathBuf, Error> {
let bundle = spotlight_locate_dsym_bundle(uuid)?;
Ok(Path::new(&bundle).join(spotlight_get_dsym_path(&bundle)?))
}
}
#[cfg(not(target_os="macos"))]
mod dsym {
use failure::{self, Error};
use std::path::{Path, PathBuf};
use uuid::Uuid;
/// Attempt to find the DWARF-containing file inside a dSYM bundle for the Mach-O binary
/// at `path` using simple path manipulation.
pub fn locate(path: &Path, _uuid: Uuid) -> Result<PathBuf, Error> {
let filename = path.file_name()
.ok_or(failure::err_msg("Bad path"))?;
let mut dsym = filename.to_owned();
dsym.push(".dSYM");
let f = path.with_file_name(&dsym).join("Contents/Resources/DWARF").join(filename);
if f.exists() {
Ok(f)
} else {
Err(failure::err_msg("Could not locate dSYM"))
}
}
}
/// Attempt to locate the path to separate debug symbols for `object` at `path`.
///
/// If `object` does not contain information that can be used to locate debug symbols for it,
/// or if the debug symbol file is not present on disk, return an error.
///
/// Currently only locating Mach-O dSYM bundles is supported.
pub fn locate_debug_symbols<T>(object: &File, path: T) -> Result<PathBuf, Error>
where T: AsRef<Path>,
{
if let Some(uuid) = object.mach_uuid() {
return locate_dsym(path.as_ref(), uuid);
}
if let Some(build_id) = object.build_id() {
let path = locate_debug_build_id(build_id);
if path.is_ok() {
return path;
}
// If not found, try gnu_debuglink.
}
if let Some((filename, crc)) = object.gnu_debuglink() {
let filename = path_from_bytes(filename)?;
return locate_gnu_debuglink(path.as_ref(), filename, crc);
}
Err(failure::err_msg("Object does not have debug info pointer"))
}
/// Attempt to locate the Mach-O file contained within a dSYM bundle containing the debug
/// symbols for the Mach-O file at `path` with UUID `uuid`.
pub fn locate_dsym<T>(path: T, uuid: Uuid) -> Result<PathBuf, Error>
where T: AsRef<Path>,
{
dsym::locate(path.as_ref(), uuid)
}
/// Attempt to locate the separate debug symbol file for the object file at `path` with
/// build ID `id`.
pub fn locate_debug_build_id(id: &[u8]) -> Result<PathBuf, Error> {
if id.len() < 2 {
return Err(failure::err_msg("Build ID is too short"));
}
// Try "/usr/lib/debug/.build-id/12/345678etc.debug"
let mut f = format!("/usr/lib/debug/.build-id/{:02x}/", id[0]);
for x in &id[1..] {
write!(&mut f, "{:02x}", x).ok();
}
write!(&mut f, ".debug").ok();
let f = PathBuf::from(f);
if f.exists() {
return Ok(f);
}
Err(failure::err_msg("Could not locate file with build ID"))
}
/// Attempt to locate the separate debug symbol file for the object file at `path` with
/// GNU "debug link" information consisting of `filename` and `crc`.
pub fn locate_gnu_debuglink<T, U>(path: T, filename: U, _crc: u32) -> Result<PathBuf, Error>
where
T: AsRef<Path>,
U: AsRef<Path>,
{
let path = fs::canonicalize(path)?;
let parent = path.parent().ok_or(failure::err_msg("Bad path"))?;
let filename = filename.as_ref();
// TODO: check CRC
// Try "/parent/filename" if it differs from "path"
let f = parent.join(filename);
if f != path && f.exists() {
return Ok(f);
}
// Try "/parent/.debug/filename"
let f = parent.join(".debug").join(filename);
if f.exists() {
return Ok(f);
}
// Try "/usr/lib/debug/parent/filename"
let parent = parent.strip_prefix("/").unwrap();
let f = Path::new("/usr/lib/debug").join(parent).join(filename);
if f.exists() {
return Ok(f);
}
Err(failure::err_msg("Could not locate GNU debug link file"))
}
|
fn main() {
// loop
loop {
println!("loop forever!");
break;
}
// while
let mut x: i32 = 5;
let mut done: bool = false;
while !done {
x += x - 3;
println!("{}",x);
if x % 5 == 0 {
done = true;
}
}
// for
for x in 0..10 {
println!("{}",x);
}
let a = 0..10;
println!("test : {:?}",a);
for (i,j) in (5..10).enumerate() {
println!("i = {} and j = {}",i,j);
}
let mut x: i32 = 5;
loop {
x += x - 3;
println!("{}",x);
if x % 5 == 0 {break;}
}
for x in 0..10 {
if x % 2 == 0 {continue;}
println!("{}",x);
}
// loop label
'outer: for x in 0..10 {
'inner: for y in 0..10 {
if x % 2 == 0 {continue 'outer;}
if y % 2 == 0 {continue 'inner;}
if y == 5 {break 'inner;}
println!("x: {}, y: {}",x,y);
}
}
}
|
/*!
```rudra-poc
[target]
crate = "atomic-option"
version = "0.1.2"
[[target.peer]]
crate = "crossbeam-utils"
version = "0.8.0"
[report]
issue_url = "https://github.com/reem/rust-atomic-option/issues/4"
issue_date = 2020-10-31
rustsec_url = "https://github.com/RustSec/advisory-db/pull/588"
rustsec_id = "RUSTSEC-2020-0113"
[[bugs]]
analyzer = "SendSyncVariance"
bug_class = "SendSyncVariance"
rudra_report_locations = ["src/lib.rs:23:1: 23:43"]
```
!*/
#![forbid(unsafe_code)]
use atomic_option::AtomicOption;
use crossbeam_utils::thread;
use std::{cell::Cell, sync::atomic::Ordering};
static SOME_INT: u64 = 123;
fn main() {
#[derive(Debug, Clone, Copy)]
enum RefOrInt<'a> {
Ref(&'a u64),
Int(u64),
}
let cell = Cell::new(RefOrInt::Ref(&SOME_INT));
let atomic_opt = AtomicOption::new(Box::new(&cell));
let ref_to_atomic_opt = &atomic_opt;
thread::scope(|s| {
s.spawn(move |_| {
let cell_in_thread = *(ref_to_atomic_opt.take(Ordering::Relaxed).unwrap());
println!("Thread - {:p} - {:?}", cell_in_thread, cell_in_thread);
loop {
// Repeatedly write Ref(&addr) and Int(0xdeadbeef) into the cell.
cell_in_thread.set(RefOrInt::Ref(&SOME_INT));
cell_in_thread.set(RefOrInt::Int(0xdeadbeef));
}
});
println!("Main - {:p} - {:?}", &cell, cell);
loop {
if let RefOrInt::Ref(addr) = cell.get() {
// Hope that between the time we pattern match the object as a
// `Ref`, it gets written to by the other thread.
if addr as *const u64 == &SOME_INT as *const u64 {
continue;
}
// Due to the data race, obtaining Ref(0xdeadbeef) is possible
println!("Pointer is now: {:p}", addr);
println!("Dereferencing addr will now segfault: {}", *addr);
}
}
});
}
|
use crate::{
cost_model::transferred_byte_cycles,
syscalls::{
utils::store_data, Source, SourceEntry, INDEX_OUT_OF_BOUND, LOAD_WITNESS_SYSCALL_NUMBER,
SUCCESS,
},
};
use ckb_types::packed::{Bytes, BytesVec};
use ckb_vm::{
registers::{A0, A3, A4, A7},
Error as VMError, Register, SupportMachine, Syscalls,
};
#[derive(Debug)]
pub struct LoadWitness<'a> {
witnesses: BytesVec,
group_inputs: &'a [usize],
group_outputs: &'a [usize],
}
impl<'a> LoadWitness<'a> {
pub fn new(
witnesses: BytesVec,
group_inputs: &'a [usize],
group_outputs: &'a [usize],
) -> LoadWitness<'a> {
LoadWitness {
witnesses,
group_inputs,
group_outputs,
}
}
fn fetch_witness(&self, source: Source, index: usize) -> Option<Bytes> {
match source {
Source::Group(SourceEntry::Input) => self
.group_inputs
.get(index)
.and_then(|actual_index| self.witnesses.get(*actual_index)),
Source::Group(SourceEntry::Output) => self
.group_outputs
.get(index)
.and_then(|actual_index| self.witnesses.get(*actual_index)),
Source::Transaction(SourceEntry::Input) => self.witnesses.get(index),
Source::Transaction(SourceEntry::Output) => self.witnesses.get(index),
_ => None,
}
}
}
impl<'a, Mac: SupportMachine> Syscalls<Mac> for LoadWitness<'a> {
fn initialize(&mut self, _machine: &mut Mac) -> Result<(), VMError> {
Ok(())
}
fn ecall(&mut self, machine: &mut Mac) -> Result<bool, VMError> {
if machine.registers()[A7].to_u64() != LOAD_WITNESS_SYSCALL_NUMBER {
return Ok(false);
}
let index = machine.registers()[A3].to_u64();
let source = Source::parse_from_u64(machine.registers()[A4].to_u64())?;
let witness = self.fetch_witness(source, index as usize);
if witness.is_none() {
machine.set_register(A0, Mac::REG::from_u8(INDEX_OUT_OF_BOUND));
return Ok(true);
}
let witness = witness.unwrap();
let data = witness.raw_data();
let wrote_size = store_data(machine, &data)?;
machine.add_cycles(transferred_byte_cycles(wrote_size))?;
machine.set_register(A0, Mac::REG::from_u8(SUCCESS));
Ok(true)
}
}
|
#![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 ErrorDetails {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Error {
#[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<ErrorDetails>,
#[serde(rename = "innerError", default, skip_serializing_if = "Option::is_none")]
pub inner_error: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AzureAsyncOperationResult {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<azure_async_operation_result::Status>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<Error>,
}
pub mod azure_async_operation_result {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Status {
InProgress,
Succeeded,
Failed,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Resource {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: 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 location: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SubResource {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TagsObject {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ProfileProperties {
#[serde(rename = "resourceState", default, skip_serializing_if = "Option::is_none")]
pub resource_state: Option<NetworkExperimentResourceState>,
#[serde(rename = "enabledState", default, skip_serializing_if = "Option::is_none")]
pub enabled_state: Option<profile_properties::EnabledState>,
}
pub mod profile_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum EnabledState {
Enabled,
Disabled,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ProfileList {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Profile>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Profile {
#[serde(flatten)]
pub resource: Resource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<ProfileProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub etag: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Endpoint {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub endpoint: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ProfileUpdateProperties {
#[serde(rename = "enabledState", default, skip_serializing_if = "Option::is_none")]
pub enabled_state: Option<profile_update_properties::EnabledState>,
}
pub mod profile_update_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum EnabledState {
Enabled,
Disabled,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ProfileUpdateModel {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<ProfileUpdateProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ExperimentUpdateProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(rename = "enabledState", default, skip_serializing_if = "Option::is_none")]
pub enabled_state: Option<experiment_update_properties::EnabledState>,
}
pub mod experiment_update_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum EnabledState {
Enabled,
Disabled,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ExperimentUpdateModel {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<ExperimentUpdateProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ExperimentProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(rename = "endpointA", default, skip_serializing_if = "Option::is_none")]
pub endpoint_a: Option<Endpoint>,
#[serde(rename = "endpointB", default, skip_serializing_if = "Option::is_none")]
pub endpoint_b: Option<Endpoint>,
#[serde(rename = "enabledState", default, skip_serializing_if = "Option::is_none")]
pub enabled_state: Option<experiment_properties::EnabledState>,
#[serde(rename = "resourceState", default, skip_serializing_if = "Option::is_none")]
pub resource_state: Option<NetworkExperimentResourceState>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<String>,
#[serde(rename = "scriptFileUri", default, skip_serializing_if = "Option::is_none")]
pub script_file_uri: Option<String>,
}
pub mod experiment_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum EnabledState {
Enabled,
Disabled,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ExperimentList {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Experiment>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Experiment {
#[serde(flatten)]
pub resource: Resource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<ExperimentProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LatencyScorecard {
#[serde(flatten)]
pub resource: Resource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<LatencyScorecardProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum NetworkExperimentResourceState {
Creating,
Enabling,
Enabled,
Disabling,
Disabled,
Deleting,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LatencyScorecardProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(rename = "endpointA", default, skip_serializing_if = "Option::is_none")]
pub endpoint_a: Option<String>,
#[serde(rename = "endpointB", default, skip_serializing_if = "Option::is_none")]
pub endpoint_b: Option<String>,
#[serde(rename = "startDateTimeUTC", default, skip_serializing_if = "Option::is_none")]
pub start_date_time_utc: Option<String>,
#[serde(rename = "endDateTimeUTC", default, skip_serializing_if = "Option::is_none")]
pub end_date_time_utc: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub country: Option<String>,
#[serde(rename = "latencyMetrics", default, skip_serializing_if = "Vec::is_empty")]
pub latency_metrics: Vec<LatencyMetric>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LatencyMetric {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "endDateTimeUTC", default, skip_serializing_if = "Option::is_none")]
pub end_date_time_utc: Option<String>,
#[serde(rename = "aValue", default, skip_serializing_if = "Option::is_none")]
pub a_value: Option<f64>,
#[serde(rename = "bValue", default, skip_serializing_if = "Option::is_none")]
pub b_value: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub delta: Option<f64>,
#[serde(rename = "deltaPercent", default, skip_serializing_if = "Option::is_none")]
pub delta_percent: Option<f64>,
#[serde(rename = "aCLower95CI", default, skip_serializing_if = "Option::is_none")]
pub a_c_lower95_ci: Option<f64>,
#[serde(rename = "aHUpper95CI", default, skip_serializing_if = "Option::is_none")]
pub a_h_upper95_ci: Option<f64>,
#[serde(rename = "bCLower95CI", default, skip_serializing_if = "Option::is_none")]
pub b_c_lower95_ci: Option<f64>,
#[serde(rename = "bUpper95CI", default, skip_serializing_if = "Option::is_none")]
pub b_upper95_ci: Option<f64>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Timeseries {
#[serde(flatten)]
pub resource: Resource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<TimeseriesProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TimeseriesProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub endpoint: Option<String>,
#[serde(rename = "startDateTimeUTC", default, skip_serializing_if = "Option::is_none")]
pub start_date_time_utc: Option<String>,
#[serde(rename = "endDateTimeUTC", default, skip_serializing_if = "Option::is_none")]
pub end_date_time_utc: Option<String>,
#[serde(rename = "aggregationInterval", default, skip_serializing_if = "Option::is_none")]
pub aggregation_interval: Option<timeseries_properties::AggregationInterval>,
#[serde(rename = "timeseriesType", default, skip_serializing_if = "Option::is_none")]
pub timeseries_type: Option<timeseries_properties::TimeseriesType>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub country: Option<String>,
#[serde(rename = "timeseriesData", default, skip_serializing_if = "Vec::is_empty")]
pub timeseries_data: Vec<TimeseriesDataPoint>,
}
pub mod timeseries_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum AggregationInterval {
Hourly,
Daily,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum TimeseriesType {
MeasurementCounts,
LatencyP50,
LatencyP75,
LatencyP95,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TimeseriesDataPoint {
#[serde(rename = "dateTimeUTC", default, skip_serializing_if = "Option::is_none")]
pub date_time_utc: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<f64>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PreconfiguredEndpointList {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<PreconfiguredEndpoint>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PreconfiguredEndpoint {
#[serde(flatten)]
pub resource: Resource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<PreconfiguredEndpointProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PreconfiguredEndpointProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub endpoint: Option<String>,
#[serde(rename = "endpointType", default, skip_serializing_if = "Option::is_none")]
pub endpoint_type: Option<preconfigured_endpoint_properties::EndpointType>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub backend: Option<String>,
}
pub mod preconfigured_endpoint_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum EndpointType {
#[serde(rename = "AFD")]
Afd,
AzureRegion,
#[serde(rename = "CDN")]
Cdn,
#[serde(rename = "ATM")]
Atm,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorResponse {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FrontDoor {
#[serde(flatten)]
pub resource: Resource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<FrontDoorProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FrontDoorUpdateParameters {
#[serde(rename = "friendlyName", default, skip_serializing_if = "Option::is_none")]
pub friendly_name: Option<String>,
#[serde(rename = "routingRules", default, skip_serializing_if = "Vec::is_empty")]
pub routing_rules: Vec<RoutingRule>,
#[serde(rename = "loadBalancingSettings", default, skip_serializing_if = "Vec::is_empty")]
pub load_balancing_settings: Vec<LoadBalancingSettingsModel>,
#[serde(rename = "healthProbeSettings", default, skip_serializing_if = "Vec::is_empty")]
pub health_probe_settings: Vec<HealthProbeSettingsModel>,
#[serde(rename = "backendPools", default, skip_serializing_if = "Vec::is_empty")]
pub backend_pools: Vec<BackendPool>,
#[serde(rename = "frontendEndpoints", default, skip_serializing_if = "Vec::is_empty")]
pub frontend_endpoints: Vec<FrontendEndpoint>,
#[serde(rename = "backendPoolsSettings", default, skip_serializing_if = "Option::is_none")]
pub backend_pools_settings: Option<BackendPoolsSettings>,
#[serde(rename = "enabledState", default, skip_serializing_if = "Option::is_none")]
pub enabled_state: Option<front_door_update_parameters::EnabledState>,
}
pub mod front_door_update_parameters {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum EnabledState {
Enabled,
Disabled,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FrontDoorProperties {
#[serde(flatten)]
pub front_door_update_parameters: FrontDoorUpdateParameters,
#[serde(rename = "resourceState", default, skip_serializing_if = "Option::is_none")]
pub resource_state: Option<ResourceState>,
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cname: Option<String>,
#[serde(rename = "frontdoorId", default, skip_serializing_if = "Option::is_none")]
pub frontdoor_id: Option<String>,
#[serde(rename = "rulesEngines", default, skip_serializing_if = "Vec::is_empty")]
pub rules_engines: Vec<RulesEngine>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FrontDoorListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<FrontDoor>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PurgeParameters {
#[serde(rename = "contentPaths")]
pub content_paths: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RoutingRule {
#[serde(flatten)]
pub sub_resource: SubResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<RoutingRuleProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RoutingRuleProperties {
#[serde(flatten)]
pub routing_rule_update_parameters: RoutingRuleUpdateParameters,
#[serde(rename = "resourceState", default, skip_serializing_if = "Option::is_none")]
pub resource_state: Option<ResourceState>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RoutingRuleListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<RoutingRule>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RoutingRuleUpdateParameters {
#[serde(rename = "frontendEndpoints", default, skip_serializing_if = "Vec::is_empty")]
pub frontend_endpoints: Vec<SubResource>,
#[serde(rename = "acceptedProtocols", default, skip_serializing_if = "Vec::is_empty")]
pub accepted_protocols: Vec<String>,
#[serde(rename = "patternsToMatch", default, skip_serializing_if = "Vec::is_empty")]
pub patterns_to_match: Vec<String>,
#[serde(rename = "enabledState", default, skip_serializing_if = "Option::is_none")]
pub enabled_state: Option<routing_rule_update_parameters::EnabledState>,
#[serde(rename = "routeConfiguration", default, skip_serializing_if = "Option::is_none")]
pub route_configuration: Option<RouteConfiguration>,
#[serde(rename = "rulesEngine", default, skip_serializing_if = "Option::is_none")]
pub rules_engine: Option<SubResource>,
#[serde(rename = "webApplicationFirewallPolicyLink", default, skip_serializing_if = "Option::is_none")]
pub web_application_firewall_policy_link: Option<routing_rule_update_parameters::WebApplicationFirewallPolicyLink>,
}
pub mod routing_rule_update_parameters {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum EnabledState {
Enabled,
Disabled,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WebApplicationFirewallPolicyLink {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RouteConfiguration {
#[serde(rename = "@odata.type")]
pub odata_type: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ForwardingConfiguration {
#[serde(flatten)]
pub route_configuration: RouteConfiguration,
#[serde(rename = "customForwardingPath", default, skip_serializing_if = "Option::is_none")]
pub custom_forwarding_path: Option<String>,
#[serde(rename = "forwardingProtocol", default, skip_serializing_if = "Option::is_none")]
pub forwarding_protocol: Option<forwarding_configuration::ForwardingProtocol>,
#[serde(rename = "cacheConfiguration", default, skip_serializing_if = "Option::is_none")]
pub cache_configuration: Option<CacheConfiguration>,
#[serde(rename = "backendPool", default, skip_serializing_if = "Option::is_none")]
pub backend_pool: Option<SubResource>,
}
pub mod forwarding_configuration {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ForwardingProtocol {
HttpOnly,
HttpsOnly,
MatchRequest,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RedirectConfiguration {
#[serde(flatten)]
pub route_configuration: RouteConfiguration,
#[serde(rename = "redirectType", default, skip_serializing_if = "Option::is_none")]
pub redirect_type: Option<redirect_configuration::RedirectType>,
#[serde(rename = "redirectProtocol", default, skip_serializing_if = "Option::is_none")]
pub redirect_protocol: Option<redirect_configuration::RedirectProtocol>,
#[serde(rename = "customHost", default, skip_serializing_if = "Option::is_none")]
pub custom_host: Option<String>,
#[serde(rename = "customPath", default, skip_serializing_if = "Option::is_none")]
pub custom_path: Option<String>,
#[serde(rename = "customFragment", default, skip_serializing_if = "Option::is_none")]
pub custom_fragment: Option<String>,
#[serde(rename = "customQueryString", default, skip_serializing_if = "Option::is_none")]
pub custom_query_string: Option<String>,
}
pub mod redirect_configuration {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum RedirectType {
Moved,
Found,
TemporaryRedirect,
PermanentRedirect,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum RedirectProtocol {
HttpOnly,
HttpsOnly,
MatchRequest,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Backend {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub address: Option<String>,
#[serde(rename = "privateLinkAlias", default, skip_serializing_if = "Option::is_none")]
pub private_link_alias: Option<String>,
#[serde(rename = "privateLinkResourceId", default, skip_serializing_if = "Option::is_none")]
pub private_link_resource_id: Option<String>,
#[serde(rename = "privateLinkLocation", default, skip_serializing_if = "Option::is_none")]
pub private_link_location: Option<String>,
#[serde(rename = "privateEndpointStatus", default, skip_serializing_if = "Option::is_none")]
pub private_endpoint_status: Option<backend::PrivateEndpointStatus>,
#[serde(rename = "privateLinkApprovalMessage", default, skip_serializing_if = "Option::is_none")]
pub private_link_approval_message: Option<String>,
#[serde(rename = "httpPort", default, skip_serializing_if = "Option::is_none")]
pub http_port: Option<i64>,
#[serde(rename = "httpsPort", default, skip_serializing_if = "Option::is_none")]
pub https_port: Option<i64>,
#[serde(rename = "enabledState", default, skip_serializing_if = "Option::is_none")]
pub enabled_state: Option<backend::EnabledState>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub priority: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub weight: Option<i64>,
#[serde(rename = "backendHostHeader", default, skip_serializing_if = "Option::is_none")]
pub backend_host_header: Option<String>,
}
pub mod backend {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum PrivateEndpointStatus {
Pending,
Approved,
Rejected,
Disconnected,
Timeout,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum EnabledState {
Enabled,
Disabled,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LoadBalancingSettingsModel {
#[serde(flatten)]
pub sub_resource: SubResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<LoadBalancingSettingsProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LoadBalancingSettingsProperties {
#[serde(flatten)]
pub load_balancing_settings_update_parameters: LoadBalancingSettingsUpdateParameters,
#[serde(rename = "resourceState", default, skip_serializing_if = "Option::is_none")]
pub resource_state: Option<ResourceState>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LoadBalancingSettingsListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<LoadBalancingSettingsModel>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LoadBalancingSettingsUpdateParameters {
#[serde(rename = "sampleSize", default, skip_serializing_if = "Option::is_none")]
pub sample_size: Option<i64>,
#[serde(rename = "successfulSamplesRequired", default, skip_serializing_if = "Option::is_none")]
pub successful_samples_required: Option<i64>,
#[serde(rename = "additionalLatencyMilliseconds", default, skip_serializing_if = "Option::is_none")]
pub additional_latency_milliseconds: Option<i64>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct HealthProbeSettingsModel {
#[serde(flatten)]
pub sub_resource: SubResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<HealthProbeSettingsProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct HealthProbeSettingsProperties {
#[serde(flatten)]
pub health_probe_settings_update_parameters: HealthProbeSettingsUpdateParameters,
#[serde(rename = "resourceState", default, skip_serializing_if = "Option::is_none")]
pub resource_state: Option<ResourceState>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct HealthProbeSettingsListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<HealthProbeSettingsModel>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct HealthProbeSettingsUpdateParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub path: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub protocol: Option<health_probe_settings_update_parameters::Protocol>,
#[serde(rename = "intervalInSeconds", default, skip_serializing_if = "Option::is_none")]
pub interval_in_seconds: Option<i64>,
#[serde(rename = "healthProbeMethod", default, skip_serializing_if = "Option::is_none")]
pub health_probe_method: Option<health_probe_settings_update_parameters::HealthProbeMethod>,
#[serde(rename = "enabledState", default, skip_serializing_if = "Option::is_none")]
pub enabled_state: Option<health_probe_settings_update_parameters::EnabledState>,
}
pub mod health_probe_settings_update_parameters {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Protocol {
Http,
Https,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum HealthProbeMethod {
#[serde(rename = "GET")]
Get,
#[serde(rename = "HEAD")]
Head,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum EnabledState {
Enabled,
Disabled,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BackendPool {
#[serde(flatten)]
pub sub_resource: SubResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<BackendPoolProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BackendPoolUpdateParameters {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub backends: Vec<Backend>,
#[serde(rename = "loadBalancingSettings", default, skip_serializing_if = "Option::is_none")]
pub load_balancing_settings: Option<SubResource>,
#[serde(rename = "healthProbeSettings", default, skip_serializing_if = "Option::is_none")]
pub health_probe_settings: Option<SubResource>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BackendPoolProperties {
#[serde(flatten)]
pub backend_pool_update_parameters: BackendPoolUpdateParameters,
#[serde(rename = "resourceState", default, skip_serializing_if = "Option::is_none")]
pub resource_state: Option<ResourceState>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BackendPoolListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<BackendPool>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CacheConfiguration {
#[serde(rename = "queryParameterStripDirective", default, skip_serializing_if = "Option::is_none")]
pub query_parameter_strip_directive: Option<cache_configuration::QueryParameterStripDirective>,
#[serde(rename = "queryParameters", default, skip_serializing_if = "Option::is_none")]
pub query_parameters: Option<String>,
#[serde(rename = "dynamicCompression", default, skip_serializing_if = "Option::is_none")]
pub dynamic_compression: Option<cache_configuration::DynamicCompression>,
#[serde(rename = "cacheDuration", default, skip_serializing_if = "Option::is_none")]
pub cache_duration: Option<String>,
}
pub mod cache_configuration {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum QueryParameterStripDirective {
StripNone,
StripAll,
StripOnly,
StripAllExcept,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum DynamicCompression {
Enabled,
Disabled,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct KeyVaultCertificateSourceParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub vault: Option<key_vault_certificate_source_parameters::Vault>,
#[serde(rename = "secretName", default, skip_serializing_if = "Option::is_none")]
pub secret_name: Option<String>,
#[serde(rename = "secretVersion", default, skip_serializing_if = "Option::is_none")]
pub secret_version: Option<String>,
}
pub mod key_vault_certificate_source_parameters {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Vault {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FrontDoorCertificateSourceParameters {
#[serde(rename = "certificateType", default, skip_serializing_if = "Option::is_none")]
pub certificate_type: Option<front_door_certificate_source_parameters::CertificateType>,
}
pub mod front_door_certificate_source_parameters {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum CertificateType {
Dedicated,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CustomHttpsConfiguration {
#[serde(rename = "certificateSource")]
pub certificate_source: custom_https_configuration::CertificateSource,
#[serde(rename = "protocolType")]
pub protocol_type: custom_https_configuration::ProtocolType,
#[serde(rename = "minimumTlsVersion")]
pub minimum_tls_version: custom_https_configuration::MinimumTlsVersion,
#[serde(rename = "keyVaultCertificateSourceParameters", default, skip_serializing_if = "Option::is_none")]
pub key_vault_certificate_source_parameters: Option<KeyVaultCertificateSourceParameters>,
#[serde(rename = "frontDoorCertificateSourceParameters", default, skip_serializing_if = "Option::is_none")]
pub front_door_certificate_source_parameters: Option<FrontDoorCertificateSourceParameters>,
}
pub mod custom_https_configuration {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum CertificateSource {
AzureKeyVault,
FrontDoor,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ProtocolType {
ServerNameIndication,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum MinimumTlsVersion {
#[serde(rename = "1.0")]
N1_0,
#[serde(rename = "1.2")]
N1_2,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FrontendEndpoint {
#[serde(flatten)]
pub sub_resource: SubResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<FrontendEndpointProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FrontendEndpointProperties {
#[serde(flatten)]
pub frontend_endpoint_update_parameters: FrontendEndpointUpdateParameters,
#[serde(rename = "resourceState", default, skip_serializing_if = "Option::is_none")]
pub resource_state: Option<ResourceState>,
#[serde(rename = "customHttpsProvisioningState", default, skip_serializing_if = "Option::is_none")]
pub custom_https_provisioning_state: Option<frontend_endpoint_properties::CustomHttpsProvisioningState>,
#[serde(rename = "customHttpsProvisioningSubstate", default, skip_serializing_if = "Option::is_none")]
pub custom_https_provisioning_substate: Option<frontend_endpoint_properties::CustomHttpsProvisioningSubstate>,
#[serde(rename = "customHttpsConfiguration", default, skip_serializing_if = "Option::is_none")]
pub custom_https_configuration: Option<CustomHttpsConfiguration>,
}
pub mod frontend_endpoint_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum CustomHttpsProvisioningState {
Enabling,
Enabled,
Disabling,
Disabled,
Failed,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum CustomHttpsProvisioningSubstate {
SubmittingDomainControlValidationRequest,
PendingDomainControlValidationREquestApproval,
DomainControlValidationRequestApproved,
DomainControlValidationRequestRejected,
DomainControlValidationRequestTimedOut,
IssuingCertificate,
DeployingCertificate,
CertificateDeployed,
DeletingCertificate,
CertificateDeleted,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FrontendEndpointUpdateParameters {
#[serde(rename = "hostName", default, skip_serializing_if = "Option::is_none")]
pub host_name: Option<String>,
#[serde(rename = "sessionAffinityEnabledState", default, skip_serializing_if = "Option::is_none")]
pub session_affinity_enabled_state: Option<frontend_endpoint_update_parameters::SessionAffinityEnabledState>,
#[serde(rename = "sessionAffinityTtlSeconds", default, skip_serializing_if = "Option::is_none")]
pub session_affinity_ttl_seconds: Option<i64>,
#[serde(rename = "webApplicationFirewallPolicyLink", default, skip_serializing_if = "Option::is_none")]
pub web_application_firewall_policy_link: Option<frontend_endpoint_update_parameters::WebApplicationFirewallPolicyLink>,
}
pub mod frontend_endpoint_update_parameters {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum SessionAffinityEnabledState {
Enabled,
Disabled,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WebApplicationFirewallPolicyLink {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FrontendEndpointsListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<FrontendEndpoint>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BackendPoolsSettings {
#[serde(rename = "enforceCertificateNameCheck", default, skip_serializing_if = "Option::is_none")]
pub enforce_certificate_name_check: Option<backend_pools_settings::EnforceCertificateNameCheck>,
#[serde(rename = "sendRecvTimeoutSeconds", default, skip_serializing_if = "Option::is_none")]
pub send_recv_timeout_seconds: Option<i64>,
}
pub mod backend_pools_settings {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum EnforceCertificateNameCheck {
Enabled,
Disabled,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct HeaderAction {
#[serde(rename = "headerActionType")]
pub header_action_type: header_action::HeaderActionType,
#[serde(rename = "headerName")]
pub header_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
}
pub mod header_action {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum HeaderActionType {
Append,
Delete,
Overwrite,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RulesEngineMatchCondition {
#[serde(rename = "rulesEngineMatchVariable")]
pub rules_engine_match_variable: rules_engine_match_condition::RulesEngineMatchVariable,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub selector: Option<String>,
#[serde(rename = "rulesEngineOperator")]
pub rules_engine_operator: rules_engine_match_condition::RulesEngineOperator,
#[serde(rename = "negateCondition", default, skip_serializing_if = "Option::is_none")]
pub negate_condition: Option<bool>,
#[serde(rename = "rulesEngineMatchValue")]
pub rules_engine_match_value: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub transforms: Vec<Transform>,
}
pub mod rules_engine_match_condition {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum RulesEngineMatchVariable {
IsMobile,
RemoteAddr,
RequestMethod,
QueryString,
PostArgs,
RequestUri,
RequestPath,
RequestFilename,
RequestFilenameExtension,
RequestHeader,
RequestBody,
RequestScheme,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum RulesEngineOperator {
Any,
#[serde(rename = "IPMatch")]
IpMatch,
GeoMatch,
Equal,
Contains,
LessThan,
GreaterThan,
LessThanOrEqual,
GreaterThanOrEqual,
BeginsWith,
EndsWith,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ResourceState {
Creating,
Enabling,
Enabled,
Disabling,
Disabled,
Deleting,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RulesEngineAction {
#[serde(rename = "requestHeaderActions", default, skip_serializing_if = "Vec::is_empty")]
pub request_header_actions: Vec<HeaderAction>,
#[serde(rename = "responseHeaderActions", default, skip_serializing_if = "Vec::is_empty")]
pub response_header_actions: Vec<HeaderAction>,
#[serde(rename = "routeConfigurationOverride", default, skip_serializing_if = "Option::is_none")]
pub route_configuration_override: Option<RouteConfiguration>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RulesEngine {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<RulesEngineProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: 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 id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RulesEngineListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<RulesEngine>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RulesEngineProperties {
#[serde(flatten)]
pub rules_engine_update_parameters: RulesEngineUpdateParameters,
#[serde(rename = "resourceState", default, skip_serializing_if = "Option::is_none")]
pub resource_state: Option<ResourceState>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RulesEngineRule {
pub name: String,
pub priority: i64,
pub action: RulesEngineAction,
#[serde(rename = "matchConditions", default, skip_serializing_if = "Vec::is_empty")]
pub match_conditions: Vec<RulesEngineMatchCondition>,
#[serde(rename = "matchProcessingBehavior", default, skip_serializing_if = "Option::is_none")]
pub match_processing_behavior: Option<rules_engine_rule::MatchProcessingBehavior>,
}
pub mod rules_engine_rule {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum MatchProcessingBehavior {
Continue,
Stop,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RulesEngineUpdateParameters {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub rules: Vec<RulesEngineRule>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Transform {
Lowercase,
Uppercase,
Trim,
UrlDecode,
UrlEncode,
RemoveNulls,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ValidateCustomDomainInput {
#[serde(rename = "hostName")]
pub host_name: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ValidateCustomDomainOutput {
#[serde(rename = "customDomainValidated", default, skip_serializing_if = "Option::is_none")]
pub custom_domain_validated: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CheckNameAvailabilityInput {
pub name: String,
#[serde(rename = "type")]
pub type_: ResourceType,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CheckNameAvailabilityOutput {
#[serde(rename = "nameAvailability", default, skip_serializing_if = "Option::is_none")]
pub name_availability: Option<check_name_availability_output::NameAvailability>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
}
pub mod check_name_availability_output {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum NameAvailability {
Available,
Unavailable,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ResourceType {
#[serde(rename = "Microsoft.Network/frontDoors")]
MicrosoftNetworkFrontDoors,
#[serde(rename = "Microsoft.Network/frontDoors/frontendEndpoints")]
MicrosoftNetworkFrontDoorsFrontendEndpoints,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WebApplicationFirewallPolicy {
#[serde(flatten)]
pub resource: Resource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<WebApplicationFirewallPolicyProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub etag: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sku: Option<Sku>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WebApplicationFirewallPolicyProperties {
#[serde(rename = "policySettings", default, skip_serializing_if = "Option::is_none")]
pub policy_settings: Option<PolicySettings>,
#[serde(rename = "customRules", default, skip_serializing_if = "Option::is_none")]
pub custom_rules: Option<CustomRuleList>,
#[serde(rename = "managedRules", default, skip_serializing_if = "Option::is_none")]
pub managed_rules: Option<ManagedRuleSetList>,
#[serde(rename = "frontendEndpointLinks", default, skip_serializing_if = "Vec::is_empty")]
pub frontend_endpoint_links: Vec<FrontendEndpointLink>,
#[serde(rename = "routingRuleLinks", default, skip_serializing_if = "Vec::is_empty")]
pub routing_rule_links: Vec<RoutingRuleLink>,
#[serde(rename = "securityPolicyLinks", default, skip_serializing_if = "Vec::is_empty")]
pub security_policy_links: Vec<SecurityPolicyLink>,
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<String>,
#[serde(rename = "resourceState", default, skip_serializing_if = "Option::is_none")]
pub resource_state: Option<web_application_firewall_policy_properties::ResourceState>,
}
pub mod web_application_firewall_policy_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ResourceState {
Creating,
Enabling,
Enabled,
Disabling,
Disabled,
Deleting,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Sku {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<sku::Name>,
}
pub mod sku {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Name {
#[serde(rename = "Classic_AzureFrontDoor")]
ClassicAzureFrontDoor,
#[serde(rename = "Standard_AzureFrontDoor")]
StandardAzureFrontDoor,
#[serde(rename = "Premium_AzureFrontDoor")]
PremiumAzureFrontDoor,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WebApplicationFirewallPolicyList {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<WebApplicationFirewallPolicy>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PolicySettings {
#[serde(rename = "enabledState", default, skip_serializing_if = "Option::is_none")]
pub enabled_state: Option<policy_settings::EnabledState>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mode: Option<policy_settings::Mode>,
#[serde(rename = "redirectUrl", default, skip_serializing_if = "Option::is_none")]
pub redirect_url: Option<String>,
#[serde(rename = "customBlockResponseStatusCode", default, skip_serializing_if = "Option::is_none")]
pub custom_block_response_status_code: Option<i64>,
#[serde(rename = "customBlockResponseBody", default, skip_serializing_if = "Option::is_none")]
pub custom_block_response_body: Option<String>,
#[serde(rename = "requestBodyCheck", default, skip_serializing_if = "Option::is_none")]
pub request_body_check: Option<policy_settings::RequestBodyCheck>,
}
pub mod policy_settings {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum EnabledState {
Disabled,
Enabled,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Mode {
Prevention,
Detection,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum RequestBodyCheck {
Disabled,
Enabled,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CustomRuleList {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub rules: Vec<CustomRule>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CustomRule {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
pub priority: i64,
#[serde(rename = "enabledState", default, skip_serializing_if = "Option::is_none")]
pub enabled_state: Option<custom_rule::EnabledState>,
#[serde(rename = "ruleType")]
pub rule_type: custom_rule::RuleType,
#[serde(rename = "rateLimitDurationInMinutes", default, skip_serializing_if = "Option::is_none")]
pub rate_limit_duration_in_minutes: Option<i64>,
#[serde(rename = "rateLimitThreshold", default, skip_serializing_if = "Option::is_none")]
pub rate_limit_threshold: Option<i64>,
#[serde(rename = "matchConditions")]
pub match_conditions: Vec<MatchCondition>,
pub action: ActionType,
}
pub mod custom_rule {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum EnabledState {
Disabled,
Enabled,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum RuleType {
MatchRule,
RateLimitRule,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum TransformType {
Lowercase,
Uppercase,
Trim,
UrlDecode,
UrlEncode,
RemoveNulls,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MatchCondition {
#[serde(rename = "matchVariable")]
pub match_variable: match_condition::MatchVariable,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub selector: Option<String>,
pub operator: match_condition::Operator,
#[serde(rename = "negateCondition", default, skip_serializing_if = "Option::is_none")]
pub negate_condition: Option<bool>,
#[serde(rename = "matchValue")]
pub match_value: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub transforms: Vec<TransformType>,
}
pub mod match_condition {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum MatchVariable {
RemoteAddr,
RequestMethod,
QueryString,
PostArgs,
RequestUri,
RequestHeader,
RequestBody,
Cookies,
SocketAddr,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Operator {
Any,
#[serde(rename = "IPMatch")]
IpMatch,
GeoMatch,
Equal,
Contains,
LessThan,
GreaterThan,
LessThanOrEqual,
GreaterThanOrEqual,
BeginsWith,
EndsWith,
RegEx,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ManagedRuleSetList {
#[serde(rename = "managedRuleSets", default, skip_serializing_if = "Vec::is_empty")]
pub managed_rule_sets: Vec<ManagedRuleSet>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ManagedRuleSet {
#[serde(rename = "ruleSetType")]
pub rule_set_type: String,
#[serde(rename = "ruleSetVersion")]
pub rule_set_version: String,
#[serde(rename = "ruleSetAction", default, skip_serializing_if = "Option::is_none")]
pub rule_set_action: Option<ManagedRuleSetActionType>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub exclusions: Vec<ManagedRuleExclusion>,
#[serde(rename = "ruleGroupOverrides", default, skip_serializing_if = "Vec::is_empty")]
pub rule_group_overrides: Vec<ManagedRuleGroupOverride>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ManagedRuleGroupOverride {
#[serde(rename = "ruleGroupName")]
pub rule_group_name: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub exclusions: Vec<ManagedRuleExclusion>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub rules: Vec<ManagedRuleOverride>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ManagedRuleOverride {
#[serde(rename = "ruleId")]
pub rule_id: String,
#[serde(rename = "enabledState", default, skip_serializing_if = "Option::is_none")]
pub enabled_state: Option<ManagedRuleEnabledState>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub action: Option<ActionType>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub exclusions: Vec<ManagedRuleExclusion>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ManagedRuleSetDefinitionList {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<ManagedRuleSetDefinition>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ManagedRuleSetDefinition {
#[serde(flatten)]
pub resource: Resource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<ManagedRuleSetDefinitionProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ManagedRuleSetDefinitionProperties {
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<String>,
#[serde(rename = "ruleSetId", default, skip_serializing_if = "Option::is_none")]
pub rule_set_id: Option<String>,
#[serde(rename = "ruleSetType", default, skip_serializing_if = "Option::is_none")]
pub rule_set_type: Option<String>,
#[serde(rename = "ruleSetVersion", default, skip_serializing_if = "Option::is_none")]
pub rule_set_version: Option<String>,
#[serde(rename = "ruleGroups", default, skip_serializing_if = "Vec::is_empty")]
pub rule_groups: Vec<ManagedRuleGroupDefinition>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ManagedRuleGroupDefinition {
#[serde(rename = "ruleGroupName", default, skip_serializing_if = "Option::is_none")]
pub rule_group_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub rules: Vec<ManagedRuleDefinition>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ManagedRuleDefinition {
#[serde(rename = "ruleId", default, skip_serializing_if = "Option::is_none")]
pub rule_id: Option<String>,
#[serde(rename = "defaultState", default, skip_serializing_if = "Option::is_none")]
pub default_state: Option<ManagedRuleEnabledState>,
#[serde(rename = "defaultAction", default, skip_serializing_if = "Option::is_none")]
pub default_action: Option<ActionType>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ManagedRuleExclusion {
#[serde(rename = "matchVariable")]
pub match_variable: managed_rule_exclusion::MatchVariable,
#[serde(rename = "selectorMatchOperator")]
pub selector_match_operator: managed_rule_exclusion::SelectorMatchOperator,
pub selector: String,
}
pub mod managed_rule_exclusion {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum MatchVariable {
RequestHeaderNames,
RequestCookieNames,
QueryStringArgNames,
RequestBodyPostArgNames,
RequestBodyJsonArgNames,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum SelectorMatchOperator {
Equals,
Contains,
StartsWith,
EndsWith,
EqualsAny,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ActionType {
Allow,
Block,
Log,
Redirect,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ManagedRuleSetActionType {
Block,
Log,
Redirect,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ManagedRuleEnabledState {
Disabled,
Enabled,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FrontendEndpointLink {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RoutingRuleLink {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SecurityPolicyLink {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
}
|
use std::collections::BTreeMap;
use chrono::{Local, TimeZone};
use regex::Regex;
use serde::Serialize;
#[derive(Debug, Serialize)]
struct Episode {
show_id: String,
description: String,
// I believe this is autoincremented if none
#[serde(skip_serializing_if = "Option::is_none")]
number: Option<String>,
season: String,
#[serde(rename = "type")]
typ: String,
title: String,
}
#[derive(Debug, Serialize)]
struct EpisodeWrapper {
episode: Episode,
}
fn main() {
let re = Regex::new(r"((\d+)_(\d+)_(\d+))\.md:## (.*)").unwrap();
let data = std::fs::read_to_string("../sodes.txt").unwrap();
let sodes = data.lines();
let all = sodes
.enumerate()
.map(|(_, sode)| {
println!("{}", sode);
let captures = re.captures(sode).unwrap();
println!("{:#?}", captures);
let (ymd, yy, mm, dd, title) = (
&captures[1],
&captures[2],
&captures[3],
&captures[4],
&captures[5],
);
let date = Local.ymd(
yy.parse().unwrap(),
mm.parse().unwrap(),
dd.parse().unwrap(),
);
let path = format!("../html/{}.html", ymd);
println!("path = {}", path);
let description = std::fs::read_to_string(path).unwrap();
(
date,
Episode {
show_id: "29256".to_string(),
description,
number: None,
season: "2".to_string(),
typ: "full".to_string(),
title: format!("{} ({})", title, date.format("%Y-%m-%d")),
},
)
})
.collect::<BTreeMap<_, _>>();
for (date, sode) in all {
let contents = serde_json::to_string_pretty(&EpisodeWrapper { episode: sode }).unwrap();
println!("{}", contents);
std::fs::write(
format!("../json/{}.json", date.format("%Y_%m_%d")),
contents,
)
.unwrap();
}
}
|
use anyhow::Result;
use rustimate_core::messages::req::RequestMessage;
use wasm_bindgen::prelude::{Closure, JsValue};
use wasm_bindgen::JsCast;
use web_sys::{ErrorEvent, MessageEvent, WebSocket};
#[derive(Clone, Debug)]
pub(crate) struct ClientSocket {
url: String,
binary: bool,
pub(crate) ws: WebSocket
}
impl ClientSocket {
pub(crate) fn new(curr_url: &str, binary: bool) -> Result<Self> {
let url = calc_url(curr_url);
let ws = WebSocket::new(&url).map_err(|e| anyhow::anyhow!(format!("Error creating WebSocket: {:?}", e)))?;
ws.set_binary_type(web_sys::BinaryType::Arraybuffer);
crate::js::wire_onbeforeunload(&ws);
Ok(Self { url, binary, ws })
}
pub(crate) fn set_callbacks(
&self, on_open: Box<dyn FnMut(JsValue)>, on_message: Box<dyn FnMut(MessageEvent)>, on_error: Box<dyn FnMut(ErrorEvent)>,
on_close: Box<dyn FnMut(JsValue)>
)
{
let onopen_callback = Closure::wrap(on_open);
self.ws.set_onopen(Some(onopen_callback.as_ref().unchecked_ref()));
onopen_callback.forget();
let onmessage_callback = Closure::wrap(on_message);
self.ws.set_onmessage(Some(onmessage_callback.as_ref().unchecked_ref()));
onmessage_callback.forget();
let onerror_callback = Closure::wrap(on_error);
self.ws.set_onerror(Some(onerror_callback.as_ref().unchecked_ref()));
onerror_callback.forget();
let onclose_callback = Closure::wrap(on_close);
self.ws.set_onclose(Some(onclose_callback.as_ref().unchecked_ref()));
onclose_callback.forget();
}
pub(crate) fn set_binary(&mut self, b: bool) {
self.binary = b;
}
pub(crate) fn send(&self, msg: &RequestMessage) {
if self.binary {
self.send_binary(msg);
} else {
self.send_json(msg);
}
}
pub(crate) fn send_json(&self, req: &RequestMessage) {
match req.to_json() {
Ok(j) => match &self.ws.send_with_str(&j) {
Ok(_) => (),
Err(err) => error!("Error sending json message: [{:?}]", err)
},
Err(e) => {
error!("Cannot serialize json RequestMessage: {}", e);
}
};
}
pub(crate) fn send_binary(&self, msg: &RequestMessage) {
match msg.to_binary() {
Ok(mut v) => {
let v: &mut [u8] = &mut v[..];
match &self.ws.send_with_u8_array(v) {
Ok(_) => (),
Err(err) => error!("Error sending binary message: [{:?}]", err)
}
}
Err(e) => {
error!("Cannot serialize RequestMessage to binary: {}", e);
}
};
}
}
fn calc_url(src: &str) -> String {
let protocol = if src.contains("s:") { "wss" } else { "ws" };
let cleaned = src
.trim_start_matches("http")
.trim_start_matches("file")
.trim_start_matches("ws")
.trim_start_matches('s')
.trim_start_matches("://")
.trim_end_matches('/')
.split('#')
.collect::<Vec<&str>>()[0]
.split('?')
.collect::<Vec<&str>>()[0];
let slashes: Vec<char> = cleaned.chars().filter(|c| *c == '/').collect();
let path = if slashes.len() < 2 {
let p = format!("{}/s/test", cleaned);
debug!("Using [test] channel [{}]", p);
p
} else {
cleaned.into()
};
format!("{}://{}/connect", protocol, path)
}
|
use lex::Token;
use std::iter::Peekable;
use std::slice::Iter;
type Tokens<'a> = Peekable<Iter<'a, Token>>;
#[derive(Debug, PartialEq)]
pub enum Object {
Empty,
Nonempty(Box<Members>),
}
#[derive(Debug, PartialEq)]
pub enum Members {
Pair(String, Value),
Pairs(String, Value, Box<Members>),
}
#[derive(Debug, PartialEq)]
pub enum Array {
Empty,
Nonempty(Box<Elements>),
}
#[derive(Debug, PartialEq)]
pub enum Elements {
Single(Value),
Many(Value, Box<Elements>),
}
#[derive(Debug, PartialEq)]
pub enum Value {
String(String),
Number(JSONNumber),
Object(Object),
Array(Array),
True,
False,
Null,
}
#[derive(Debug, PartialEq)]
pub enum JSONNumber {
Integer(i32),
Float(f64),
}
#[derive(Debug, PartialEq)]
pub enum ParseError {
ExpectedToken,
}
pub fn parse_object(mut tokens: &mut Tokens) -> Result<Object, ParseError> {
if tokens
.next()
.filter(|t| **t == Token::ObjectStart)
.is_none()
{
return Err(ParseError::ExpectedToken);
}
if tokens.peek().filter(|t| ***t == Token::ObjectEnd).is_some() {
tokens.next();
return Ok(Object::Empty);
}
parse_members(&mut tokens).and_then(|members| {
tokens
.next()
.filter(|t| **t == Token::ObjectEnd)
.map_or(Err(ParseError::ExpectedToken), |_| {
Ok(Object::Nonempty(Box::new(members)))
})
})
}
fn parse_members(mut tokens: &mut Tokens) -> Result<Members, ParseError> {
parse_pair(&mut tokens).and_then(|(key, value)| {
if tokens.peek().filter(|t| ***t == Token::Comma).is_none() {
return Ok(Members::Pair(key, value));
}
tokens.next();
parse_members(&mut tokens).map(|members| Members::Pairs(key, value, Box::new(members)))
})
}
fn parse_pair(mut tokens: &mut Tokens) -> Result<(String, Value), ParseError> {
match (tokens.next(), tokens.next()) {
(Some(&Token::String(ref key)), Some(&Token::Colon)) => {
parse_value(&mut tokens).map(|value| (key.clone(), value))
}
_ => Err(ParseError::ExpectedToken),
}
}
fn parse_value(mut tokens: &mut Tokens) -> Result<Value, ParseError> {
if let Some(t) = tokens.peek().map(|t| *t) {
match *t {
Token::String(ref string) => {
tokens.next();
Ok(Value::String(string.clone()))
}
Token::Integer(number) => {
tokens.next();
Ok(Value::Number(JSONNumber::Integer(number)))
}
Token::Float(number) => {
tokens.next();
Ok(Value::Number(JSONNumber::Float(number)))
}
Token::True => {
tokens.next();
Ok(Value::True)
}
Token::False => {
tokens.next();
Ok(Value::False)
}
Token::Null => {
tokens.next();
Ok(Value::Null)
}
Token::ObjectStart => parse_object(&mut tokens).map(Value::Object),
Token::ArrayStart => parse_array(&mut tokens).map(Value::Array),
_ => Err(ParseError::ExpectedToken),
}
} else {
Err(ParseError::ExpectedToken)
}
}
fn parse_array(mut tokens: &mut Tokens) -> Result<Array, ParseError> {
if tokens.next().filter(|t| **t == Token::ArrayStart).is_none() {
return Err(ParseError::ExpectedToken);
}
if tokens.peek().filter(|t| ***t == Token::ArrayEnd).is_some() {
tokens.next();
return Ok(Array::Empty);
}
parse_elements(&mut tokens).and_then(|elements| {
tokens
.next()
.filter(|t| **t == Token::ArrayEnd)
.map_or(Err(ParseError::ExpectedToken), |_| {
Ok(Array::Nonempty(Box::new(elements)))
})
})
}
fn parse_elements(mut tokens: &mut Tokens) -> Result<Elements, ParseError> {
parse_value(&mut tokens).and_then(|value| {
if tokens.peek().filter(|t| ***t == Token::Comma).is_none() {
return Ok(Elements::Single(value));
}
tokens.next();
parse_elements(&mut tokens).map(|elements| Elements::Many(value, Box::new(elements)))
})
}
#[cfg(test)]
mod test {
use super::*;
use lex::Token;
#[test]
fn test_parse_value_string() {
let result = parse_value(&mut vec![Token::String("string".to_string())].iter().peekable());
assert_eq!(result, Ok(Value::String("string".to_string())));
}
#[test]
fn test_parse_value_number() {
let result = parse_value(&mut vec![Token::Integer(5)].iter().peekable());
assert_eq!(result, Ok(Value::Number(JSONNumber::Integer(5))));
}
#[test]
fn test_parse_value_true() {
let result = parse_value(&mut vec![Token::True].iter().peekable());
assert_eq!(result, Ok(Value::True));
}
#[test]
fn test_parse_value_false() {
let result = parse_value(&mut vec![Token::False].iter().peekable());
assert_eq!(result, Ok(Value::False));
}
#[test]
fn test_parse_value_null() {
let result = parse_value(&mut vec![Token::Null].iter().peekable());
assert_eq!(result, Ok(Value::Null));
}
#[test]
fn test_parse_value_no_token() {
let result = parse_value(&mut vec![].iter().peekable());
assert_eq!(result, Err(ParseError::ExpectedToken));
}
#[test]
fn test_parse_value_invalid_token() {
let result = parse_value(&mut vec![Token::ObjectStart].iter().peekable());
assert_eq!(result, Err(ParseError::ExpectedToken));
}
#[test]
fn test_parse_object_empty() {
let result =
parse_object(&mut vec![Token::ObjectStart, Token::ObjectEnd].iter().peekable());
assert_eq!(result, Ok(Object::Empty));
}
#[test]
fn test_parse_object_member_string() {
let result = parse_object(&mut vec![
Token::ObjectStart,
Token::String("key".to_string()),
Token::Colon,
Token::String("value".to_string()),
Token::ObjectEnd,
].iter()
.peekable());
assert_eq!(
result,
Ok(Object::Nonempty(Box::new(Members::Pair(
"key".to_string(),
Value::String("value".to_string())
))))
);
}
#[test]
fn test_parse_object_members() {
let result = parse_object(&mut vec![
Token::ObjectStart,
Token::String("key1".to_string()),
Token::Colon,
Token::String("value1".to_string()),
Token::Comma,
Token::String("key2".to_string()),
Token::Colon,
Token::String("value2".to_string()),
Token::ObjectEnd,
].iter()
.peekable());
assert_eq!(
result,
Ok(Object::Nonempty(Box::new(Members::Pairs(
"key1".to_string(),
Value::String("value1".to_string()),
Box::new(Members::Pair(
"key2".to_string(),
Value::String("value2".to_string())
))
))))
);
}
#[test]
fn test_parse_object_member_int() {
let result = parse_object(&mut vec![
Token::ObjectStart,
Token::String("key".to_string()),
Token::Colon,
Token::Integer(5),
Token::ObjectEnd,
].iter()
.peekable());
assert_eq!(
result,
Ok(Object::Nonempty(Box::new(Members::Pair(
"key".to_string(),
Value::Number(JSONNumber::Integer(5))
))))
);
}
#[test]
fn test_parse_object_member_float() {
let result = parse_object(&mut vec![
Token::ObjectStart,
Token::String("key".to_string()),
Token::Colon,
Token::Float(0.5),
Token::ObjectEnd,
].iter()
.peekable());
assert_eq!(
result,
Ok(Object::Nonempty(Box::new(Members::Pair(
"key".to_string(),
Value::Number(JSONNumber::Float(0.5))
))))
);
}
#[test]
fn test_parse_object_member_true() {
let result = parse_object(&mut vec![
Token::ObjectStart,
Token::String("key".to_string()),
Token::Colon,
Token::True,
Token::ObjectEnd,
].iter()
.peekable());
assert_eq!(
result,
Ok(Object::Nonempty(Box::new(Members::Pair(
"key".to_string(),
Value::True
))))
);
}
#[test]
fn test_parse_object_member_false() {
let result = parse_object(&mut vec![
Token::ObjectStart,
Token::String("key".to_string()),
Token::Colon,
Token::False,
Token::ObjectEnd,
].iter()
.peekable());
assert_eq!(
result,
Ok(Object::Nonempty(Box::new(Members::Pair(
"key".to_string(),
Value::False
))))
);
}
#[test]
fn test_parse_object_member_null() {
let result = parse_object(&mut vec![
Token::ObjectStart,
Token::String("key".to_string()),
Token::Colon,
Token::Null,
Token::ObjectEnd,
].iter()
.peekable());
assert_eq!(
result,
Ok(Object::Nonempty(Box::new(Members::Pair(
"key".to_string(),
Value::Null
))))
);
}
#[test]
fn test_parse_object_member_array_empty() {
let result = parse_object(&mut vec![
Token::ObjectStart,
Token::String("key".to_string()),
Token::Colon,
Token::ArrayStart,
Token::ArrayEnd,
Token::ObjectEnd,
].iter()
.peekable());
assert_eq!(
result,
Ok(Object::Nonempty(Box::new(Members::Pair(
"key".to_string(),
Value::Array(Array::Empty)
))))
);
}
#[test]
fn test_parse_object_member_array_element() {
let result = parse_object(&mut vec![
Token::ObjectStart,
Token::String("key".to_string()),
Token::Colon,
Token::ArrayStart,
Token::Integer(5),
Token::ArrayEnd,
Token::ObjectEnd,
].iter()
.peekable());
assert_eq!(
result,
Ok(Object::Nonempty(Box::new(Members::Pair(
"key".to_string(),
Value::Array(Array::Nonempty(Box::new(Elements::Single(Value::Number(
JSONNumber::Integer(5)
)))))
))))
);
}
#[test]
fn test_parse_object_member_array_elements() {
let result = parse_object(&mut vec![
Token::ObjectStart,
Token::String("key".to_string()),
Token::Colon,
Token::ArrayStart,
Token::Integer(5),
Token::Comma,
Token::String("elements".to_string()),
Token::ArrayEnd,
Token::ObjectEnd,
].iter()
.peekable());
assert_eq!(
result,
Ok(Object::Nonempty(Box::new(Members::Pair(
"key".to_string(),
Value::Array(Array::Nonempty(Box::new(Elements::Many(
Value::Number(JSONNumber::Integer(5)),
Box::new(Elements::Single(Value::String("elements".to_string())))
))))
))))
);
}
#[test]
fn test_parse_object_member_object() {
let result = parse_object(&mut vec![
Token::ObjectStart,
Token::String("key".to_string()),
Token::Colon,
Token::ObjectStart,
Token::ObjectEnd,
Token::ObjectEnd,
].iter()
.peekable());
assert_eq!(
result,
Ok(Object::Nonempty(Box::new(Members::Pair(
"key".to_string(),
Value::Object(Object::Empty)
))))
);
}
}
|
extern crate rmp_serde;
extern crate serde;
#[macro_use]
extern crate serde_derive;
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
struct A {
b: B,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "kind", content = "data")]
#[serde(rename_all = "snake_case")]
pub enum B {
First,
Second
}
fn main() {
println!("Hello, world!");
let a = A {
b: B::First,
};
let a = rmp_serde::to_vec(&a).unwrap();
let a: A = rmp_serde::from_slice(&a).unwrap();
println!("a: {:?}", a);
}
|
use std::collections::BTreeMap;
use std::process::Stdio;
use k8s_openapi::api::core::v1::Secret;
use kube::api::ObjectMeta;
use oauth2::prelude::*;
use oauth2::AccessToken;
use serde_derive::{Deserialize, Serialize};
use serde_json::{json, Value};
use tokio::prelude::*;
use tokio::process::Command;
use crate::Targets;
/// The credentials returned as JSON by a docker credentials helper command.
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct Credentials {
#[serde(rename = "Username")]
username: String,
#[serde(rename = "Secret")]
secret: String,
}
pub struct CredentialConfiguration<'a> {
secret_name: &'a str,
targets: &'a Targets,
}
impl<'a> CredentialConfiguration<'a> {
pub fn new(secret_name: &'a str, targets: &'a Targets) -> CredentialConfiguration<'a> {
CredentialConfiguration {
secret_name,
targets,
}
}
}
pub trait K8sImagePullSecret {
fn registry_url(&self) -> &str;
fn namespace(&self) -> &str;
fn name(&self) -> &str;
fn targets(&self) -> &Targets;
}
impl Credentials {
/// Constructs a new instance by forking a `gcloud` child process.
pub async fn from_gcloud() -> anyhow::Result<Self> {
let mut child = Command::new("gcloud")
.arg("auth")
.arg("docker-helper")
.arg("get")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()?;
child
.stdin
.as_mut()
.unwrap()
.write_all(b"https://gcr.io") // url does not matter, same token used for all
.await?;
serde_json::from_slice(&child.wait_with_output().await?.stdout).map_err(|e| e.into())
}
/// Constructs a new instance from an access token
pub fn from_access_token(token: &AccessToken, username: Option<&str>) -> Self {
Credentials {
// we have to impersonate https://github.com/GoogleCloudPlatform/docker-credential-gcr/
username: username.unwrap_or("_dcgcr_2_0_1_token").into(),
secret: token.secret().into(),
}
}
/// Converts the credentials into a named secret for the specified namespace.
pub fn as_secret(&self, config: CredentialConfiguration<'_>) -> Secret {
let auths: BTreeMap<String, Value> = config
.targets
.registry_urls()
.iter()
.map(|url| {
(
(*url).to_string(),
json! {
{
"username": self.username.clone(),
"password": self.secret.clone(),
"auths": base64::encode(format!("{}:{}", self.username, self.secret))
}
},
)
})
.collect();
Secret {
metadata: Some(ObjectMeta {
name: Some(config.secret_name.into()),
namespace: Some(config.targets.namespace().into()),
labels: Some(
vec![
(
"app.kubernetes.io/name".to_string(),
env!("CARGO_PKG_NAME").to_string(),
),
(
"app.kubernetes.io/version".to_string(),
env!("CARGO_PKG_VERSION").to_string(),
),
(
"app.kubernetes.io/component".to_string(),
"dockerconfigjson".to_string(),
),
(
"app.kubernetes.io/managed-by".to_string(),
env!("CARGO_PKG_NAME").to_string(),
),
]
.into_iter()
.collect(),
),
..Default::default()
}),
type_: Some("kubernetes.io/dockerconfigjson".into()),
string_data: Some(
vec![(
".dockerconfigjson".to_string(),
json!({ "auths": auths }).to_string(),
)]
.into_iter()
.collect(),
),
..Default::default()
}
}
/// Converts the credentials into the byte array of its Secret form serialized as JSON.
pub fn as_secret_bytes(&self, config: CredentialConfiguration<'_>) -> Vec<u8> {
serde_json::to_string(&self.as_secret(config))
.unwrap()
.into_bytes()
}
}
|
use aoc20::days::day14;
#[test]
fn day14_parse_mask() {
let m = day14::Mask::parse("mask = XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X").unwrap();
assert_eq!(m, day14::Mask::new(0x40, 0xF_FFFF_FFBD));
}
#[test]
fn day14_parse_mem() {
let m = day14::Mem::parse("mem[36932] = 186083").unwrap();
assert_eq!(m, day14::Mem::new(36932, 186083));
}
#[test]
fn day14_parse_mem_mask() {
let m = day14::MemMask::parse("mask = 000000000000000000000000000000X1001X").unwrap();
assert_eq!(m, day14::MemMask::new(0x12, 0xF_FFFF_FFDE, vec![0, 5]));
}
#[test]
fn day14_parse_mem_mask_iter() {
let m = day14::MemMask::parse("mask = 000000000000000000000000000000X1001X").unwrap();
assert_eq!(m.collect::<Vec<u64>>(), vec![0, 1, 0x20, 0x21]);
}
#[test]
fn day14_parse_mem_mask_iter2() {
let m = day14::MemMask::parse("mask = 00000000000000000000000000000000X0XX").unwrap();
assert_eq!(m.collect::<Vec<u64>>(), vec![0, 1, 2, 3, 8, 9, 10, 11]);
}
#[test]
fn day14_parse_mem_mask_iter3() {
let m = day14::MemMask::parse("mask = 000000000000000000000000000000X1001X").unwrap();
let value = m.condition(42);
assert_eq!(m.map(|fl| value | fl).collect::<Vec<u64>>(), vec![26, 27, 58, 59]);
}
|
use std::fs;
use std::io::{self, Write};
use aspotify::{Client, ClientCredentials, Scope};
#[tokio::main]
async fn main() {
// Read .env file into environment variables.
dotenv::dotenv().unwrap();
// Create the Spotify client from the credentials in the env variables.
let client = Client::new(ClientCredentials::from_env().unwrap());
// Get the URL to send the user to, requesting all the scopes and redirecting to a non-existant website.
let (url, state) = aspotify::authorization_url(
&client.credentials.id,
[
Scope::UgcImageUpload,
Scope::UserReadPlaybackState,
Scope::UserModifyPlaybackState,
Scope::UserReadCurrentlyPlaying,
Scope::Streaming,
Scope::AppRemoteControl,
Scope::UserReadEmail,
Scope::UserReadPrivate,
Scope::PlaylistReadCollaborative,
Scope::PlaylistModifyPublic,
Scope::PlaylistReadPrivate,
Scope::PlaylistModifyPrivate,
Scope::UserLibraryModify,
Scope::UserLibraryRead,
Scope::UserTopRead,
Scope::UserReadRecentlyPlayed,
Scope::UserFollowRead,
Scope::UserFollowModify,
]
.iter()
.copied(),
false,
"http://non.existant/",
);
// Get the user to authorize our application.
println!("Go to this website: {}", url);
// Receive the URL that was redirected to.
print!("Enter the URL that you were redirected to: ");
io::stdout().flush().unwrap();
let mut redirect = String::new();
io::stdin().read_line(&mut redirect).unwrap();
// Create the refresh token from the redirected URL.
client.redirected(&redirect, &state).await.unwrap();
// Put the refresh token in a file.
fs::write(".refresh_token", client.refresh_token().await.unwrap()).unwrap();
}
|
use consts;
use hidapi::{HidResult, HidApi, HidDevice};
pub struct LuxaforDeviceDescriptor {
pub vendor_id : u16,
pub product_id : u16
}
pub struct LuxaforContext {
hid_api : HidApi
}
pub struct LuxaforDevice<'a> {
hid_device : HidDevice<'a>
}
impl LuxaforContext {
pub fn new() -> HidResult<LuxaforContext> {
Ok(LuxaforContext {
hid_api: HidApi::new()?
})
}
pub fn open_device(&self, device_descriptor: LuxaforDeviceDescriptor) -> HidResult<LuxaforDevice> {
LuxaforDevice::new(self.hid_api.open(device_descriptor.vendor_id, device_descriptor.product_id)?)
}
}
impl<'a> LuxaforDevice<'a> {
pub fn new(device: HidDevice) -> HidResult<LuxaforDevice> {
Ok(LuxaforDevice {
hid_device: device
})
}
pub fn solid(self, r: u8, g: u8, b: u8) -> HidResult<usize> {
self.hid_device.write(&[consts::mode::STATIC, consts::led::ALL, r, g, b])
}
}
|
use lexer::{Input, State, Reader};
use super::super::token::{Token, TokenKind};
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct OperatorsReader;
impl Reader<TokenKind> for OperatorsReader {
#[inline(always)]
fn priority(&self) -> usize { 3usize }
fn read(&self, input: &Input, state: &mut State) -> Option<Token> {
let ch = input.read(state);
if input.has_char_at(state, 0) {
let next_ch = input.char_at(state, 0);
let kind = match (ch, next_ch) {
('=','=') => Some(TokenKind::EQ),
('!', '=') => Some(TokenKind::NEQ),
('<', '=') => Some(TokenKind::LTE),
('>', '=') => Some(TokenKind::GTE),
(':', '=') => Some(TokenKind::DECLARE_BIND),
('&', '&') => Some(TokenKind::LOGICAL_AND),
('|', '|') => Some(TokenKind::LOGICAL_OR),
('+', '=') => Some(TokenKind::ADD_REBIND),
('-', '=') => Some(TokenKind::SUB_REBIND),
('*', '=') => Some(TokenKind::MUL_REBIND),
('/', '=') => Some(TokenKind::DIV_REBIND),
('%', '=') => Some(TokenKind::MOD_REBIND),
('&', '=') => Some(TokenKind::BIT_AND_REBIND),
('|', '=') => Some(TokenKind::BIT_OR_REBIND),
('^', '=') => Some(TokenKind::BIT_XOR_REBIND),
('~', '=') => Some(TokenKind::BIT_NOT_REBIND),
('<', '<') => Some(TokenKind::BIT_LSHIFT),
('>', '>') => Some(TokenKind::BIT_RSHIFT),
(_, _) => None,
};
if kind.is_some() {
let mut value = String::new();
input.read(state);
value.push(ch);
value.push(next_ch);
return Some(Token::new(
input.new_state_meta(state),
kind.unwrap(),
value
))
}
}
let kind = match ch {
'=' => Some(TokenKind::BIND),
':' => Some(TokenKind::DECLARE_TYPE),
'<' => Some(TokenKind::LT),
'>' => Some(TokenKind::GT),
'+' => Some(TokenKind::ADD),
'-' => Some(TokenKind::SUB),
'*' => Some(TokenKind::MUL),
'/' => Some(TokenKind::DIV),
'%' => Some(TokenKind::MOD),
'&' => Some(TokenKind::BIT_AND),
'|' => Some(TokenKind::BIT_OR),
'^' => Some(TokenKind::BIT_XOR),
'~' => Some(TokenKind::BIT_NOT),
_ => None,
};
if kind.is_some() {
let mut value = String::new();
value.push(ch);
Some(Token::new(
input.new_state_meta(state),
kind.unwrap(),
value
))
} else {
None
}
}
}
|
#[cfg(feature = "textfield")]
mod textfield;
#[cfg(feature = "textfield")]
pub use textfield::*;
#[cfg(any(feature = "textfield", feature = "textarea"))]
pub(crate) mod validity_state;
#[cfg(any(feature = "textfield", feature = "textarea"))]
pub use validity_state::ValidityState;
#[cfg(any(feature = "textfield", feature = "textarea"))]
pub(crate) mod text_field_type;
#[cfg(any(feature = "textfield", feature = "textarea"))]
pub use text_field_type::*;
#[cfg(feature = "textarea")]
mod textarea;
#[cfg(feature = "textarea")]
pub use textarea::*;
#[cfg(any(feature = "textfield", feature = "textarea"))]
pub use web_sys::ValidityState as NativeValidityState;
use std::rc::Rc;
use gloo::events::EventListener;
use wasm_bindgen::{JsCast, JsValue};
use web_sys::{Element, Event, InputEvent};
use yew::{Callback, InputData, NodeRef};
#[cfg(any(feature = "textfield", feature = "textarea"))]
pub(crate) type ValidityTransformFn = dyn Fn(String, NativeValidityState) -> ValidityState;
#[cfg(any(feature = "textfield", feature = "textarea"))]
#[derive(Clone)]
/// Owned function for validity props
pub struct ValidityTransform(pub(crate) Rc<ValidityTransformFn>);
#[cfg(any(feature = "textfield", feature = "textarea"))]
impl ValidityTransform {
pub(crate) fn new<F: Fn(String, NativeValidityState) -> ValidityState + 'static>(
func: F,
) -> ValidityTransform {
ValidityTransform(Rc::new(func))
}
}
fn set_on_input_handler(
node_ref: &NodeRef,
callback: Callback<InputData>,
convert: impl Fn((InputEvent, JsValue)) -> InputData + 'static,
) -> EventListener {
let element = node_ref.cast::<Element>().unwrap();
EventListener::new(&element, "input", move |event: &Event| {
let js_value = JsValue::from(event);
let input_event = js_value
.clone()
.dyn_into::<web_sys::InputEvent>()
.expect("could not convert to `InputEvent`");
callback.emit(convert((input_event, js_value)))
})
}
|
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, RwLock};
use std::sync::mpsc::Sender;
use std::fs;
use std::thread;
use super::{Error, Event, op, Watcher};
use std::path::{Path, PathBuf};
use std::time::Duration;
use self::walkdir::WalkDir;
use filetime::FileTime;
extern crate walkdir;
pub struct PollWatcher {
tx: Sender<Event>,
watches: Arc<RwLock<HashSet<PathBuf>>>,
open: Arc<RwLock<bool>>
}
impl PollWatcher {
pub fn with_delay(tx: Sender<Event>, delay: u32) -> Result<PollWatcher, Error> {
let mut p = PollWatcher {
tx: tx,
watches: Arc::new(RwLock::new(HashSet::new())),
open: Arc::new(RwLock::new(true))
};
p.run(delay);
Ok(p)
}
fn run(&mut self, delay: u32) {
let tx = self.tx.clone();
let watches = self.watches.clone();
let open = self.open.clone();
thread::spawn(move || {
// In order of priority:
// TODO: populate mtimes before loop, and then handle creation events
// TODO: handle deletion events
// TODO: handle chmod events
// TODO: handle renames
// TODO: DRY it up
let mut mtimes: HashMap<PathBuf, u64> = HashMap::new();
loop {
if delay != 0 {
thread::sleep(Duration::from_millis(delay as u64));
}
if !(*open.read().unwrap()) {
break
}
for watch in watches.read().unwrap().iter() {
let meta = fs::metadata(watch);
if !meta.is_ok() {
let _ = tx.send(Event {
path: Some(watch.clone()),
op: Err(Error::PathNotFound)
});
continue
}
match meta {
Err(e) => {
let _ = tx.send(Event {
path: Some(watch.clone()),
op: Err(Error::Io(e))
});
continue
},
Ok(stat) => {
let modified =
FileTime::from_last_modification_time(&stat)
.seconds();
match mtimes.insert(watch.clone(), modified) {
None => continue, // First run
Some(old) => {
if modified > old {
let _ = tx.send(Event {
path: Some(watch.clone()),
op: Ok(op::WRITE)
});
continue
}
}
}
if !stat.is_dir() { continue }
}
}
// TODO: more efficient implementation where the dir tree is cached?
for entry in WalkDir::new(watch).follow_links(true)
.into_iter().filter_map(|e| e.ok()) {
let path = entry.path();
match fs::metadata(&path) {
Err(e) => {
let _ = tx.send(Event {
path: Some(path.to_path_buf()),
op: Err(Error::Io(e))
});
continue
},
Ok(stat) => {
let modified = FileTime::from_last_modification_time(&stat).seconds();
match mtimes.insert(path.to_path_buf(), modified) {
None => continue, // First run
Some(old) => {
if modified > old {
let _ = tx.send(Event {
path: Some(path.to_path_buf()),
op: Ok(op::WRITE)
});
continue
}
}
}
}
}
}
}
}
});
}
}
impl Watcher for PollWatcher {
fn new(tx: Sender<Event>) -> Result<PollWatcher, Error> {
PollWatcher::with_delay(tx, 10)
}
fn watch<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error> {
(*self.watches).write().unwrap().insert(path.as_ref().to_path_buf());
Ok(())
}
fn unwatch<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error> {
if (*self.watches).write().unwrap().remove(path.as_ref()) {
Ok(())
} else {
Err(Error::WatchNotFound)
}
}
}
impl Drop for PollWatcher {
fn drop(&mut self) {
{
let mut open = (*self.open).write().unwrap();
(*open) = false;
}
}
}
|
use crate::util::prelude::*;
use crate::state::prelude::*;
use crate::gfx;
use crate::gfx::glyph_gfx::*;
use std::collections::{HashMap, HashSet};
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
pub enum RenderModifier {
GravityInverse,
}
struct CachedRegion {
tick: Tick,
region: GfxRegion
}
pub struct WorldRenderer {
world_id: WorldId,
render_modifiers: HashSet<RenderModifier>,
render_cache: HashMap<(i32, i32, i32), CachedRegion>,
camera: gfx::camera::Camera,
}
const OFF_SCREEN_RENDER_HEURISTIC: i32 = 2;
impl WorldRenderer {
pub fn new(world_id: WorldId) -> Self {
let camera = gfx::camera::Camera {
world_offset: (0, 0, 0),
region_offset: (0, 0),
// TODO: Assuming glyph size of (10, 20) and window size of (1280, 720).
tiles_dims: (128, 36),
};
Self {
world_id,
render_modifiers: HashSet::new(),
render_cache: HashMap::new(),
camera,
}
}
pub fn render(
&mut self,
// TODO: Separate the world from the cache so that we don't need a mutable handle to the world.
world: &mut World,
glyph_context: &mut gfx::glyph_context::MonospaceGlyphContext,
) {
assert!(self.world_id == world.id,
"World renderer called with a different world than the one with which is was initialized.");
// TODO: All this logic should be in the camera. probably.
let (base_region_x, base_region_y, z) = self.camera.world_offset;
let (render_size_x, render_size_y) = self.camera.tiles_dims;
let regions_wide = ((render_size_x / REGION_DIM as u32) + 1) as i32;
let regions_tall = ((render_size_y / REGION_DIM as u32) + 1) as i32;
let base_y = base_region_y - OFF_SCREEN_RENDER_HEURISTIC;
let final_y = base_region_y + regions_tall + OFF_SCREEN_RENDER_HEURISTIC;
let base_x = base_region_x - OFF_SCREEN_RENDER_HEURISTIC;
let final_x = base_region_x + regions_wide + OFF_SCREEN_RENDER_HEURISTIC;
for y in base_y..final_y {
for x in base_x..final_x {
self.render_offset(world, glyph_context, (x, y, z));
}
}
}
fn render_offset(
&mut self,
world: &mut World,
glyph_context: &mut gfx::glyph_context::MonospaceGlyphContext,
offset: (i32, i32, i32),
) {
let (tile_x, tile_y) = self.camera.get_screen_coords(offset);
let region = &self.get_cached_region(world, offset).region;
let mut section = wgpu_glyph::Section {
screen_position: (
tile_x as f32 * glyph_context.glyph_width,
tile_y as f32 * glyph_context.glyph_height,
),
..wgpu_glyph::Section::default()
};
// Do not attempt to render a region if its `Tiles` vector is malformed.
if region.tiles.len() != REGION_DIM as usize * REGION_DIM as usize {
return;
}
for y in 0..REGION_DIM {
for x in 0..REGION_DIM {
let idx = (y as usize * REGION_DIM as usize) + x as usize;
let tile = ®ion.tiles[idx];
section = section.add_text(
wgpu_glyph::Text::new(tile.glyph.glyph)
.with_color(tile.fg)
.with_scale(glyph_context.get_px_scale())
);
}
// TODO: Is this really the best way to do this?
section = section.add_text(wgpu_glyph::Text::new("\n"));
}
glyph_context.glyph_context.glyph_brush.queue(section);
}
fn get_cached_region(
&mut self,
world: &World,
offset: (i32, i32, i32),
) -> &CachedRegion {
// TODO: This logic is haphazard.
if let Some(world_region) = world.get_cached_region(offset) {
let render_modifiers = &self.render_modifiers;
self.render_cache.entry(offset)
.and_modify(|cached_region| {
if world_region.last_update_tick > cached_region.tick {
*cached_region = CachedRegion {
region: gen_gfx_region(&world_region.region, render_modifiers),
tick: world.current_tick,
};
}
})
.or_insert_with(|| CachedRegion {
region: gen_gfx_region(&world_region.region, render_modifiers),
tick: world.current_tick,
})
} else {
// The region wasn't loaded in memory, so there's no way we can render it. Just "render"
// the empty region instead.
self.render_cache.entry(offset)
.and_modify(|cr| *cr = CachedRegion {
region: GfxRegion::empty(),
// Aggressively try to rerender this region.
tick: world.current_tick - 1,
})
.or_insert_with(|| CachedRegion {
region: GfxRegion::empty(),
// Aggressively try to rerender this region.
tick: world.current_tick - 1,
})
}
}
pub fn add_render_modifier(&mut self, render_modifier: RenderModifier) {
self.render_cache.clear();
self.render_modifiers.insert(render_modifier);
}
pub fn remove_render_modifier(&mut self, render_modifier: RenderModifier) {
self.render_cache.clear();
self.render_modifiers.remove(&render_modifier);
}
}
fn gen_gfx_region(region: &Region, _render_modifiers: &HashSet<RenderModifier>) -> GfxRegion {
let mut tiles = Vec::with_capacity(REGION_DIM as usize * REGION_DIM as usize);
for b in ®ion.blocks {
match b.fill {
BlockFill::Solid(_m_id) => tiles.push(GfxTile {
glyph: GfxGlyph::new("#"),
fg: [1.0, 0.0, 0.0, 1.0],
bg: [0.0, 1.0, 0.0, 1.0],
}),
BlockFill::Floor(_m_id) => tiles.push(GfxTile {
glyph: GfxGlyph::new("."),
fg: [0.0, 0.0, 1.0, 1.0],
bg: [0.0, 0.0, 0.0, 1.0],
}),
_ => todo!(),
}
}
GfxRegion { tiles }
}
|
fn main() {
//let target = "world";
let mut target = "world";
let mut greeting = "Hello";
println!("{}, {}", greeting, target);
greeting = "How's it goin'";
target = "mate";
println!("{}, {}", greeting, target);
}
|
use regex::Regex;
fn main() {
let input = include_str!("../data/2015-06.txt");
println!("Part 1: {}", part1(input));
println!("Part 2: {}", part2(input));
}
fn part1(input: &str) -> u32 {
let adjust = |act: &str, light: &mut u16| {
match act {
"turn on" => *light = 1,
"turn off" => *light = 0,
_ => *light ^= 1
}
};
lights(input, adjust)
}
fn part2(input: &str) -> u32 {
let adjust = |act: &str, light: &mut u16| {
match act {
"turn on" => *light += 1,
"turn off" => *light = light.saturating_sub(1),
_ => *light += 2
}
};
lights(input, adjust)
}
fn lights(input: &str, adjust: fn(&str, &mut u16)) -> u32 {
let mut lights = [[0u16; 1_000]; 1_000];
let pattern = r"(turn on|turn off|toggle) (\d+),(\d+) through (\d+),(\d+)";
for line in Regex::new(pattern).unwrap().captures_iter(input) {
let x1 = line[2].parse().unwrap();
let y1 = line[3].parse().unwrap();
let x2 = line[4].parse().unwrap();
let y2 = line[5].parse().unwrap();
for row in &mut lights[y1..=y2] {
for light in &mut row[x1..=x2] {
adjust(&line[1], light);
}
}
}
let mut on = 0;
for row in &lights {
for light in row {
on += *light as u32;
}
}
on
}
#[test]
fn test1() {
aoc::test(part1, [
("turn on 0,0 through 999,999", 1_000_000),
("toggle 0,0 through 999,0", 1_000),
("turn off 499,499 through 500,500", 0)
])
}
#[test]
fn test2() {
aoc::test(part2, [
("turn on 0,0 through 0,0", 1),
("toggle 0,0 through 999,999", 2_000_000)
])
}
|
use crate::{KvsError, Result};
use serde::{Deserialize, Serialize};
use serde_json;
use std::collections::HashMap;
use std::fs::{self, OpenOptions};
use std::io::{BufWriter, Write};
use std::io::{BufReader, Read};
use std::io::{Seek, SeekFrom};
use std::path::PathBuf;
const MAX_UNCOMPACTED_SIZE: u64 = 1024 * 1024;
#[derive(Debug, Deserialize, Serialize)]
enum Command {
Set { key: String, value: String },
Rm { key: String },
Get { key: String },
}
/// the `KvStore` using a hashmap to store log in the memory
/// log is presented by a position in the file and the length of it
pub struct KvStore {
map: HashMap<String, LogInFile>,
command: Option<Command>,
buffer: BufReader<std::fs::File>,
position: u64,
uncompacted_size: u64,
path: PathBuf,
}
impl KvStore {
fn new(buffer: BufReader<std::fs::File>, path: PathBuf) -> KvStore {
KvStore {
map: HashMap::new(),
command: None,
buffer,
position: 0,
uncompacted_size: 0,
path,
}
}
/// This method used to set a new key-value pair,
/// It can also be used to update the value of a key
/// An `KvsError::IoError` or `KvsError::SerdeError` may return
pub fn set(&mut self, key: String, value: String) -> Result<()> {
let key_clone = key.clone();
self.command = Some(Command::Set { key, value });
let j = serde_json::to_string(&self.command)?;
let len = (j.len() + "\n".len()) as u64;
self.map
.insert(key_clone, LogInFile::new(self.position, len));
self.position += len;
let mut f = self.buffer.get_ref();
serde_json::to_writer(f, &self.command)?;
// Question: using `%` to separate commands can not pass the get_stored_key test
f.write(b"\n")?;
self.uncompacted_size += len;
if self.uncompacted_size > MAX_UNCOMPACTED_SIZE {
self.compact()?;
}
Ok(())
}
/// This method used to get a value of the key in the Option.
/// Key not been set will return `Ok(None)`
/// An `KvsError::IoError` or `KvsError::SerdeError` may return
pub fn get(&mut self, key: String) -> Result<Option<String>> {
match self.map.get(&key) {
None => Ok(None),
Some(log) => {
let reader = self.buffer.get_mut();
reader.seek(SeekFrom::Start(log.offset))?;
let cmd = reader.take(log.length);
if let Command::Set { value, .. } = serde_json::from_reader(cmd)? {
Ok(Some(value))
} else {
Ok(None)
}
}
}
}
/// This method used to remove a key-value pair
/// if the given key is not exist, a `KvsError::KeyNotFoundError` will be returned
/// An `KvsError::IoError` or `KvsError::SerdeError` may return
pub fn remove(&mut self, key: String) -> Result<()> {
match self.map.get(&key) {
None => return Err(KvsError::KeyNotFoundError),
Some(_) => {
self.map.remove(&key);
self.command = Some(Command::Rm { key });
let j = serde_json::to_string(&self.command)?;
let len = (j.len() + "\n".len()) as u64;
self.position += len;
self.uncompacted_size += len;
let mut f = self.buffer.get_ref();
serde_json::to_writer(f, &self.command)?;
f.write(b"\n")?;
if self.uncompacted_size > MAX_UNCOMPACTED_SIZE {
self.compact()?;
}
}
}
Ok(())
}
/// This method is used to create a KvStore
/// It will read the "kvs-data.json" file in the path
/// initiate the key-log record in the memory.
pub fn open(path: impl Into<PathBuf>) -> Result<KvStore> {
let mut path: PathBuf = path.into();
let path_clone = path.clone();
path.push("kvs-data.json");
let f = OpenOptions::new()
.read(true)
.write(true)
.append(true)
.create(true)
.open(&path)?;
let buffer = BufReader::new(f);
let mut str_buffer = String::new();
let mut kvstore = KvStore::new(buffer, path_clone);
kvstore.buffer.read_to_string(&mut str_buffer)?;
for s in str_buffer.split("\n").collect::<Vec<&str>>() {
if s.len() == 0 {
continue;
}
let len = s.len() as u64;
let c: Command = serde_json::from_str(s)?;
match c {
Command::Set { key, .. } => {
kvstore
.map
.insert(key, LogInFile::new(kvstore.position, len));
}
Command::Rm { key } => {
kvstore.map.remove(&key);
}
_ => (),
}
kvstore.position += len + "\n".len() as u64;
}
Ok(kvstore)
}
/// this method is used to compact the log file
/// it will be automatically used by `rm` and `set` when uncompacted data size
/// exceed a fixed size
pub fn compact(&mut self) -> Result<()> {
let mut path_from = self.path.clone();
let mut path_to = self.path.clone();
path_from.push("kvs-data-compact.json");
path_to.push("kvs-data.json");
let f = OpenOptions::new()
.write(true)
.append(true)
.create(true)
.open(&path_from)?;
let reader = self.buffer.get_mut();
let new_reader = BufReader::new(f.try_clone()?);
let mut writer = BufWriter::new(f);
let mut new_offset: u64 = 0;
for (_key, LogInFile { offset, length }) in self.map.iter_mut() {
reader.seek(SeekFrom::Start(*offset))?;
let mut cmd = reader.take(*length);
std::io::copy(&mut cmd, &mut writer)?;
*offset = new_offset;
// Question: I still don't know why the compact test will add the split of mine twice.
// `set` 里面的 len 设置的确实是加上了 `\n` 之后的
// f.write(b"\n")?;
new_offset += *length + "\n".len() as u64;
new_offset += *length;
}
// rename 后原先的 path_to 对应的 bufreader 流就被关闭了,因此需要重新开一个
fs::rename(path_from, path_to)?;
self.uncompacted_size = 0;
self.position = writer.seek(SeekFrom::End(0))?;
self.buffer = new_reader;
Ok(())
}
}
struct LogInFile {
offset: u64,
length: u64,
}
impl LogInFile {
fn new(offset: u64, length: u64) -> LogInFile {
LogInFile { offset, length }
}
}
// In the author's code. The logs are in different files.
// every time he open a kvstore, a new log file was build, and the next log file index
// is found while scanning existing log file in the directory.
// While opening, besides store the key-[log position] pair, he also store a key-reader pair
// cause keys may not in the same log file.
// As same as the `compact` function as mine, he just scans the index-[log pos] map
// and copy the exist log to a new file (Though the file name is 1+largest index of log file now).
#[test]
fn my_test() -> Result<()> {
let mut store = KvStore::open(std::env::current_dir()?)?;
for iter in 0..28 {
for key_id in 0..1000 {
let key = format!("key{}", key_id);
let value = format!("{}", iter);
store.set(key, value)?;
}
}
Ok(())
} |
#![allow(non_upper_case_globals)]
mod bigger;
mod hint;
mod rankings;
mod skip;
mod stop;
mod tags;
use std::sync::Arc;
use bitflags::bitflags;
use dashmap::mapref::entry::Entry;
use eyre::Report;
use rosu_v2::prelude::GameMode;
use twilight_model::{
application::{
command::CommandOptionChoice,
component::{
button::ButtonStyle, select_menu::SelectMenuOption, ActionRow, Button, Component,
SelectMenu,
},
interaction::{
application_command::CommandOptionValue, ApplicationCommand,
MessageComponentInteraction,
},
},
channel::{
embed::{Embed, EmbedField},
Reaction,
},
http::interaction::{InteractionResponse, InteractionResponseData, InteractionResponseType},
id::{marker::UserMarker, Id},
};
use crate::{
bg_game::{GameWrapper, MapsetTags},
commands::{parse_mode_option, MyCommand, MyCommandOption},
embeds::{BGTagsEmbed, EmbedBuilder, EmbedData},
error::{Error, InvalidBgState},
util::{
constants::{
common_literals::{HELP, MANIA, MODE, OSU, SPECIFY_MODE},
GENERAL_ISSUE, RED,
},
InteractionExt, MessageBuilder, MessageExt,
},
BotResult, CommandData, Context,
};
pub use self::{bigger::*, hint::*, rankings::*, skip::*, stop::*, tags::*};
#[command]
#[short_desc("Play the background guessing game, use `/bg` to start")]
#[aliases("bg")]
#[sub_commands(skip, bigger, hint, stop, rankings)]
pub async fn backgroundgame(ctx: Arc<Context>, data: CommandData) -> BotResult<()> {
match data {
CommandData::Message { msg, mut args, .. } => match args.next() {
None | Some(HELP) => {
let content = "Use `/bg` to start a new background guessing game.\n\
Given part of a map's background, try to guess the **title** of the map's song.\n\
You don't need to guess content in parentheses `(...)` or content after `ft.` or `feat.`.\n\n\
Use these prefix commands to initiate with the game:\n\
• `<bg s[kip]` / `<bg r[esolve]`: Resolve the current background and \
give a new one with the same tag specs.\n\
• `<bg h[int]`: Receive a hint (can be used multiple times).\n\
• `<bg b[igger]`: Increase the radius of the displayed image (can be used multiple times).\n\
• `<bg stop`: Resolve the current background and stop the game.
• `<bg l[eaderboard] s[erver]`: Check out the global leaderboard for \
amount of correct guesses. If `server` or `s` is added at the end, \
I will only show members of this server.";
let builder = MessageBuilder::new().embed(content);
msg.create_message(&ctx, builder).await?;
Ok(())
}
_ => {
let prefix = ctx.guild_first_prefix(msg.guild_id).await;
let content =
format!("That's not a valid subcommand. Check `{prefix}bg` for more help.");
msg.error(&ctx, content).await
}
},
CommandData::Interaction { .. } => unreachable!(),
}
}
enum ReactionWrapper {
Add(Reaction),
Remove(Reaction),
}
impl ReactionWrapper {
fn as_deref(&self) -> &Reaction {
match self {
Self::Add(r) | Self::Remove(r) => r,
}
}
}
bitflags! {
pub struct Effects: u8 {
const Blur = 1 << 0;
const Contrast = 1 << 1;
const FlipHorizontal = 1 << 2;
const FlipVertical = 1 << 3;
const Grayscale = 1 << 4;
const Invert = 1 << 5;
}
}
#[derive(Copy, Clone, Debug)]
pub enum GameDifficulty {
Normal,
Hard,
Impossible,
}
impl GameDifficulty {
pub fn value(self) -> f32 {
match self {
GameDifficulty::Normal => 0.5,
GameDifficulty::Hard => 0.75,
GameDifficulty::Impossible => 0.95,
}
}
}
impl Default for GameDifficulty {
fn default() -> Self {
Self::Normal
}
}
pub enum BgGameState {
Running {
game: GameWrapper,
},
Setup {
author: Id<UserMarker>,
difficulty: GameDifficulty,
effects: Effects,
excluded: MapsetTags,
included: MapsetTags,
},
}
fn parse_component_tags(component: &MessageComponentInteraction) -> MapsetTags {
component
.data
.values
.iter()
.fold(MapsetTags::empty(), |tags, value| {
tags | match value.as_str() {
"easy" => MapsetTags::Easy,
"hard" => MapsetTags::Hard,
"meme" => MapsetTags::Meme,
"weeb" => MapsetTags::Weeb,
"kpop" => MapsetTags::Kpop,
"farm" => MapsetTags::Farm,
"hardname" => MapsetTags::HardName,
"alt" => MapsetTags::Alternate,
"bluesky" => MapsetTags::BlueSky,
"english" => MapsetTags::English,
"streams" => MapsetTags::Streams,
"old" => MapsetTags::Old,
"tech" => MapsetTags::Tech,
_ => {
warn!("unknown mapset tag `{value}`");
return tags;
}
}
})
}
async fn update_field(
ctx: &Context,
component: &mut MessageComponentInteraction,
tags: MapsetTags,
name: &str,
) -> BotResult<()> {
let mut embed = component
.message
.embeds
.pop()
.ok_or(InvalidBgState::MissingEmbed)?;
let field_opt = embed.fields.iter_mut().find(|field| field.name == name);
if let Some(field) = field_opt {
field.value = tags.join(", ");
} else {
let field = EmbedField {
inline: false,
name: name.to_owned(),
value: tags.join(", "),
};
embed.fields.push(field);
}
let data = InteractionResponseData {
embeds: Some(vec![embed]),
..Default::default()
};
let response = InteractionResponse {
kind: InteractionResponseType::UpdateMessage,
data: Some(data),
};
let client = ctx.interaction();
client
.create_response(component.id, &component.token, &response)
.exec()
.await?;
Ok(())
}
pub async fn handle_bg_start_include(
ctx: &Context,
mut component: MessageComponentInteraction,
) -> BotResult<()> {
match ctx.bg_games().entry(component.channel_id) {
Entry::Occupied(mut entry) => match entry.get_mut() {
BgGameState::Running { .. } => {
if let Err(err) = remove_components(ctx, &component, None).await {
let report = Report::new(err).wrap_err("failed to remove components");
warn!("{report:?}");
}
}
BgGameState::Setup {
author, included, ..
} => {
if *author != component.user_id()? {
return Ok(());
}
*included = parse_component_tags(&component);
update_field(ctx, &mut component, *included, "Included tags").await?;
}
},
Entry::Vacant(_) => {
if let Err(err) = remove_components(ctx, &component, None).await {
let report = Report::new(err).wrap_err("failed to remove components");
warn!("{report:?}");
}
}
}
Ok(())
}
pub async fn handle_bg_start_exclude(
ctx: &Context,
mut component: MessageComponentInteraction,
) -> BotResult<()> {
match ctx.bg_games().entry(component.channel_id) {
Entry::Occupied(mut entry) => match entry.get_mut() {
BgGameState::Running { .. } => {
if let Err(err) = remove_components(ctx, &component, None).await {
let report = Report::new(err).wrap_err("failed to remove components");
warn!("{report:?}");
}
}
BgGameState::Setup {
author, excluded, ..
} => {
if *author != component.user_id()? {
return Ok(());
}
*excluded = parse_component_tags(&component);
update_field(ctx, &mut component, *excluded, "Excluded tags").await?;
}
},
Entry::Vacant(_) => {
if let Err(err) = remove_components(ctx, &component, None).await {
let report = Report::new(err).wrap_err("failed to remove components");
warn!("{report:?}");
}
}
}
Ok(())
}
pub async fn handle_bg_start_button(
ctx: Arc<Context>,
component: MessageComponentInteraction,
) -> BotResult<()> {
let channel = component.channel_id;
match ctx.bg_games().entry(channel) {
Entry::Occupied(mut entry) => match entry.get() {
BgGameState::Running { .. } => {
if let Err(err) = remove_components(&ctx, &component, None).await {
let report = Report::new(err).wrap_err("failed to remove components");
warn!("{report:?}");
}
}
BgGameState::Setup {
author,
difficulty,
effects,
excluded,
included,
} => {
if *author != component.user_id()? {
return Ok(());
}
let mapset_fut =
ctx.psql()
.get_specific_tags_mapset(GameMode::STD, *included, *excluded);
let mapsets = match mapset_fut.await {
Ok(mapsets) => mapsets,
Err(err) => {
let embed = EmbedBuilder::new()
.color(RED)
.description(GENERAL_ISSUE)
.build();
if let Err(err) = remove_components(&ctx, &component, Some(embed)).await {
let report = Report::new(err).wrap_err("failed to remove components");
warn!("{report:?}");
}
return Err(err);
}
};
let embed =
BGTagsEmbed::new(*included, *excluded, mapsets.len(), *effects, *difficulty)
.into_builder()
.build();
if let Err(err) = remove_components(&ctx, &component, Some(embed)).await {
let report = Report::new(err).wrap_err("failed to remove components");
warn!("{report:?}");
}
if mapsets.is_empty() {
entry.remove();
return Ok(());
}
info!(
"Starting game with included: {} - excluded: {}",
included.join(','),
excluded.join(',')
);
let game =
GameWrapper::new(Arc::clone(&ctx), channel, mapsets, *effects, *difficulty)
.await;
entry.insert(BgGameState::Running { game });
}
},
Entry::Vacant(_) => {
if let Err(err) = remove_components(&ctx, &component, None).await {
let report = Report::new(err).wrap_err("failed to remove components");
warn!("{report:?}");
}
}
}
Ok(())
}
pub async fn handle_bg_start_cancel(
ctx: &Context,
component: MessageComponentInteraction,
) -> BotResult<()> {
let channel = component.channel_id;
match ctx.bg_games().entry(channel) {
Entry::Occupied(entry) => match entry.get() {
BgGameState::Running { .. } => {
if let Err(err) = remove_components(ctx, &component, None).await {
let report = Report::new(err).wrap_err("failed to remove components");
warn!("{report:?}");
}
return Ok(());
}
BgGameState::Setup { author, .. } => {
if *author != component.user_id()? {
return Ok(());
}
let embed = EmbedBuilder::new()
.description("Aborted background game setup")
.build();
entry.remove();
remove_components(ctx, &component, Some(embed)).await?;
}
},
Entry::Vacant(_) => {
if let Err(err) = remove_components(ctx, &component, None).await {
let report = Report::new(err).wrap_err("failed to remove components");
warn!("{report:?}");
}
}
}
Ok(())
}
pub async fn handle_bg_start_effects(
ctx: &Context,
mut component: MessageComponentInteraction,
) -> BotResult<()> {
match ctx.bg_games().entry(component.channel_id) {
Entry::Occupied(mut entry) => match entry.get_mut() {
BgGameState::Running { .. } => {
if let Err(err) = remove_components(ctx, &component, None).await {
let report = Report::new(err).wrap_err("failed to remove components");
warn!("{report:?}");
}
}
BgGameState::Setup {
author, effects, ..
} => {
if *author != component.user_id()? {
return Ok(());
}
*effects = component
.data
.values
.iter()
.fold(Effects::empty(), |effects, value| {
effects
| match value.as_str() {
"blur" => Effects::Blur,
"contrast" => Effects::Contrast,
"flip_h" => Effects::FlipHorizontal,
"flip_v" => Effects::FlipVertical,
"grayscale" => Effects::Grayscale,
"invert" => Effects::Invert,
_ => {
warn!("unknown effects `{value}`");
return effects;
}
}
});
let mut embed = component
.message
.embeds
.pop()
.ok_or(InvalidBgState::MissingEmbed)?;
let field_opt = embed
.fields
.iter_mut()
.find(|field| field.name == "Effects");
if let Some(field) = field_opt {
field.value = effects.join(", ");
} else {
let field = EmbedField {
inline: false,
name: "Effects".to_owned(),
value: effects.join(", "),
};
embed.fields.push(field);
}
let data = InteractionResponseData {
embeds: Some(vec![embed]),
..Default::default()
};
let response = InteractionResponse {
kind: InteractionResponseType::UpdateMessage,
data: Some(data),
};
let client = ctx.interaction();
client
.create_response(component.id, &component.token, &response)
.exec()
.await?;
}
},
Entry::Vacant(_) => {
if let Err(err) = remove_components(ctx, &component, None).await {
let report = Report::new(err).wrap_err("failed to remove components");
warn!("{report:?}");
}
}
}
Ok(())
}
async fn remove_components(
ctx: &Context,
component: &MessageComponentInteraction,
embed: Option<Embed>,
) -> BotResult<()> {
let data = InteractionResponseData {
components: Some(Vec::new()),
embeds: embed.map(|e| vec![e]),
..Default::default()
};
let response = InteractionResponse {
kind: InteractionResponseType::UpdateMessage,
data: Some(data),
};
let client = ctx.interaction();
client
.create_response(component.id, &component.token, &response)
.exec()
.await?;
Ok(())
}
fn bg_components() -> Vec<Component> {
let options = vec![
SelectMenuOption {
default: false,
description: None,
emoji: None,
label: "Easy".to_owned(),
value: "easy".to_owned(),
},
SelectMenuOption {
default: false,
description: None,
emoji: None,
label: "Hard".to_owned(),
value: "hard".to_owned(),
},
SelectMenuOption {
default: false,
description: None,
emoji: None,
label: "Meme".to_owned(),
value: "meme".to_owned(),
},
SelectMenuOption {
default: false,
description: None,
emoji: None,
label: "Weeb".to_owned(),
value: "weeb".to_owned(),
},
SelectMenuOption {
default: false,
description: None,
emoji: None,
label: "K-Pop".to_owned(),
value: "kpop".to_owned(),
},
SelectMenuOption {
default: false,
description: None,
emoji: None,
label: "Farm".to_owned(),
value: "farm".to_owned(),
},
SelectMenuOption {
default: false,
description: None,
emoji: None,
label: "Hard name".to_owned(),
value: "hardname".to_owned(),
},
SelectMenuOption {
default: false,
description: None,
emoji: None,
label: "Alternate".to_owned(),
value: "alt".to_owned(),
},
SelectMenuOption {
default: false,
description: None,
emoji: None,
label: "Blue sky".to_owned(),
value: "bluesky".to_owned(),
},
SelectMenuOption {
default: false,
description: None,
emoji: None,
label: "English".to_owned(),
value: "english".to_owned(),
},
SelectMenuOption {
default: false,
description: None,
emoji: None,
label: "Streams".to_owned(),
value: "streams".to_owned(),
},
SelectMenuOption {
default: false,
description: None,
emoji: None,
label: "Old".to_owned(),
value: "old".to_owned(),
},
SelectMenuOption {
default: false,
description: None,
emoji: None,
label: "Tech".to_owned(),
value: "tech".to_owned(),
},
];
let include_menu = SelectMenu {
custom_id: "bg_start_include".to_owned(),
disabled: false,
max_values: Some(options.len() as u8),
min_values: Some(0),
options: options.clone(),
placeholder: Some("Select which tags should be included".to_owned()),
};
let include_row = ActionRow {
components: vec![Component::SelectMenu(include_menu)],
};
let exclude_menu = SelectMenu {
custom_id: "bg_start_exclude".to_owned(),
disabled: false,
max_values: Some(options.len() as u8),
min_values: Some(0),
options,
placeholder: Some("Select which tags should be excluded".to_owned()),
};
let exclude_row = ActionRow {
components: vec![Component::SelectMenu(exclude_menu)],
};
let start_button = Button {
custom_id: Some("bg_start_button".to_owned()),
disabled: false,
emoji: None,
label: Some("Start".to_owned()),
style: ButtonStyle::Success,
url: None,
};
let cancel_button = Button {
custom_id: Some("bg_start_cancel".to_owned()),
disabled: false,
emoji: None,
label: Some("Cancel".to_owned()),
style: ButtonStyle::Danger,
url: None,
};
let button_row = ActionRow {
components: vec![
Component::Button(start_button),
Component::Button(cancel_button),
],
};
let effects = vec![
SelectMenuOption {
default: false,
description: Some("Blur the image".to_owned()),
emoji: None,
label: "blur".to_owned(),
value: "blur".to_owned(),
},
SelectMenuOption {
default: false,
description: Some("Increase the color contrast".to_owned()),
emoji: None,
label: "Contrast".to_owned(),
value: "contrast".to_owned(),
},
SelectMenuOption {
default: false,
description: Some("Flip the image horizontally".to_owned()),
emoji: None,
label: "Flip horizontal".to_owned(),
value: "flip_h".to_owned(),
},
SelectMenuOption {
default: false,
description: Some("Flip the image vertically".to_owned()),
emoji: None,
label: "Flip vertical".to_owned(),
value: "flip_v".to_owned(),
},
SelectMenuOption {
default: false,
description: Some("Grayscale the colors".to_owned()),
emoji: None,
label: "Grayscale".to_owned(),
value: "grayscale".to_owned(),
},
SelectMenuOption {
default: false,
description: Some("Invert the colors".to_owned()),
emoji: None,
label: "Invert".to_owned(),
value: "invert".to_owned(),
},
];
let effects_menu = SelectMenu {
custom_id: "bg_start_effects".to_owned(),
disabled: false,
max_values: Some(effects.len() as u8),
min_values: Some(0),
options: effects,
placeholder: Some("Modify images through effects".to_owned()),
};
let effects_row = ActionRow {
components: vec![Component::SelectMenu(effects_menu)],
};
vec![
Component::ActionRow(include_row),
Component::ActionRow(exclude_row),
Component::ActionRow(effects_row),
Component::ActionRow(button_row),
]
}
pub async fn slash_bg(ctx: Arc<Context>, command: ApplicationCommand) -> BotResult<()> {
if let Some((_, BgGameState::Running { game })) = ctx.bg_games().remove(&command.channel_id) {
if let Err(err) = game.stop() {
let report = Report::new(err).wrap_err("failed to stop game");
warn!("{report:?}");
}
}
let mut mode = None;
let mut difficulty = None;
for option in &command.data.options {
match option.value {
CommandOptionValue::String(ref value) => match option.name.as_str() {
"difficulty" => match value.as_str() {
"normal" => difficulty = Some(GameDifficulty::Normal),
"hard" => difficulty = Some(GameDifficulty::Hard),
"impossible" => difficulty = Some(GameDifficulty::Impossible),
_ => return Err(Error::InvalidCommandOptions),
},
MODE => mode = parse_mode_option(value),
_ => return Err(Error::InvalidCommandOptions),
},
_ => return Err(Error::InvalidCommandOptions),
}
}
let difficulty = difficulty.unwrap_or_default();
let state = match mode {
Some(GameMode::STD) | None => {
let components = bg_components();
let author = command.user_id()?;
let content = format!(
"<@{author}> select which tags should be included \
and which ones should be excluded, then start the game.\n\
Only you can use the components below.",
);
let builder = MessageBuilder::new().embed(content).components(&components);
command.create_message(&ctx, builder).await?;
BgGameState::Setup {
author,
difficulty,
effects: Effects::empty(),
excluded: MapsetTags::empty(),
included: MapsetTags::empty(),
}
}
Some(GameMode::MNA) => {
let mapsets = match ctx.psql().get_all_tags_mapset(GameMode::MNA).await {
Ok(mapsets) => mapsets,
Err(err) => {
let _ = command.error(&ctx, GENERAL_ISSUE).await;
return Err(err);
}
};
let content = format!(
"Starting mania background guessing game with {} different backgrounds",
mapsets.len()
);
let builder = MessageBuilder::new().embed(content);
command.create_message(&ctx, builder).await?;
let game_fut = GameWrapper::new(
Arc::clone(&ctx),
command.channel_id,
mapsets,
Effects::empty(),
difficulty,
);
BgGameState::Running {
game: game_fut.await,
}
}
Some(GameMode::TKO | GameMode::CTB) => unreachable!(),
};
ctx.bg_games().insert(command.channel_id, state);
Ok(())
}
pub fn define_bg() -> MyCommand {
let mode_choices = vec![
CommandOptionChoice::String {
name: OSU.to_owned(),
value: OSU.to_owned(),
},
CommandOptionChoice::String {
name: MANIA.to_owned(),
value: MANIA.to_owned(),
},
];
let mode = MyCommandOption::builder(MODE, SPECIFY_MODE).string(mode_choices, false);
let difficulty_choices = vec![
CommandOptionChoice::String {
name: "Normal".to_owned(),
value: "normal".to_owned(),
},
CommandOptionChoice::String {
name: "Hard".to_owned(),
value: "hard".to_owned(),
},
CommandOptionChoice::String {
name: "Impossible".to_owned(),
value: "impossible".to_owned(),
},
];
let difficulty_description = "Increase difficulty by requiring better guessing";
let difficulty_help = "Increase the difficulty.\n\
The higher the difficulty, the more accurate guesses have to be in order to be accepted.";
let difficulty = MyCommandOption::builder("difficulty", difficulty_description)
.help(difficulty_help)
.string(difficulty_choices, false);
let description = "Start a new background guessing game";
let help = "Start a new background guessing game.\n\
Given part of a map's background, try to guess the **title** of the map's song.\n\
You don't need to guess content in parentheses `(...)` or content after `ft.` or `feat.`.\n\n\
Use these prefix commands to initiate with the game:\n\
• `<bg s[kip]` / `<bg r[esolve]`: Resolve the current background and \
give a new one with the same tag specs.\n\
• `<bg h[int]`: Receive a hint (can be used multiple times).\n\
• `<bg b[igger]`: Increase the radius of the displayed image (can be used multiple times).\n\
• `<bg stop`: Resolve the current background and stop the game.
• `<bg l[eaderboard] s[erver]`: Check out the global leaderboard for \
amount of correct guesses. If `server` or `s` is added at the end, \
I will only show members of this server.";
MyCommand::new("bg", description)
.help(help)
.options(vec![mode, difficulty])
}
|
#[doc = "Register `AHBSMENR` reader"]
pub type R = crate::R<AHBSMENR_SPEC>;
#[doc = "Register `AHBSMENR` writer"]
pub type W = crate::W<AHBSMENR_SPEC>;
#[doc = "Field `DMASMEN` reader - DMA clock enable during sleep mode bit"]
pub type DMASMEN_R = crate::BitReader<DMASMEN_A>;
#[doc = "DMA clock enable during sleep mode bit\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DMASMEN_A {
#[doc = "0: DMA clock disabled in Sleep mode"]
Disabled = 0,
#[doc = "1: DMA clock enabled in Sleep mode"]
Enabled = 1,
}
impl From<DMASMEN_A> for bool {
#[inline(always)]
fn from(variant: DMASMEN_A) -> Self {
variant as u8 != 0
}
}
impl DMASMEN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> DMASMEN_A {
match self.bits {
false => DMASMEN_A::Disabled,
true => DMASMEN_A::Enabled,
}
}
#[doc = "DMA clock disabled in Sleep mode"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == DMASMEN_A::Disabled
}
#[doc = "DMA clock enabled in Sleep mode"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == DMASMEN_A::Enabled
}
}
#[doc = "Field `DMASMEN` writer - DMA clock enable during sleep mode bit"]
pub type DMASMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, DMASMEN_A>;
impl<'a, REG, const O: u8> DMASMEN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "DMA clock disabled in Sleep mode"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(DMASMEN_A::Disabled)
}
#[doc = "DMA clock enabled in Sleep mode"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(DMASMEN_A::Enabled)
}
}
#[doc = "Field `MIFSMEN` reader - NVM interface clock enable during sleep mode bit"]
pub type MIFSMEN_R = crate::BitReader<MIFSMEN_A>;
#[doc = "NVM interface clock enable during sleep mode bit\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MIFSMEN_A {
#[doc = "0: NVM interface clock disabled in Sleep mode"]
Disabled = 0,
#[doc = "1: NVM interface clock enabled in Sleep mode"]
Enabled = 1,
}
impl From<MIFSMEN_A> for bool {
#[inline(always)]
fn from(variant: MIFSMEN_A) -> Self {
variant as u8 != 0
}
}
impl MIFSMEN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> MIFSMEN_A {
match self.bits {
false => MIFSMEN_A::Disabled,
true => MIFSMEN_A::Enabled,
}
}
#[doc = "NVM interface clock disabled in Sleep mode"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == MIFSMEN_A::Disabled
}
#[doc = "NVM interface clock enabled in Sleep mode"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == MIFSMEN_A::Enabled
}
}
#[doc = "Field `MIFSMEN` writer - NVM interface clock enable during sleep mode bit"]
pub type MIFSMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, MIFSMEN_A>;
impl<'a, REG, const O: u8> MIFSMEN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "NVM interface clock disabled in Sleep mode"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(MIFSMEN_A::Disabled)
}
#[doc = "NVM interface clock enabled in Sleep mode"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(MIFSMEN_A::Enabled)
}
}
#[doc = "Field `SRAMSMEN` reader - SRAM interface clock enable during sleep mode bit"]
pub type SRAMSMEN_R = crate::BitReader<SRAMSMEN_A>;
#[doc = "SRAM interface clock enable during sleep mode bit\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SRAMSMEN_A {
#[doc = "0: NVM interface clock disabled in Sleep mode"]
Disabled = 0,
#[doc = "1: NVM interface clock enabled in Sleep mode"]
Enabled = 1,
}
impl From<SRAMSMEN_A> for bool {
#[inline(always)]
fn from(variant: SRAMSMEN_A) -> Self {
variant as u8 != 0
}
}
impl SRAMSMEN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> SRAMSMEN_A {
match self.bits {
false => SRAMSMEN_A::Disabled,
true => SRAMSMEN_A::Enabled,
}
}
#[doc = "NVM interface clock disabled in Sleep mode"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == SRAMSMEN_A::Disabled
}
#[doc = "NVM interface clock enabled in Sleep mode"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == SRAMSMEN_A::Enabled
}
}
#[doc = "Field `SRAMSMEN` writer - SRAM interface clock enable during sleep mode bit"]
pub type SRAMSMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, SRAMSMEN_A>;
impl<'a, REG, const O: u8> SRAMSMEN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "NVM interface clock disabled in Sleep mode"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(SRAMSMEN_A::Disabled)
}
#[doc = "NVM interface clock enabled in Sleep mode"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(SRAMSMEN_A::Enabled)
}
}
#[doc = "Field `CRCSMEN` reader - CRC clock enable during sleep mode bit"]
pub type CRCSMEN_R = crate::BitReader<CRCSMEN_A>;
#[doc = "CRC clock enable during sleep mode bit\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CRCSMEN_A {
#[doc = "0: Test integration module clock disabled in Sleep mode"]
Disabled = 0,
#[doc = "1: Test integration module clock enabled in Sleep mode (if enabled by CRCEN)"]
Enabled = 1,
}
impl From<CRCSMEN_A> for bool {
#[inline(always)]
fn from(variant: CRCSMEN_A) -> Self {
variant as u8 != 0
}
}
impl CRCSMEN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> CRCSMEN_A {
match self.bits {
false => CRCSMEN_A::Disabled,
true => CRCSMEN_A::Enabled,
}
}
#[doc = "Test integration module clock disabled in Sleep mode"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == CRCSMEN_A::Disabled
}
#[doc = "Test integration module clock enabled in Sleep mode (if enabled by CRCEN)"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == CRCSMEN_A::Enabled
}
}
#[doc = "Field `CRCSMEN` writer - CRC clock enable during sleep mode bit"]
pub type CRCSMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, CRCSMEN_A>;
impl<'a, REG, const O: u8> CRCSMEN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Test integration module clock disabled in Sleep mode"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(CRCSMEN_A::Disabled)
}
#[doc = "Test integration module clock enabled in Sleep mode (if enabled by CRCEN)"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(CRCSMEN_A::Enabled)
}
}
impl R {
#[doc = "Bit 0 - DMA clock enable during sleep mode bit"]
#[inline(always)]
pub fn dmasmen(&self) -> DMASMEN_R {
DMASMEN_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 8 - NVM interface clock enable during sleep mode bit"]
#[inline(always)]
pub fn mifsmen(&self) -> MIFSMEN_R {
MIFSMEN_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - SRAM interface clock enable during sleep mode bit"]
#[inline(always)]
pub fn sramsmen(&self) -> SRAMSMEN_R {
SRAMSMEN_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 12 - CRC clock enable during sleep mode bit"]
#[inline(always)]
pub fn crcsmen(&self) -> CRCSMEN_R {
CRCSMEN_R::new(((self.bits >> 12) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - DMA clock enable during sleep mode bit"]
#[inline(always)]
#[must_use]
pub fn dmasmen(&mut self) -> DMASMEN_W<AHBSMENR_SPEC, 0> {
DMASMEN_W::new(self)
}
#[doc = "Bit 8 - NVM interface clock enable during sleep mode bit"]
#[inline(always)]
#[must_use]
pub fn mifsmen(&mut self) -> MIFSMEN_W<AHBSMENR_SPEC, 8> {
MIFSMEN_W::new(self)
}
#[doc = "Bit 9 - SRAM interface clock enable during sleep mode bit"]
#[inline(always)]
#[must_use]
pub fn sramsmen(&mut self) -> SRAMSMEN_W<AHBSMENR_SPEC, 9> {
SRAMSMEN_W::new(self)
}
#[doc = "Bit 12 - CRC clock enable during sleep mode bit"]
#[inline(always)]
#[must_use]
pub fn crcsmen(&mut self) -> CRCSMEN_W<AHBSMENR_SPEC, 12> {
CRCSMEN_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 = "AHB peripheral clock enable in sleep mode register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ahbsmenr::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 [`ahbsmenr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct AHBSMENR_SPEC;
impl crate::RegisterSpec for AHBSMENR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`ahbsmenr::R`](R) reader structure"]
impl crate::Readable for AHBSMENR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`ahbsmenr::W`](W) writer structure"]
impl crate::Writable for AHBSMENR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets AHBSMENR to value 0x0111_1301"]
impl crate::Resettable for AHBSMENR_SPEC {
const RESET_VALUE: Self::Ux = 0x0111_1301;
}
|
use serde::{Serialize, Deserialize};
#[derive(Debug, Serialize)]
pub struct ViewerServerMsg {
pub msg_type: ViewerServerType,
}
#[derive(Debug, Serialize)]
pub enum ViewerServerType {
Info(Info),
GameEnded,
GameOpened,
GameClosed,
TurnAdvanced,
NewOffsets(Offsets),
NewScores(Vec<(String, f64)>),
NewParticipant(Participant),
KickedParticipant(String),
Ping,
ServerKicked,
Winners(Vec<Option<(Vec<String>, f64)>>)
}
#[derive(Debug, Deserialize)]
pub enum ViewerClientType {
Pong,
}
#[derive(Debug, Deserialize)]
pub struct ViewerClientMsg {
pub msg_type: ViewerClientType,
}
#[derive(Debug, Serialize, Clone)]
pub struct Info {
pub participants: Vec<Participant>,
pub turn: u64,
pub game_id: String,
pub is_open: bool,
pub trending: u8,
pub subsidies: u8,
pub supply_shock: u8,
}
#[derive(Debug, Serialize, Clone)]
pub struct Offsets {
pub trending: u8,
pub subsidies: u8,
pub supply_shock: u8,
}
#[derive(Debug, Serialize, Clone)]
pub struct Participant {
pub name: String,
pub is_consumer: bool,
pub score: f64,
pub next_index: usize,
}
|
fn foo() {
let a = "hello
world";
let b = "hello\
world";
let c = r#"
hello
world
"#;
}
|
use ring;
use std::io::Write;
use crate::msgs::codec;
use crate::msgs::codec::Codec;
use crate::msgs::enums::{ContentType, ProtocolVersion};
use crate::msgs::message::{BorrowMessage, Message, MessagePayload};
use crate::msgs::fragmenter::MAX_FRAGMENT_LEN;
use crate::error::TLSError;
use crate::session::SessionSecrets;
use crate::suites::{SupportedCipherSuite, BulkAlgorithm};
use crate::key_schedule::{derive_traffic_key, derive_traffic_iv};
// accum[i] ^= offset[i] for all i in 0..len(accum)
fn xor(accum: &mut [u8], offset: &[u8]) {
for i in 0..accum.len() {
accum[i] ^= offset[i];
}
}
/// Objects with this trait can decrypt TLS messages.
pub trait MessageDecrypter : Send + Sync {
fn decrypt(&self, m: Message, seq: u64) -> Result<Message, TLSError>;
}
/// Objects with this trait can encrypt TLS messages.
pub trait MessageEncrypter : Send + Sync {
fn encrypt(&self, m: BorrowMessage, seq: u64) -> Result<Message, TLSError>;
}
impl dyn MessageEncrypter {
pub fn invalid() -> Box<dyn MessageEncrypter> {
Box::new(InvalidMessageEncrypter {})
}
}
impl dyn MessageDecrypter {
pub fn invalid() -> Box<dyn MessageDecrypter> {
Box::new(InvalidMessageDecrypter {})
}
}
pub type MessageCipherPair = (Box<dyn MessageDecrypter>, Box<dyn MessageEncrypter>);
const TLS12_AAD_SIZE: usize = 8 + 1 + 2 + 2;
fn make_tls12_aad(seq: u64,
typ: ContentType,
vers: ProtocolVersion,
len: usize,
out: &mut [u8]) {
codec::put_u64(seq, &mut out[0..]);
out[8] = typ.get_u8();
codec::put_u16(vers.get_u16(), &mut out[9..]);
codec::put_u16(len as u16, &mut out[11..]);
}
/// Make a `MessageCipherPair` based on the given supported ciphersuite `scs`,
/// and the session's `secrets`.
pub fn new_tls12(scs: &'static SupportedCipherSuite,
secrets: &SessionSecrets)
-> MessageCipherPair {
// Make a key block, and chop it up.
// nb. we don't implement any ciphersuites with nonzero mac_key_len.
let key_block = secrets.make_key_block(scs.key_block_len());
let mut offs = 0;
let client_write_key = &key_block[offs..offs + scs.enc_key_len];
offs += scs.enc_key_len;
let server_write_key = &key_block[offs..offs + scs.enc_key_len];
offs += scs.enc_key_len;
let client_write_iv = &key_block[offs..offs + scs.fixed_iv_len];
offs += scs.fixed_iv_len;
let server_write_iv = &key_block[offs..offs + scs.fixed_iv_len];
offs += scs.fixed_iv_len;
let explicit_nonce_offs = &key_block[offs..offs + scs.explicit_nonce_len];
let (write_key, write_iv) = if secrets.randoms.we_are_client {
(client_write_key, client_write_iv)
} else {
(server_write_key, server_write_iv)
};
let (read_key, read_iv) = if secrets.randoms.we_are_client {
(server_write_key, server_write_iv)
} else {
(client_write_key, client_write_iv)
};
let aead_alg = scs.get_aead_alg();
match scs.bulk {
BulkAlgorithm::AES_128_GCM |
BulkAlgorithm::AES_256_GCM => {
(Box::new(GCMMessageDecrypter::new(aead_alg,
read_key,
read_iv)),
Box::new(GCMMessageEncrypter::new(aead_alg,
write_key,
write_iv,
explicit_nonce_offs)))
}
BulkAlgorithm::CHACHA20_POLY1305 => {
(Box::new(ChaCha20Poly1305MessageDecrypter::new(aead_alg,
read_key,
read_iv)),
Box::new(ChaCha20Poly1305MessageEncrypter::new(aead_alg,
write_key,
write_iv)))
}
}
}
pub fn new_tls13_read(scs: &'static SupportedCipherSuite,
secret: &[u8]) -> Box<dyn MessageDecrypter> {
let hash = scs.get_hash();
let key = derive_traffic_key(hash, secret, scs.enc_key_len);
let iv = derive_traffic_iv(hash, secret, scs.fixed_iv_len);
let aead_alg = scs.get_aead_alg();
Box::new(TLS13MessageDecrypter::new(aead_alg, &key, &iv))
}
pub fn new_tls13_write(scs: &'static SupportedCipherSuite,
secret: &[u8]) -> Box<dyn MessageEncrypter> {
let hash = scs.get_hash();
let key = derive_traffic_key(hash, secret, scs.enc_key_len);
let iv = derive_traffic_iv(hash, secret, scs.fixed_iv_len);
let aead_alg = scs.get_aead_alg();
Box::new(TLS13MessageEncrypter::new(aead_alg, &key, &iv))
}
/// A `MessageEncrypter` for AES-GCM AEAD ciphersuites. TLS 1.2 only.
pub struct GCMMessageEncrypter {
alg: &'static ring::aead::Algorithm,
enc_key: ring::aead::SealingKey,
enc_salt: [u8; 4],
nonce_offset: [u8; 8],
}
/// A `MessageDecrypter` for AES-GCM AEAD ciphersuites. TLS1.2 only.
pub struct GCMMessageDecrypter {
dec_key: ring::aead::OpeningKey,
dec_salt: [u8; 4],
}
const GCM_EXPLICIT_NONCE_LEN: usize = 8;
const GCM_OVERHEAD: usize = GCM_EXPLICIT_NONCE_LEN + 16;
impl MessageDecrypter for GCMMessageDecrypter {
fn decrypt(&self, mut msg: Message, seq: u64) -> Result<Message, TLSError> {
let payload = msg.take_opaque_payload()
.ok_or(TLSError::DecryptError)?;
let mut buf = payload.0;
if buf.len() < GCM_OVERHEAD {
return Err(TLSError::DecryptError);
}
let nonce = {
let mut nonce = [0u8; 12];
nonce.as_mut().write_all(&self.dec_salt).unwrap();
nonce[4..].as_mut().write_all(&buf[..8]).unwrap();
ring::aead::Nonce::assume_unique_for_key(nonce)
};
let mut aad = [0u8; TLS12_AAD_SIZE];
make_tls12_aad(seq, msg.typ, msg.version, buf.len() - GCM_OVERHEAD, &mut aad);
let aad = ring::aead::Aad::from(&aad);
let plain_len = ring::aead::open_in_place(&self.dec_key,
nonce,
aad,
GCM_EXPLICIT_NONCE_LEN,
&mut buf)
.map_err(|_| TLSError::DecryptError)?
.len();
if plain_len > MAX_FRAGMENT_LEN {
return Err(TLSError::PeerSentOversizedRecord);
}
buf.truncate(plain_len);
Ok(Message {
typ: msg.typ,
version: msg.version,
payload: MessagePayload::new_opaque(buf),
})
}
}
impl MessageEncrypter for GCMMessageEncrypter {
fn encrypt(&self, msg: BorrowMessage, seq: u64) -> Result<Message, TLSError> {
// The GCM nonce is constructed from a 32-bit 'salt' derived
// from the master-secret, and a 64-bit explicit part,
// with no specified construction. Thanks for that.
//
// We use the same construction as TLS1.3/ChaCha20Poly1305:
// a starting point extracted from the key block, xored with
// the sequence number.
//
let nonce = {
let mut nonce = [0u8; 12];
nonce.as_mut().write_all(&self.enc_salt).unwrap();
codec::put_u64(seq, &mut nonce[4..]);
xor(&mut nonce[4..], &self.nonce_offset);
ring::aead::Nonce::assume_unique_for_key(nonce)
};
// make output buffer with room for nonce/tag
let tag_len = self.alg.tag_len();
let total_len = 8 + msg.payload.len() + tag_len;
let mut buf = Vec::with_capacity(total_len);
buf.extend_from_slice(&nonce.as_ref()[4..]);
buf.extend_from_slice(msg.payload);
buf.resize(total_len, 0u8);
let mut aad = [0u8; TLS12_AAD_SIZE];
make_tls12_aad(seq, msg.typ, msg.version, msg.payload.len(), &mut aad);
let aad = ring::aead::Aad::from(&aad);
ring::aead::seal_in_place(&self.enc_key, nonce, aad, &mut buf[8..], tag_len)
.map_err(|_| TLSError::General("encrypt failed".to_string()))?;
Ok(Message {
typ: msg.typ,
version: msg.version,
payload: MessagePayload::new_opaque(buf),
})
}
}
impl GCMMessageEncrypter {
fn new(alg: &'static ring::aead::Algorithm,
enc_key: &[u8],
enc_iv: &[u8],
nonce_offset: &[u8])
-> GCMMessageEncrypter {
let mut ret = GCMMessageEncrypter {
alg,
enc_key: ring::aead::SealingKey::new(alg, enc_key).unwrap(),
enc_salt: [0u8; 4],
nonce_offset: [0u8; 8],
};
debug_assert_eq!(enc_iv.len(), 4);
debug_assert_eq!(nonce_offset.len(), 8);
ret.enc_salt.as_mut().write_all(enc_iv).unwrap();
ret.nonce_offset.as_mut().write_all(nonce_offset).unwrap();
ret
}
}
impl GCMMessageDecrypter {
fn new(alg: &'static ring::aead::Algorithm,
dec_key: &[u8],
dec_iv: &[u8]) -> GCMMessageDecrypter {
let mut ret = GCMMessageDecrypter {
dec_key: ring::aead::OpeningKey::new(alg, dec_key).unwrap(),
dec_salt: [0u8; 4],
};
debug_assert_eq!(dec_iv.len(), 4);
ret.dec_salt.as_mut().write_all(dec_iv).unwrap();
ret
}
}
struct TLS13MessageEncrypter {
alg: &'static ring::aead::Algorithm,
enc_key: ring::aead::SealingKey,
enc_offset: [u8; 12],
}
struct TLS13MessageDecrypter {
alg: &'static ring::aead::Algorithm,
dec_key: ring::aead::OpeningKey,
dec_offset: [u8; 12],
}
fn unpad_tls13(v: &mut Vec<u8>) -> ContentType {
loop {
match v.pop() {
Some(0) => {}
Some(content_type) => return ContentType::read_bytes(&[content_type]).unwrap(),
None => return ContentType::Unknown(0),
}
}
}
const TLS13_AAD_SIZE: usize = 1 + 2 + 2;
fn make_tls13_aad(len: usize, out: &mut [u8]) {
out[0] = 0x17; // ContentType::ApplicationData
out[1] = 0x3; // ProtocolVersion (major)
out[2] = 0x3; // ProtocolVersion (minor)
out[3] = (len >> 8) as u8;
out[4] = len as u8;
}
impl MessageEncrypter for TLS13MessageEncrypter {
fn encrypt(&self, msg: BorrowMessage, seq: u64) -> Result<Message, TLSError> {
let nonce = {
let mut nonce = [0u8; 12];
codec::put_u64(seq, &mut nonce[4..]);
xor(&mut nonce, &self.enc_offset);
ring::aead::Nonce::assume_unique_for_key(nonce)
};
// make output buffer with room for content type and tag
let tag_len = self.alg.tag_len();
let total_len = msg.payload.len() + 1 + tag_len;
let mut buf = Vec::with_capacity(total_len);
buf.extend_from_slice(msg.payload);
msg.typ.encode(&mut buf);
buf.resize(total_len, 0u8);
let mut aad = [0u8; TLS13_AAD_SIZE];
make_tls13_aad(total_len, &mut aad);
ring::aead::seal_in_place(&self.enc_key, nonce, ring::aead::Aad::from(&aad), &mut buf,
tag_len)
.map_err(|_| TLSError::General("encrypt failed".to_string()))?;
Ok(Message {
typ: ContentType::ApplicationData,
version: ProtocolVersion::TLSv1_2,
payload: MessagePayload::new_opaque(buf),
})
}
}
impl MessageDecrypter for TLS13MessageDecrypter {
fn decrypt(&self, mut msg: Message, seq: u64) -> Result<Message, TLSError> {
let nonce = {
let mut nonce = [0u8; 12];
codec::put_u64(seq, &mut nonce[4..]);
xor(&mut nonce, &self.dec_offset);
ring::aead::Nonce::assume_unique_for_key(nonce)
};
let payload = msg.take_opaque_payload()
.ok_or(TLSError::DecryptError)?;
let mut buf = payload.0;
if buf.len() < self.alg.tag_len() {
return Err(TLSError::DecryptError);
}
let mut aad = [0u8; TLS13_AAD_SIZE];
make_tls13_aad(buf.len(), &mut aad);
let aad = ring::aead::Aad::from(&aad);
let plain_len = ring::aead::open_in_place(&self.dec_key, nonce, aad, 0, &mut buf)
.map_err(|_| TLSError::DecryptError)?
.len();
buf.truncate(plain_len);
if buf.len() > MAX_FRAGMENT_LEN + 1 {
return Err(TLSError::PeerSentOversizedRecord);
}
let content_type = unpad_tls13(&mut buf);
if content_type == ContentType::Unknown(0) {
let msg = "peer sent bad TLSInnerPlaintext".to_string();
return Err(TLSError::PeerMisbehavedError(msg));
}
if buf.len() > MAX_FRAGMENT_LEN {
return Err(TLSError::PeerSentOversizedRecord);
}
Ok(Message {
typ: content_type,
version: ProtocolVersion::TLSv1_3,
payload: MessagePayload::new_opaque(buf),
})
}
}
impl TLS13MessageEncrypter {
fn new(alg: &'static ring::aead::Algorithm,
enc_key: &[u8],
enc_iv: &[u8]) -> TLS13MessageEncrypter {
let mut ret = TLS13MessageEncrypter {
alg,
enc_key: ring::aead::SealingKey::new(alg, enc_key).unwrap(),
enc_offset: [0u8; 12],
};
ret.enc_offset.as_mut().write_all(enc_iv).unwrap();
ret
}
}
impl TLS13MessageDecrypter {
fn new(alg: &'static ring::aead::Algorithm,
dec_key: &[u8],
dec_iv: &[u8]) -> TLS13MessageDecrypter {
let mut ret = TLS13MessageDecrypter {
alg,
dec_key: ring::aead::OpeningKey::new(alg, dec_key).unwrap(),
dec_offset: [0u8; 12],
};
ret.dec_offset.as_mut().write_all(dec_iv).unwrap();
ret
}
}
/// The RFC7905/RFC7539 ChaCha20Poly1305 construction.
/// This implementation does the AAD construction required in TLS1.2.
/// TLS1.3 uses `TLS13MessageEncrypter`.
pub struct ChaCha20Poly1305MessageEncrypter {
alg: &'static ring::aead::Algorithm,
enc_key: ring::aead::SealingKey,
enc_offset: [u8; 12],
}
/// The RFC7905/RFC7539 ChaCha20Poly1305 construction.
/// This implementation does the AAD construction required in TLS1.2.
/// TLS1.3 uses `TLS13MessageDecrypter`.
pub struct ChaCha20Poly1305MessageDecrypter {
dec_key: ring::aead::OpeningKey,
dec_offset: [u8; 12],
}
impl ChaCha20Poly1305MessageEncrypter {
fn new(alg: &'static ring::aead::Algorithm,
enc_key: &[u8],
enc_iv: &[u8]) -> ChaCha20Poly1305MessageEncrypter {
let mut ret = ChaCha20Poly1305MessageEncrypter {
alg,
enc_key: ring::aead::SealingKey::new(alg, enc_key).unwrap(),
enc_offset: [0u8; 12],
};
ret.enc_offset.as_mut().write_all(enc_iv).unwrap();
ret
}
}
impl ChaCha20Poly1305MessageDecrypter {
fn new(alg: &'static ring::aead::Algorithm,
dec_key: &[u8],
dec_iv: &[u8]) -> ChaCha20Poly1305MessageDecrypter {
let mut ret = ChaCha20Poly1305MessageDecrypter {
dec_key: ring::aead::OpeningKey::new(alg, dec_key).unwrap(),
dec_offset: [0u8; 12],
};
ret.dec_offset.as_mut().write_all(dec_iv).unwrap();
ret
}
}
const CHACHAPOLY1305_OVERHEAD: usize = 16;
impl MessageDecrypter for ChaCha20Poly1305MessageDecrypter {
fn decrypt(&self, mut msg: Message, seq: u64) -> Result<Message, TLSError> {
let payload = msg.take_opaque_payload()
.ok_or(TLSError::DecryptError)?;
let mut buf = payload.0;
if buf.len() < CHACHAPOLY1305_OVERHEAD {
return Err(TLSError::DecryptError);
}
// Nonce is offset_96 ^ (0_32 || seq_64)
let nonce = {
let mut nonce = [0u8; 12];
codec::put_u64(seq, &mut nonce[4..]);
xor(&mut nonce, &self.dec_offset);
ring::aead::Nonce::assume_unique_for_key(nonce)
};
let mut aad = [0u8; TLS12_AAD_SIZE];
make_tls12_aad(seq, msg.typ, msg.version, buf.len() - CHACHAPOLY1305_OVERHEAD, &mut aad);
let aad = ring::aead::Aad::from(&aad);
let plain_len = ring::aead::open_in_place(&self.dec_key, nonce, aad, 0, &mut buf)
.map_err(|_| TLSError::DecryptError)?
.len();
if plain_len > MAX_FRAGMENT_LEN {
return Err(TLSError::PeerSentOversizedRecord);
}
buf.truncate(plain_len);
Ok(Message {
typ: msg.typ,
version: msg.version,
payload: MessagePayload::new_opaque(buf),
})
}
}
impl MessageEncrypter for ChaCha20Poly1305MessageEncrypter {
fn encrypt(&self, msg: BorrowMessage, seq: u64) -> Result<Message, TLSError> {
let nonce = {
let mut nonce = [0u8; 12];
codec::put_u64(seq, &mut nonce[4..]);
xor(&mut nonce, &self.enc_offset);
ring::aead::Nonce::assume_unique_for_key(nonce)
};
let mut aad = [0u8; TLS12_AAD_SIZE];
make_tls12_aad(seq, msg.typ, msg.version, msg.payload.len(), &mut aad);
let aad = ring::aead::Aad::from(&aad);
// make result buffer with room for tag, etc.
let tag_len = self.alg.tag_len();
let total_len = msg.payload.len() + tag_len;
let mut buf = Vec::with_capacity(total_len);
buf.extend_from_slice(msg.payload);
buf.resize(total_len, 0u8);
ring::aead::seal_in_place(&self.enc_key, nonce, aad, &mut buf, tag_len)
.map_err(|_| TLSError::General("encrypt failed".to_string()))?;
Ok(Message {
typ: msg.typ,
version: msg.version,
payload: MessagePayload::new_opaque(buf),
})
}
}
/// A `MessageEncrypter` which doesn't work.
pub struct InvalidMessageEncrypter {}
impl MessageEncrypter for InvalidMessageEncrypter {
fn encrypt(&self, _m: BorrowMessage, _seq: u64) -> Result<Message, TLSError> {
Err(TLSError::General("encrypt not yet available".to_string()))
}
}
/// A `MessageDecrypter` which doesn't work.
pub struct InvalidMessageDecrypter {}
impl MessageDecrypter for InvalidMessageDecrypter {
fn decrypt(&self, _m: Message, _seq: u64) -> Result<Message, TLSError> {
Err(TLSError::DecryptError)
}
}
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
use core::fmt;
use core::marker::PhantomData;
use core::ptr::NonNull;
// Only used for `IoSlice`. To be fully no_std, this should get replaced with a
// custom `IoSlice` type.
use std::io;
/// An address to some immutable memory. We don't know where the memory lives;
/// it can be either in the current process or a another process.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
#[repr(transparent)]
pub struct Addr<'a, T> {
// This is our non-null pointer. Since this may not point to memory in the
// same process, we need to be very careful to never dereference this.
inner: NonNull<T>,
_p: PhantomData<&'a T>,
}
impl<'a, T> From<usize> for Addr<'a, T> {
fn from(raw: usize) -> Self {
Self::from_raw(raw).unwrap()
}
}
impl<'a, T> Addr<'a, T> {
/// Construct an address pointing to mutable data from a raw u64. Useful for
/// converting a syscall register to a pointer.
pub fn from_raw(raw: usize) -> Option<Self> {
if raw == 0 {
None
} else {
Some(unsafe { Self::from_raw_unchecked(raw) })
}
}
/// Creates an address pointing to mutable data from a raw pointer. If the
/// pointer is null, then `None` will be returned.
pub fn from_ptr(r: *const T) -> Option<Self> {
NonNull::new(r as *mut T).map(|p| Self {
inner: p,
_p: PhantomData,
})
}
/// Construct an address from a raw u64 without checking if it is null.
///
/// # Safety
///
/// `raw` must be non-zero.
pub unsafe fn from_raw_unchecked(raw: usize) -> Self {
Self {
inner: NonNull::new_unchecked(raw as *mut T),
_p: PhantomData,
}
}
/// Casts this pointer to a mutable pointer.
///
/// # Safety
///
/// This method is unsafe for numerous reasons.
pub unsafe fn into_mut(self) -> AddrMut<'a, T> {
AddrMut {
inner: self.inner,
_p: PhantomData,
}
}
/// Returns a raw pointer.
///
/// # Safety
///
/// This method is unsafe because the pointer returned by this function
/// should never be dereferenced as it could point to memory outside of the
/// current address space.
#[allow(clippy::wrong_self_convention)]
pub unsafe fn as_ptr(self) -> *const T {
self.inner.as_ptr()
}
/// Returns the raw integer value of the address.
#[allow(clippy::wrong_self_convention)]
pub fn as_raw(self) -> usize {
self.inner.as_ptr() as usize
}
/// Casts the address into an address of another type.
pub fn cast<U>(self) -> Addr<'a, U> {
Addr {
inner: self.inner.cast(),
_p: PhantomData,
}
}
/// Returns a new address relative to the current address + `count *
/// size_of::<T>()`.
///
/// # Safety
///
/// This method is unsafe because the new address may not point to valid
/// memory.
pub unsafe fn offset(self, count: isize) -> Self {
Self {
inner: NonNull::new_unchecked(self.inner.as_ptr().offset(count)),
_p: PhantomData,
}
}
/// Returns a new address plus `count * size_of::<T>()`.
///
/// # Safety
///
/// This method is unsafe because the new address may not point to valid
/// memory.
#[allow(clippy::should_implement_trait)]
pub unsafe fn add(self, count: usize) -> Self {
self.offset(count as isize)
}
}
impl<'a, T> From<&'a T> for Addr<'a, T> {
fn from(inner: &'a T) -> Self {
Self {
inner: NonNull::from(inner),
_p: PhantomData,
}
}
}
impl<'a, T> fmt::Debug for Addr<'a, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Pointer::fmt(&self.inner, f)
}
}
impl<'a, T> fmt::Display for Addr<'a, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Pointer::fmt(&self.inner, f)
}
}
impl<'a, T> fmt::Pointer for Addr<'a, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Pointer::fmt(&self.inner, f)
}
}
/// An address to some mutable memory. We don't know where the memory lives; it
/// can be either in the current process or a another process.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
#[repr(transparent)]
pub struct AddrMut<'a, T> {
// This is our non-null pointer. Since this may not point to memory in the
// same process, we need to be very careful to never dereference this.
inner: NonNull<T>,
_p: PhantomData<&'a mut T>,
}
impl<'a, T> AddrMut<'a, T> {
/// Construct an address from a raw `usize`. Useful for converting a syscall
/// register to a pointer. If the raw value is 0, then `None` is returned.
pub fn from_raw(raw: usize) -> Option<Self> {
if raw == 0 {
None
} else {
Some(unsafe { Self::from_raw_unchecked(raw) })
}
}
/// Creates an address from a raw pointer. If the pointer is null, then
/// `None` will be returned.
pub fn from_ptr(r: *const T) -> Option<Self> {
NonNull::new(r as *mut T).map(|p| Self {
inner: p,
_p: PhantomData,
})
}
/// Construct an address from a raw u64 without checking if it is null.
///
/// # Safety
///
/// `raw` must be non-zero.
pub unsafe fn from_raw_unchecked(raw: usize) -> Self {
Self {
inner: NonNull::new_unchecked(raw as *mut T),
_p: PhantomData,
}
}
/// Returns a raw mutable pointer.
///
/// # Safety
///
/// This method is unsafe because the pointer returned by this function
/// should never be dereferenced as it could point to memory outside of the
/// current address space.
#[allow(clippy::wrong_self_convention)]
pub unsafe fn as_mut_ptr(self) -> *mut T {
self.inner.as_ptr()
}
/// Returns the raw integer value of the address.
#[allow(clippy::wrong_self_convention)]
pub fn as_raw(self) -> usize {
self.inner.as_ptr() as usize
}
/// Casts the address into an address of another type.
pub fn cast<U>(self) -> AddrMut<'a, U> {
AddrMut {
inner: self.inner.cast(),
_p: PhantomData,
}
}
/// Returns a new address relative to the current address + `count *
/// size_of::<T>()`.
///
/// # Safety
///
/// This method is unsafe because the new address may not point to valid
/// memory.
pub unsafe fn offset(self, count: isize) -> Self {
Self {
inner: NonNull::new_unchecked(self.inner.as_ptr().offset(count)),
_p: PhantomData,
}
}
/// Returns a new address plus `count * size_of::<T>()`.
///
/// # Safety
///
/// This method is unsafe because the new address may not point to valid
/// memory.
#[allow(clippy::should_implement_trait)]
pub unsafe fn add(self, count: usize) -> Self {
self.offset(count as isize)
}
}
impl<'a, T> From<AddrMut<'a, T>> for Addr<'a, T> {
fn from(addr: AddrMut<'a, T>) -> Self {
Self {
inner: addr.inner,
_p: PhantomData,
}
}
}
impl<'a, T> From<&'a T> for AddrMut<'a, T> {
fn from(inner: &'a T) -> Self {
Self {
inner: NonNull::from(inner),
_p: PhantomData,
}
}
}
impl<'a, T> fmt::Debug for AddrMut<'a, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Pointer::fmt(&self.inner, f)
}
}
impl<'a, T> fmt::Display for AddrMut<'a, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Pointer::fmt(&self.inner, f)
}
}
impl<'a, T> fmt::Pointer for AddrMut<'a, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Pointer::fmt(&self.inner, f)
}
}
unsafe impl<'a, T> Send for Addr<'a, T> where T: Send {}
unsafe impl<'a, T> Send for AddrMut<'a, T> where T: Send {}
/// A slice of some read-only memory. The memory can be in this process or in
/// another process.
#[derive(Copy, Clone)]
pub struct AddrSlice<'a, T> {
inner: &'a [T],
}
impl<'a, T> AddrSlice<'a, T> {
/// Creates the slice from its raw parts.
///
/// # Safety
///
/// This method is unsafe for the same reasons that
/// [`std::slice::from_raw_parts`] is unsafe.
pub unsafe fn from_raw_parts(addr: Addr<'a, T>, len: usize) -> Self {
Self {
inner: ::core::slice::from_raw_parts(addr.as_ptr(), len),
}
}
/// Divides one slice into two at an index. Panics if `mid > len`.
pub fn split_at(&self, mid: usize) -> (Self, Self) {
let (a, b) = self.inner.split_at(mid);
(Self { inner: a }, Self { inner: b })
}
/// Returns the number of elements in the slice.
pub fn len(&self) -> usize {
self.inner.len()
}
/// Returns true if the slice is empty.
pub fn is_empty(&self) -> bool {
self.inner.is_empty()
}
/// Splits the slice at the next page boundary if the slice spans two pages.
/// Returns `None` if the slice does not span two pages. Thus, both slices
/// are guaranteed to be non-empty.
pub fn split_at_page_boundary(&self) -> Option<(Self, Self)> {
let addr = self.inner.as_ptr() as usize;
// Get the offset to the next page. If this is larger than (or equal to)
// the length of the slice, then it's not possible to split the slice.
let offset = next_page(addr) - addr;
if offset < self.len() {
Some(self.split_at(offset))
} else {
None
}
}
}
impl<'a> AddrSlice<'a, u8> {
/// Returns an `IoSlice` representing this `AddrSlice`.
///
/// # Safety
/// This function is unsafe because it gives access to raw pointers, which
/// may not be valid for the current address space.
pub unsafe fn as_ioslice(&self) -> io::IoSlice {
io::IoSlice::new(self.inner)
}
}
/// A slice of some writable memory. The memory can be in this process or in
/// another process.
pub struct AddrSliceMut<'a, T> {
inner: &'a mut [T],
}
impl<'a, T> AddrSliceMut<'a, T> {
/// Creates the slice from its raw parts.
///
/// # Safety
///
/// This method is unsafe for the same reasons that
/// [`std::slice::from_raw_parts`] is unsafe.
pub unsafe fn from_raw_parts(addr: AddrMut<'a, T>, len: usize) -> Self {
Self {
inner: ::core::slice::from_raw_parts_mut(addr.as_mut_ptr(), len),
}
}
/// Divides one slice into two at an index.
pub fn split_at(&'a mut self, mid: usize) -> (Self, Self) {
let (a, b) = self.inner.split_at_mut(mid);
(Self { inner: a }, Self { inner: b })
}
/// Returns the number of elements in the slice.
pub fn len(&self) -> usize {
self.inner.len()
}
/// Returns true if the slice is empty.
pub fn is_empty(&self) -> bool {
self.inner.is_empty()
}
/// Splits the slice at the next page boundary if the slice spans two pages.
/// Returns `None` if the slice does not span two pages. Thus, both slices
/// are guaranteed to be non-empty.
pub fn split_at_page_boundary(&'a mut self) -> Option<(Self, Self)> {
let addr = self.inner.as_ptr() as usize;
// Get the offset to the next page. If this is larger than (or equal to)
// the length of the slice, then it's not possible to split the slice.
let offset = next_page(addr) - addr;
if offset < self.len() {
Some(self.split_at(offset))
} else {
None
}
}
}
impl<'a> AddrSliceMut<'a, u8> {
/// Returns an `IoSliceMut` representing this `AddrSliceMut`.
///
/// # Safety
/// This function is unsafe because it gives access to raw pointers, which
/// may not be valid for the current address space.
pub unsafe fn as_ioslice_mut(&mut self) -> io::IoSliceMut {
io::IoSliceMut::new(self.inner)
}
}
/// Finds the boundary for the next page. Note that this is different than simply
/// aligning an address on a page boundary.
fn next_page(addr: usize) -> usize {
const PAGE_SIZE: usize = 0x1000;
(addr + PAGE_SIZE) & (!PAGE_SIZE + 1)
}
#[cfg(test)]
mod test {
use core::mem::align_of;
use core::mem::size_of;
use super::*;
#[test]
fn test_next_page() {
assert_eq!(next_page(0x1000), 0x2000);
assert_eq!(next_page(0x1), 0x1000);
assert_eq!(next_page(0x0), 0x1000);
assert_eq!(next_page(0x1234), 0x2000);
}
#[test]
fn test_addr() {
// Ensure that we haven't perturbed the size or alignment of the
// address. We rely on the fact that it is the same size as a regular
// pointer.
assert_eq!(size_of::<Addr<u8>>(), size_of::<*const u8>());
assert_eq!(size_of::<Addr<u8>>(), size_of::<&u8>());
assert_eq!(size_of::<Option<Addr<u8>>>(), size_of::<*const u8>());
assert_eq!(size_of::<Option<Addr<u8>>>(), size_of::<&u8>());
assert_eq!(align_of::<Option<Addr<u8>>>(), align_of::<*const u8>());
assert_eq!(align_of::<Option<Addr<u8>>>(), align_of::<&u8>());
assert_eq!(Addr::<u8>::from_raw(0), None);
// Test comparison operators.
assert_eq!(
Addr::<u8>::from_raw(0xdeadbeef),
Addr::<u8>::from_raw(0xdeadbeef)
);
assert_ne!(
Addr::<u8>::from_raw(0xdeadbeef),
Addr::<u8>::from_raw(0xbaadf00d)
);
assert!(Addr::<u8>::from_raw(0x1000).unwrap() < Addr::<u8>::from_raw(0x1001).unwrap());
assert_eq!(
format!("{:p}", Addr::<u8>::from_raw(0x1000).unwrap()),
"0x1000"
);
}
#[test]
fn test_addr_slice_size() {
// Ensure that we haven't purturbed the size. We rely on the fact that
// it is the same size as a regular slice.
assert_eq!(size_of::<AddrSlice<u8>>(), size_of::<&[u8]>());
assert_eq!(size_of::<Option<AddrSlice<u8>>>(), size_of::<&[u8]>());
assert_eq!(size_of::<AddrSliceMut<u8>>(), size_of::<&mut [u8]>());
assert_eq!(
size_of::<Option<AddrSliceMut<u8>>>(),
size_of::<&mut [u8]>()
);
}
}
|
use std::io;
use std::str::FromStr;
use crate::base::Part;
pub fn part1(r: &mut dyn io::Read) -> Result<String, String> {
solve(r, Part::One)
}
pub fn part2(r: &mut dyn io::Read) -> Result<String, String> {
solve(r, Part::Two)
}
fn solve(r: &mut dyn io::Read, part: Part) -> Result<String, String> {
let mut input = String::new();
r.read_to_string(&mut input).map_err(|e| e.to_string())?;
let numbers = parse_input(input.trim());
let root = parse_tree(&numbers);
match part {
Part::One => {
let sum = root.metadata_sum();
Ok(sum.to_string())
}
Part::Two => {
let sum = root.value_sum();
Ok(sum.to_string())
}
}
}
fn parse_input(input: &str) -> Vec<u64> {
input
.split(' ')
.map(u64::from_str)
.map(Result::unwrap)
.collect()
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
struct Node {
children: Vec<Node>,
metadata: Vec<usize>,
}
impl Node {
fn metadata_sum(&self) -> usize {
let self_sum = self.metadata.iter().sum::<usize>();
let children_sum = self.children.iter().map(Node::metadata_sum).sum::<usize>();
self_sum + children_sum
}
fn value_sum(&self) -> usize {
if self.children.is_empty() {
return self.metadata_sum();
}
self.metadata
.iter()
.filter(|&&idx| idx != 0 && idx <= self.children.len())
.map(|&idx| &self.children[idx - 1])
.map(Node::value_sum)
.sum()
}
}
fn parse_tree(numbers: &[u64]) -> Node {
let (root, _remaining) = parse_tree_aux(numbers);
root
}
fn parse_tree_aux(numbers: &[u64]) -> (Node, &[u64]) {
let num_children = numbers[0] as usize;
let mut children = Vec::with_capacity(num_children);
let num_metadata = numbers[1] as usize;
let mut metadata = Vec::with_capacity(num_metadata);
let mut child_numbers = &numbers[2..];
for _ in 0..num_children {
let (child, next_child_numbers) = parse_tree_aux(child_numbers);
children.push(child);
child_numbers = next_child_numbers;
}
for &data in &child_numbers[..num_metadata] {
metadata.push(data as usize);
}
(Node { children, metadata }, &child_numbers[num_metadata..])
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test;
mod part1 {
use super::*;
test!(example, "2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2", "138", part1);
test!(actual, file "../../../inputs/2018/08", "40908", part1);
}
mod part2 {
use super::*;
test!(example, "2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2", "66", part2);
test!(actual, file "../../../inputs/2018/08", "25910", part2);
}
}
|
use chrono::{DateTime, Utc};
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize, Debug)]
pub enum ContractEvent {
Requested {
id: String,
publication_id: String,
author_id: String,
timestamp: DateTime<Utc>,
},
Approved {
id: String,
publication_id: String,
author_id: String,
content_manager_id: String,
timestamp: DateTime<Utc>,
},
Rejected {
id: String,
publication_id: String,
author_id: String,
content_manager_id: String,
timestamp: DateTime<Utc>,
},
Cancelled {
id: String,
publication_id: String,
author_id: String,
timestamp: DateTime<Utc>,
},
}
|
mod fs;
mod ws;
pub mod service;
pub mod client;
use client::Client;
use fs::FsConnection;
use log::{debug, error, warn};
use serde::Serialize;
use std::{
collections::HashMap,
net::SocketAddr,
sync::Arc,
};
use tokio::sync::RwLock;
use uuid::Uuid;
use warp::ws::{Message, WebSocket};
pub use fs::FsError;
pub use ws::{SocketConnection, WsError};
use service::Service;
/// Central struct that stores the concierge data.
pub struct Concierge {
/// This is the groups registered in the Concierge.
pub services: RwLock<HashMap<String, Service>>,
/// This is the namespace of the Concierge.
/// It uses an RwLock in order to prevent race conditions.
pub namespace: RwLock<HashMap<String, Uuid>>,
/// This is the mapping between UUID and Clients. There
/// is no lock since UUID statistically will not collide.
pub clients: RwLock<HashMap<Uuid, Client>>,
}
impl Concierge {
/// Creates a new concierge.
pub fn new() -> Self {
Self {
services: RwLock::default(),
clients: RwLock::default(),
namespace: RwLock::default(),
}
}
/// Broadcast a payload to all clients.
pub async fn broadcast(&self, payload: &impl Serialize) -> Result<(), WsError> {
let message = Message::text(serde_json::to_string(&payload)?);
for (_, client) in self.clients.read().await.iter() {
client.send_ws_msg(message.clone()).ok();
}
Ok(())
}
/// Handle new socket connections
pub async fn handle_socket_conn(self: Arc<Self>, socket: WebSocket, addr: Option<SocketAddr>) {
// Connection must have an incoming socket address
if let Some(addr) = addr {
let socket_conn = SocketConnection::new(self);
if let Err(err) = socket_conn.handle_socket_conn(socket, addr).await {
error!("WS error: {:?}", err);
}
} else {
warn!("Client joined without address.");
if let Err(err) = socket.close().await {
error!("WS failed to close: {}", err);
}
}
debug!("Socket connection (addr: {:?}) dropped.", addr)
}
pub fn fs_conn(self: Arc<Self>) -> FsConnection {
FsConnection::new(self)
}
}
|
mod secret_number;
fn main() {
}
|
#![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 PrivateAtlas {
#[serde(flatten)]
pub tracked_resource: TrackedResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<PrivateAtlasProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Creator {
#[serde(flatten)]
pub tracked_resource: TrackedResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<CreatorProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MapsAccount {
#[serde(flatten)]
pub tracked_resource: TrackedResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sku: Option<Sku>,
#[serde(rename = "systemData", default, skip_serializing_if = "Option::is_none")]
pub system_data: Option<SystemData>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<MapsAccountProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MapsAccountCreateParameters {
pub location: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
pub sku: Sku,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PrivateAtlasCreateParameters {
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 CreatorCreateParameters {
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 MapsAccountUpdateParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sku: Option<Sku>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PrivateAtlasUpdateParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CreatorUpdateParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MapsAccounts {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<MapsAccount>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PrivateAtlasList {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<PrivateAtlas>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CreatorList {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Creator>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Sku {
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tier: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MapsKeySpecification {
#[serde(rename = "keyType")]
pub key_type: maps_key_specification::KeyType,
}
pub mod maps_key_specification {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum KeyType {
#[serde(rename = "primary")]
Primary,
#[serde(rename = "secondary")]
Secondary,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MapsAccountKeys {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(rename = "primaryKey", default, skip_serializing_if = "Option::is_none")]
pub primary_key: Option<String>,
#[serde(rename = "secondaryKey", default, skip_serializing_if = "Option::is_none")]
pub secondary_key: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MapsOperations {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MapsAccountProperties {
#[serde(rename = "x-ms-client-id", default, skip_serializing_if = "Option::is_none")]
pub x_ms_client_id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PrivateAtlasProperties {
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CreatorProperties {
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorResponse {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<ErrorDetail>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorDetail {
#[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<ErrorDetail>,
#[serde(rename = "additionalInfo", default, skip_serializing_if = "Vec::is_empty")]
pub additional_info: Vec<ErrorAdditionalInfo>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorAdditionalInfo {
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub info: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TrackedResource {
#[serde(flatten)]
pub resource: Resource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
pub location: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Resource {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SystemData {
#[serde(rename = "createdBy", default, skip_serializing_if = "Option::is_none")]
pub created_by: Option<String>,
#[serde(rename = "createdByType", default, skip_serializing_if = "Option::is_none")]
pub created_by_type: Option<system_data::CreatedByType>,
#[serde(rename = "createdAt", default, skip_serializing_if = "Option::is_none")]
pub created_at: Option<String>,
#[serde(rename = "lastModifiedBy", default, skip_serializing_if = "Option::is_none")]
pub last_modified_by: Option<String>,
#[serde(rename = "lastModifiedByType", default, skip_serializing_if = "Option::is_none")]
pub last_modified_by_type: Option<system_data::LastModifiedByType>,
#[serde(rename = "lastModifiedAt", default, skip_serializing_if = "Option::is_none")]
pub last_modified_at: Option<String>,
}
pub mod system_data {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum CreatedByType {
User,
Application,
ManagedIdentity,
Key,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum LastModifiedByType {
User,
Application,
ManagedIdentity,
Key,
}
}
|
use serde;
use serde_json;
use std::env;
use friday_error::frierr;
use friday_error::propagate;
use friday_error::FridayError;
use std::path::PathBuf;
use std::fs;
pub fn get_config_directory() -> Result<PathBuf, FridayError> {
return env::var("FRIDAY_CONFIG").map_or_else(
|_| frierr!("The environment variable FRIDAY_CONFIG needs to point \
to a configuration directory. \nPlease set the FRIDAY_CONFIG environment variable.\
\n\n\
For example: \n\
FRIDAY_CONFIG=./configs"),
|config_path_string| {
let path = PathBuf::from(config_path_string.clone());
if path.is_dir() {
return Ok(path);
} else {
return frierr!("{} is not a valid path", config_path_string);
}
});
}
pub fn get_config<T, S>(name: S) -> Result<T, FridayError>
where T: serde::de::DeserializeOwned,
S: AsRef<str> {
return get_config_directory().map_or_else(
propagate!("Failed to get config directory when reading config"),
|config_path| {
let mut path_to_file = config_path.clone();
path_to_file.push(name.as_ref());
fs::read_to_string(&path_to_file).map_or_else(
|err| frierr!("Failed to read {} - Reason: {}", path_to_file.to_str().unwrap(), err),
|contents| serde_json::from_str(&contents).map_or_else(
|err| frierr!("Failed to deserialize config {} - Reason: {}",
path_to_file.to_str().unwrap(), err),
|conf| Ok(conf)
))
});
}
pub fn write_config<T, S>(o: &T, name: S) -> Result<(), FridayError>
where T: serde::Serialize,
S: AsRef<str> {
return serde_json::to_string_pretty(o).map_or_else(
|err| frierr!("Failed to serialize into json - Reason {}", err),
|json| get_config_directory().map_or_else(
propagate!("Failed to get config directory when writing config"),
|config_path| {
let mut path_to_file = config_path.clone();
path_to_file.push(name.as_ref());
return fs::write(path_to_file, json).map_or_else(
|err| frierr!("Failed to write config to {} - Reason: {}",
config_path.to_str().unwrap(), err),
|_| Ok(()))
}));
}
#[cfg(test)]
mod tests {
use super::*;
use serde_derive::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
enum TestEnum {
On,
Off
}
#[derive(Deserialize, Serialize)]
struct TestConfig {
ip: String,
user: String,
action: TestEnum
}
#[test]
fn write_load_simple_config() {
env::set_var("FRIDAY_CONFIG", "./test-resources");
let conf: TestConfig = TestConfig{
ip: String::from("0.0.0.0"),
user: String::from("wolololo"),
action: TestEnum::On
};
write_config(&conf, "test_config.json").expect("Writing config failed");
let read_conf: TestConfig = get_config("test_config.json").expect("Reading config failed");
assert_eq!(read_conf.ip, conf.ip);
assert_eq!(read_conf.user, conf.user);
assert_eq!(read_conf.action, conf.action);
}
}
|
extern crate serde_yaml;
use from_file::FromFile;
#[derive(Serialize, Deserialize, Debug)]
pub struct BundleConfig {
pub bundles: Vec<ConfigItem>,
pub module_blacklist: Option<Vec<String>>,
}
impl Default for BundleConfig {
fn default() -> BundleConfig {
BundleConfig {
bundles: vec![],
module_blacklist: None,
}
}
}
impl FromFile for BundleConfig {}
#[derive(Serialize, Deserialize, Debug, Default)]
pub struct ConfigItem {
pub name: String,
pub urls: Vec<String>,
pub children: Vec<ConfigItem>,
}
impl<'a> Into<BundleConfig> for &'a str {
fn into(self) -> BundleConfig {
let items: BundleConfig = match serde_yaml::from_str(&self) {
Ok(i) => i,
Err(e) => {
eprintln!("{}", e);
BundleConfig::default()
}
};
items
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Outgoing {
pub bundles: Vec<Module>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct Module {
pub name: String,
pub include: Vec<String>,
pub exclude: Vec<String>,
pub create: bool,
}
|
use core::MatrixArray;
use core::dimension::{U1, U4};
use geometry::{QuaternionBase, UnitQuaternionBase};
/// A statically-allocated quaternion.
pub type Quaternion<N> = QuaternionBase<N, MatrixArray<N, U4, U1>>;
/// A statically-allocated unit quaternion.
pub type UnitQuaternion<N> = UnitQuaternionBase<N, MatrixArray<N, U4, U1>>;
|
use schema::horus_users;
#[derive(Queryable, Identifiable, Associations, Insertable, Serialize, Deserialize)]
#[table_name = "horus_users"]
pub struct User
{
pub id: i32,
pub first_name: String,
pub last_name: Option<String>,
pub email: String,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct PublicUser
{
pub id: i32,
pub first_name: String,
}
impl User
{
pub fn without_sensitive_attributes(&self) -> PublicUser
{
PublicUser {
id: self.id,
first_name: self.first_name.clone(),
}
}
}
|
struct A; //concrete type A
struct S(A); //concrete type S
struct SGEN<T>(T); //generic type SGEN
fn reg_fn(_s: S) {}
fn gen_spec_t(_s: SGEN<A>) {}
fn gen_spec_i32(_s: SGEN<i32>) {}
fn generic<T>(_s: SGEN<T>) {}
pub fn gen_fn() {
reg_fn(S(A)); //传入S结构体,成员为A
gen_spec_t(SGEN(A));
gen_spec_i32(SGEN(5));
generic::<char>(SGEN('c')); //强制泛型类型,如果SEGN中的成员不是char, 会报类型匹配错误
generic(SGEN("test")); //没有强制类型
println!("{:?}", "generic functions");
}
|
#[doc = "Reader of register CMD_RESP_STATUS"]
pub type R = crate::R<u32, super::CMD_RESP_STATUS>;
#[doc = "Reader of field `CURR_RD_ADDR`"]
pub type CURR_RD_ADDR_R = crate::R<u16, u16>;
#[doc = "Reader of field `CURR_WR_ADDR`"]
pub type CURR_WR_ADDR_R = crate::R<u16, u16>;
#[doc = "Reader of field `CMD_RESP_EC_BUS_BUSY`"]
pub type CMD_RESP_EC_BUS_BUSY_R = crate::R<bool, bool>;
#[doc = "Reader of field `CMD_RESP_EC_BUSY`"]
pub type CMD_RESP_EC_BUSY_R = crate::R<bool, bool>;
impl R {
#[doc = "Bits 0:8 - I2C/SPI read current address for CMD_RESP mode. HW increments the field after a read access to the memory buffer. However, when the last memory buffer address is reached, the address is NOT incremented (but remains at the maximim memory buffer address). The field is used to determine how many bytes have been read (# bytes = CURR_RD_ADDR - CMD_RESP_CTRL.BASE_RD_ADDR). This field is reliable when there is no bus transfer. This field is potentially unreliable when there is a ongoing bus transfer, i.e. when CMD_RESP_EC_BUSY is '0', the field is reliable."]
#[inline(always)]
pub fn curr_rd_addr(&self) -> CURR_RD_ADDR_R {
CURR_RD_ADDR_R::new((self.bits & 0x01ff) as u16)
}
#[doc = "Bits 16:24 - I2C/SPI write current address for CMD_RESP mode. HW increments the field after a write access to the memory buffer. However, when the last memory buffer address is reached, the address is NOT incremented (but remains at the maximim memory buffer address). The field is used to determine how many bytes have been written (# bytes = CURR_WR_ADDR - CMD_RESP_CTRL.BASE_WR_ADDR). This field is reliable when there is no bus transfer. This field is potentially unreliable when there is a ongoing bus transfer, i.e when CMD_RESP_EC_BUSY is '0', the field is reliable."]
#[inline(always)]
pub fn curr_wr_addr(&self) -> CURR_WR_ADDR_R {
CURR_WR_ADDR_R::new(((self.bits >> 16) & 0x01ff) as u16)
}
#[doc = "Bit 30 - Indicates whether there is an ongoing bus transfer to the IP. '0': no ongoing bus transfer. '1': ongoing bus transfer. For SPI, the field is '1' when slave mode is selected. For I2C, the field is set to '1' at a I2C START/RESTART. In case of an address match, the field is set to '0' on a I2C STOP. In case of NO address match, the field is set to '0' after the failing address match."]
#[inline(always)]
pub fn cmd_resp_ec_bus_busy(&self) -> CMD_RESP_EC_BUS_BUSY_R {
CMD_RESP_EC_BUS_BUSY_R::new(((self.bits >> 30) & 0x01) != 0)
}
#[doc = "Bit 31 - N/A"]
#[inline(always)]
pub fn cmd_resp_ec_busy(&self) -> CMD_RESP_EC_BUSY_R {
CMD_RESP_EC_BUSY_R::new(((self.bits >> 31) & 0x01) != 0)
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.