text stringlengths 8 4.13M |
|---|
extern crate bencode;
use self::bencode::Bencode;
use self::bencode::util::ByteString;
use std::{convert, io};
#[macro_export]
macro_rules! get_field_with_default {
($m:expr, $field:expr, $default:expr) => (
match $m.get(&ByteString::from_str($field)) {
Some(a) => try!(FromBencode::from_bencode(a)),
None => $default
}
)
}
#[macro_export]
macro_rules! get_field {
($m:expr, $field:expr) => (
get_field_with_default!($m, $field, return Err(decoder::Error::DoesntContain($field)))
)
}
#[macro_export]
macro_rules! get_optional_field {
($m:expr, $field:expr) => (
get_field_with_default!($m, $field, None)
)
}
#[macro_export]
macro_rules! get_raw_field {
($m:expr, $field:expr) => (
match $m.get(&ByteString::from_str($field)) {
Some(a) => a,
None => return Err(Error::DoesntContain($field))
}
)
}
#[macro_export]
macro_rules! get_field_as_bencoded_bytes {
($m:expr, $field:expr) => (
try!(get_raw_field!($m, $field).to_bytes())
)
}
#[macro_export]
macro_rules! get_field_as_bytes {
($m:expr, $field:expr) => (
match get_raw_field!($m, $field) {
&Bencode::ByteString(ref v) => v.clone(),
_ => return Err(decoder::Error::NotAByteString)
}
)
}
#[derive(Debug)]
pub enum Error {
IoError(io::Error),
DecodingError(bencode::streaming::Error),
DoesntContain(&'static str),
NotANumber(bencode::NumFromBencodeError),
NotAString(bencode::StringFromBencodeError),
}
impl convert::From<io::Error> for Error {
fn from(err: io::Error) -> Error {
Error::IoError(err)
}
}
impl convert::From<bencode::streaming::Error> for Error {
fn from(err: bencode::streaming::Error) -> Error {
Error::DecodingError(err)
}
}
impl convert::From<bencode::NumFromBencodeError> for Error {
fn from(err: bencode::NumFromBencodeError) -> Error {
Error::NotANumber(err)
}
}
impl convert::From<bencode::StringFromBencodeError> for Error {
fn from(err: bencode::StringFromBencodeError) -> Error {
Error::NotAString(err)
}
}
pub fn get_info_bytes(metainfo: &[u8]) -> Option<Vec<u8>> {
let mut bytes = Vec::new();
bytes.extend_from_slice(metainfo);
extract_info_bytes(bytes).ok()
}
fn extract_info_bytes(metainfo: Vec<u8>) -> Result<Vec<u8>, Error> {
if let Some(bencoded) = bencode::from_vec(metainfo).ok() {
match bencoded {
Bencode::Dict(ref m) => {
let info: Vec<_> = get_field_as_bencoded_bytes!(m, "info");
return Ok(info);
}
_ => {}
}
}
Err(Error::DoesntContain("info map"))
}
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! HTML Escaping
//!
//! This module contains one unit-struct which can be used to HTML-escape a
//! string of text (for use in a format string).
use std::fmt;
/// Wrapper struct which will emit the HTML-escaped version of the contained
/// string when passed to a format string.
pub struct Escape<'a>(pub &'a str);
impl<'a> fmt::Display for Escape<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
// Because the internet is always right, turns out there's not that many
// characters to escape: http://stackoverflow.com/questions/7381974
let Escape(s) = *self;
let pile_o_bits = s;
let mut last = 0;
for (i, ch) in s.bytes().enumerate() {
match ch as char {
'<' | '>' | '&' | '\'' | '"' => {
fmt.write_str(&pile_o_bits[last..i])?;
let s = match ch as char {
'>' => ">",
'<' => "<",
'&' => "&",
'\'' => "'",
'"' => """,
_ => unreachable!(),
};
fmt.write_str(s)?;
last = i + 1;
}
_ => {}
}
}
if last < s.len() {
fmt.write_str(&pile_o_bits[last..])?;
}
Ok(())
}
}
|
use crate::{
block::{self, BlockId},
color_system,
dicebot::{self, bcdice},
idb,
model::{self, modeless::ModelessId},
random_id::U128Id,
renderer::Renderer,
resource::{Data, ResourceId},
skyway, udonarium, Color,
};
use kagura::prelude::*;
use std::{
collections::{HashMap, HashSet},
rc::Rc,
};
use wasm_bindgen::{prelude::*, JsCast};
mod render;
mod state;
use render::render;
pub type Room = Component<Props, Sub>;
pub struct Props {
pub peer: Rc<skyway::Peer>,
pub room: Rc<skyway::Room>,
pub client_id: Rc<String>,
pub common_database: Rc<web_sys::IdbDatabase>,
pub room_database: Rc<web_sys::IdbDatabase>,
pub table_database: Rc<web_sys::IdbDatabase>,
}
pub type State = state::State<Msg, Sub>;
pub enum Msg {
NoOp,
InitDomDependents,
ResizeCanvas,
// Subscribe
UpdateTableDatabase(Rc<web_sys::IdbDatabase>),
// Tick
Tick1000ms,
// Contextmenu
OpenContextmenu([f64; 2], [f64; 2], state::Contextmenu),
CloseContextmenu,
// header menu
SetHeadermenuState(state::headermenu::State),
// Modeless
OpenModeless(state::Modeless),
FocusModeless(ModelessId),
GrabModeless(ModelessId, [f64; 2], [bool; 4]),
DragModeless(ModelessId, [f64; 2]),
DropModeless(ModelessId),
CloseModeless(ModelessId),
SetModelessTabIdx(ModelessId, usize),
GrabModelessTab(ModelessId, usize),
DropModelessTabToModeless(ModelessId),
DropModelessTab([f64; 2]),
// Modal
OpenModal(state::Modal),
CloseModal,
// UI for table
AddCharacterWithMousePositionToCloseContextmenu([f32; 2]),
AddTablemaskWithMousePositionToCloseContextmenu([f32; 2], [f32; 2], Color, bool, bool),
AddBoxblockWithMousePositionToCloseContextmenu([f32; 2], [f32; 3], Color),
CloneCharacterToCloseContextmenu(BlockId),
CloneTablemaskToCloseContextmenu(BlockId),
RemoveCharacterToCloseContextmenu(BlockId),
RemoveTablemaskToCloseContextmenu(BlockId),
RemoveAreaToCloseContextmenu(BlockId),
RemoveBoxblockToCloseContextmenu(BlockId),
SetTableIs2dMode(bool),
// Mouse
SetLastMousePosition(bool, [f32; 2]),
SetLastMouseDownPosition([f32; 2]),
SetLastMouseUpPosition([f32; 2]),
SetCameraRotationWithMouseMovement([f32; 2]),
SetCameraMovementWithMouseMovement([f32; 2]),
SetCameraMovementWithMouseWheel(f32),
SetSelectingTableTool(state::table::Tool),
SetCharacterPositionWithMousePosition(BlockId, [f32; 2]),
SetTablemaskPositionWithMousePosition(BlockId, [f32; 2]),
SetBoxblockPositionWithMousePosition(BlockId, [f32; 2]),
DrawLineWithMousePosition([f32; 2], [f32; 2], f64, Color),
EraceLineWithMousePosition([f32; 2], [f32; 2], f64),
ClearTable,
MeasureLineWithMousePosition([f32; 2], [f32; 2], Option<BlockId>, Color),
ClearMeasure,
SetAreaWithMousePosition(
[f32; 2],
[f32; 2],
Option<BlockId>,
Color,
Color,
block::table_object::area::Type,
),
// World
AddTable,
SetSelectingTable(BlockId),
RemoveTable(BlockId),
AddTag,
RemoveTag(BlockId),
AddMemo(Option<BlockId>),
RemoveMemo(BlockId),
// Table
SetTableSize(BlockId, [f32; 2]),
SetTableImage(BlockId, Option<ResourceId>),
SetTableName(BlockId, String),
SetTableIsShowingGrid(BlockId, bool),
SetTableIsBindToGrid(BlockId, bool),
// Tag
SetTagName(BlockId, String),
// PersonalData
SetPersonalDataWithPlayerName(String),
SetPersonalDataWithIconImageToCloseModal(ResourceId),
// tablemask
SetTablemaskSize(BlockId, [f32; 2]),
SetTablemaskColor(BlockId, Color),
SetTablemaskIsFixed(BlockId, bool),
SetTablemaskIsRounded(BlockId, bool),
SetTablemaskIsInved(BlockId, bool),
// boxblock
SetBoxblockSize(BlockId, [f32; 3]),
SetBoxblockColor(BlockId, Color),
SetBoxblockIsFixed(BlockId, bool),
// character
SetCharacterName(BlockId, String),
SetCharacterSize(BlockId, [Option<f32>; 2]),
SetCharacterTextrureToCloseModal(BlockId, Option<ResourceId>),
SetCharacterPosition(BlockId, [f32; 3]),
SetCharacterIsHidden(BlockId, bool),
// property
AddChildToProprty(BlockId),
SetPropertyName(BlockId, String),
SetPropertyValue(BlockId, block::property::Value),
SetPropertyIsSelected(BlockId, bool),
SetPropertyIsCollapsed(BlockId, bool),
RemoveProperty(BlockId, BlockId),
// チャット関係
SetInputingChatMessage(String),
SendInputingChatMessage,
InsertChatItem(BlockId, block::chat::Item, f64),
AddChatSender(BlockId),
RemoveChatSender(BlockId),
SetSelectingChatSenderIdx(usize),
AddChatTab,
SetSelectingChatTabIdx(usize),
SetChatTabName(BlockId, String),
RemoveChatTab(BlockId),
// 共有メモ関係
SetMemoName(BlockId, String),
SetMemoText(BlockId, String),
// ブロックフィールド
AssignFieldBlocks(HashMap<BlockId, block::FieldBlock>),
// リソース管理
LoadFromFileList(web_sys::FileList),
LoadDataToResource(Data),
AssignDataToResource(U128Id, Data),
// BCDice
GetBcdiceServerList,
SetBcdiceServerList(Vec<String>),
GetBcdiceSystemNames,
SetBcdiceSystemNames(bcdice::Names),
GetBcdiceSystemInfo(String),
SetBcdiceSystemInfo(bcdice::SystemInfo),
// IDB
LoadToOpenTable(
BlockId,
HashMap<BlockId, block::FieldBlock>,
HashMap<U128Id, Data>,
),
// Udonarium互換
LoadUdonariumCharacter(udonarium::Character),
AddCharacterWithUdonariumData(udonarium::Data, Option<Data>),
// 接続に関する操作
SendBlockPacks(HashMap<BlockId, JsValue>),
SendResourcePacks(HashMap<ResourceId, JsValue>),
ReceiveMsg(skyway::Msg),
PeerJoin(String),
PeerLeave(String),
DisconnectFromRoom,
}
pub enum Sub {
DisconnectFromRoom,
UpdateTableDatabase(Rc<web_sys::IdbDatabase>),
}
pub fn new() -> Room {
Component::new(init, update, render)
}
fn init(state: Option<State>, props: Props) -> (State, Cmd<Msg, Sub>, Vec<Batch<Msg>>) {
let state = if let Some(mut state) = state {
state.set_table_db(props.table_database);
state
} else {
State::new(
Rc::clone(&props.peer),
Rc::clone(&props.room),
props.client_id,
props.common_database,
props.room_database,
props.table_database,
)
};
let task = Cmd::task(|handler| {
handler(Msg::InitDomDependents);
});
let batch = vec![
Batch::new(|mut handler| {
let a = Closure::wrap(Box::new(move || {
handler(Msg::ResizeCanvas);
}) as Box<dyn FnMut()>);
web_sys::window()
.unwrap()
.set_onresize(Some(a.as_ref().unchecked_ref()));
a.forget();
}),
Batch::new(batch::time::tick(1000, || Msg::Tick1000ms)),
Batch::new({
let room = Rc::clone(&props.room);
move |mut handler| {
let a = Closure::wrap(Box::new({
move |receive_data: Option<skyway::ReceiveData>| {
let msg = receive_data
.and_then(|receive_data| receive_data.data())
.map(|receive_data| {
web_sys::console::log_1(&JsValue::from(&receive_data));
skyway::Msg::from(receive_data)
})
.and_then(|msg| {
if let skyway::Msg::None = msg {
None
} else {
Some(msg)
}
});
if let Some(msg) = msg {
web_sys::console::log_1(&JsValue::from(msg.type_name()));
handler(Msg::ReceiveMsg(msg));
} else {
web_sys::console::log_1(&JsValue::from("faild to deserialize message"));
}
}
})
as Box<dyn FnMut(Option<skyway::ReceiveData>)>);
room.payload.on("data", Some(a.as_ref().unchecked_ref()));
a.forget();
}
}),
Batch::new({
let room = Rc::clone(&props.room);
move |mut handler| {
let a = Closure::wrap(Box::new(move |peer_id: String| {
handler(Msg::PeerJoin(peer_id));
}) as Box<dyn FnMut(String)>);
room.payload
.on("peerJoin", Some(a.as_ref().unchecked_ref()));
a.forget();
}
}),
Batch::new({
let room = Rc::clone(&props.room);
move |mut handler| {
let a = Closure::wrap(Box::new(move |peer_id: String| {
handler(Msg::PeerLeave(peer_id));
}) as Box<dyn FnMut(String)>);
room.payload
.on("peerLeave", Some(a.as_ref().unchecked_ref()));
a.forget();
}
}),
];
(state, task, batch)
}
fn update(state: &mut State, msg: Msg) -> Cmd<Msg, Sub> {
match msg {
Msg::NoOp => state.dequeue(),
Msg::InitDomDependents => {
state.set_pixel_ratio(web_sys::window().unwrap().device_pixel_ratio() as f32);
if let (Some(canvas_size), Some(canvas), Some(modeless_parent)) = (
reset_canvas_size(state.pixel_ratio()),
get_table_canvas_element(),
get_element_by_id("modeless-parent"),
) {
state.set_canvas_size(canvas_size);
state.set_renderer(Renderer::new(canvas));
render_canvas(state);
state.set_modeless_parent(Some(modeless_parent));
Cmd::task(|resolve| resolve(Msg::GetBcdiceServerList))
} else {
state.enqueue(Cmd::task(|resolve| resolve(Msg::InitDomDependents)));
Cmd::none()
}
}
Msg::ResizeCanvas => {
if let Some(canvas_size) = reset_canvas_size(state.pixel_ratio()) {
state.set_canvas_size(canvas_size);
render_canvas(state);
state.dequeue()
} else {
state.enqueue(Cmd::task(|resolve| resolve(Msg::ResizeCanvas)));
Cmd::none()
}
}
// Subscribe
Msg::UpdateTableDatabase(table_db) => Cmd::sub(Sub::UpdateTableDatabase(table_db)),
// Tick
Msg::Tick1000ms => state.dequeue(),
// Contextmenu
Msg::OpenContextmenu(page_mouse_position, offset_mouse_position, contextmenu) => {
state.open_contextmenu(page_mouse_position, offset_mouse_position, contextmenu);
state.dequeue()
}
Msg::CloseContextmenu => {
state.close_contextmenu();
state.dequeue()
}
// Headermenu
Msg::SetHeadermenuState(headermenu_state) => {
state.set_headermenu(headermenu_state);
state.dequeue()
}
// Modeless
Msg::OpenModeless(modeless) => {
state.open_modeless(modeless);
state.dequeue()
}
Msg::FocusModeless(modeless_id) => {
state.focus_modeless(modeless_id);
state.dequeue()
}
Msg::GrabModeless(modeless_id, mouse_position, movable) => {
state.grab_modeless(modeless_id, mouse_position, movable);
state.dequeue()
}
Msg::DragModeless(modeless_id, mouse_position) => {
state.drag_modeless(modeless_id, mouse_position);
state.dequeue()
}
Msg::DropModeless(modeless_id) => {
state.drop_modeless(modeless_id);
state.dequeue()
}
Msg::CloseModeless(modeless_id) => {
state.close_modeless(modeless_id);
state.dequeue()
}
Msg::SetModelessTabIdx(modeless_id, tab_idx) => {
state.set_modeless_focused_tab(modeless_id, tab_idx);
state.dequeue()
}
Msg::GrabModelessTab(modeless_id, tab_idx) => {
state
.table_mut()
.set_moving_tab(Some((modeless_id, tab_idx)));
state.grab_modeless(modeless_id, [0.0, 0.0], [false, false, false, false]);
state.dequeue()
}
Msg::DropModelessTabToModeless(modeless_id) => {
if let Some((from_id, tab_idx)) = state.table().moving_tab() {
let from_id = *from_id;
let tab_idx = *tab_idx;
if modeless_id != from_id {
if let Some(block_id) = state.remove_modeless_tab(from_id, tab_idx) {
state.add_modeless_tab(modeless_id, block_id);
}
state.drop_modeless(from_id);
}
}
state.dequeue()
}
Msg::DropModelessTab(mouse_pos) => {
if let Some((from_id, tab_idx)) = state.table().moving_tab() {
let from_id = *from_id;
let tab_idx = *tab_idx;
if let Some(block_id) = state.remove_modeless_tab(from_id, tab_idx) {
let modeless = state::Modeless::Object {
tabs: vec![block_id],
focused: 0,
outlined: None,
};
state.open_modeless_with_position(modeless, mouse_pos);
}
state.drop_modeless(from_id);
}
state.dequeue()
}
// Modal
Msg::OpenModal(modal) => {
state.open_modal(modal);
state.dequeue()
}
Msg::CloseModal => {
state.close_modal();
state.dequeue()
}
// UI
Msg::AddCharacterWithMousePositionToCloseContextmenu(mouse_position) => {
state.close_contextmenu();
let [x, y] = get_table_position(state, false, &mouse_position, state.pixel_ratio());
let mut prop_hp = block::Property::new("HP");
prop_hp.set_value(block::property::Value::Num(0.0));
let prop_hp = state.block_field_mut().add(prop_hp);
let mut prop_mp = block::Property::new("MP");
prop_mp.set_value(block::property::Value::Num(0.0));
let prop_mp = state.block_field_mut().add(prop_mp);
let mut prop_root = block::Property::new("");
prop_root.set_value(block::property::Value::Children(vec![
prop_hp.clone(),
prop_mp.clone(),
]));
let prop_root = state.block_field_mut().add(prop_root);
let mut character = block::Character::new(
prop_root.clone(),
"キャラクター",
state.client_id().as_ref().clone(),
);
character.set_position([x, y, 0.0]);
let character = state.block_field_mut().add(character);
let world = state.world().clone();
state
.block_field_mut()
.update(&world, timestamp(), |world: &mut block::World| {
world.add_character(character.clone());
});
render_canvas(state);
send_pack_cmd(
state.block_field(),
vec![prop_hp, prop_mp, prop_root, character, world],
)
}
Msg::AddTablemaskWithMousePositionToCloseContextmenu(
mouse_position,
size,
color,
is_rounded,
is_inved,
) => {
state.close_contextmenu();
if let Some(selecting_table) = state.selecting_table().map(|t| t.clone()) {
let [x, y] = get_table_position(state, false, &mouse_position, state.pixel_ratio());
let mut tablemask =
block::table_object::Tablemask::new(&size, color, is_rounded, is_inved);
tablemask.set_position([x, y]);
let tablemask = state.block_field_mut().add(tablemask);
state.block_field_mut().update(
&selecting_table,
timestamp(),
|table: &mut block::Table| {
table.add_tablemask(tablemask.clone());
},
);
render_canvas(state);
send_pack_cmd(state.block_field(), vec![tablemask, selecting_table])
} else {
state.dequeue()
}
}
Msg::AddBoxblockWithMousePositionToCloseContextmenu(mouse_position, size, color) => {
state.close_contextmenu();
if let Some(selecting_table) = state.selecting_table().map(|t| t.clone()) {
let [xw, yw, zw] = size;
let [x, y, z] = get_focused_position(
state,
&mouse_position,
state.pixel_ratio(),
&[xw * 0.5, yw * 0.5, zw * 0.5],
);
let boxblock = block::table_object::Boxblock::new([x, y, z], [xw, yw, zw], color);
let boxblock = state.block_field_mut().add(boxblock);
state.block_field_mut().update(
&selecting_table,
timestamp(),
|table: &mut block::Table| {
table.add_boxblock(boxblock.clone());
},
);
render_canvas(state);
send_pack_cmd(state.block_field(), vec![boxblock, selecting_table])
} else {
state.dequeue()
}
}
Msg::CloneCharacterToCloseContextmenu(character) => {
state.close_contextmenu();
if let Some(character) = state.block_field().get::<block::Character>(&character) {
let mut character = character.clone();
let prop = clone_prop(state.block_field_mut(), character.property_id())
.unwrap_or(block::Property::new(""));
let prop = state.block_field_mut().add(prop);
let mut props = trace_prop_id(state.block_field(), &prop);
character.set_property_id(prop);
let character = state.block_field_mut().add(character);
let world = state.world().clone();
state
.block_field_mut()
.update(&world, timestamp(), |world: &mut block::World| {
world.add_character(character.clone());
});
props.push(character);
props.push(world.clone());
render_canvas(state);
send_pack_cmd(state.block_field(), props)
} else {
state.dequeue()
}
}
Msg::CloneTablemaskToCloseContextmenu(tablemask) => {
state.close_contextmenu();
if let (Some(tablemask), Some(selecting_table)) = (
state
.block_field()
.get::<block::table_object::Tablemask>(&tablemask),
state.selecting_table().map(|t| t.clone()),
) {
let tablemask = tablemask.clone();
let tablemask = state.block_field_mut().add(tablemask);
state.block_field_mut().update(
&selecting_table,
timestamp(),
|table: &mut block::Table| {
table.add_tablemask(tablemask.clone());
},
);
render_canvas(state);
send_pack_cmd(state.block_field(), vec![tablemask, selecting_table])
} else {
state.dequeue()
}
}
Msg::RemoveAreaToCloseContextmenu(area_id) => {
state.close_contextmenu();
if let Some(selecting_table) = state.selecting_table().map(|t| t.clone()) {
state.block_field_mut().update(
&selecting_table,
timestamp(),
|table: &mut block::Table| {
table.remove_area(&area_id);
},
);
state.block_field_mut().remove(&area_id);
render_canvas(state);
send_pack_cmd(state.block_field(), vec![selecting_table, area_id])
} else {
state.dequeue()
}
}
Msg::RemoveBoxblockToCloseContextmenu(boxblock_id) => {
state.close_contextmenu();
if let Some(selecting_table) = state.selecting_table().map(|t| t.clone()) {
state.block_field_mut().update(
&selecting_table,
timestamp(),
|table: &mut block::Table| {
table.remove_boxblock(&boxblock_id);
},
);
state.block_field_mut().remove(&boxblock_id);
render_canvas(state);
send_pack_cmd(state.block_field(), vec![selecting_table, boxblock_id])
} else {
state.dequeue()
}
}
Msg::RemoveCharacterToCloseContextmenu(character) => {
state.close_contextmenu();
let world = state.world().clone();
state
.block_field_mut()
.update(&world, timestamp(), |world: &mut block::World| {
world.remove_character(&character);
});
state.block_field_mut().remove(&character);
render_canvas(state);
send_pack_cmd(state.block_field(), vec![world, character])
}
Msg::RemoveTablemaskToCloseContextmenu(tablemask) => {
state.close_contextmenu();
if let Some(selecting_table) = state.selecting_table().map(|t| t.clone()) {
state.block_field_mut().update(
&selecting_table,
timestamp(),
|table: &mut block::Table| {
table.remove_tablemask(&tablemask);
},
);
state.block_field_mut().remove(&tablemask);
render_canvas(state);
send_pack_cmd(state.block_field(), vec![selecting_table, tablemask])
} else {
state.dequeue()
}
}
Msg::SetTableIs2dMode(is_2d_mode) => {
state.table_mut().set_is_2d_mode(is_2d_mode);
if is_2d_mode {
state.camera_mut().set_x_axis_rotation(0.0);
state.camera_mut().set_z_axis_rotation(0.0);
state.camera_mut().set_field_of_view(30.0);
} else {
state.camera_mut().set_field_of_view(30.0);
}
render_canvas(state);
state.dequeue()
}
// Mouse
Msg::SetLastMousePosition(check_focused, mouse_position) => {
if check_focused {
check_focused_object(state, &mouse_position);
}
state.table_mut().set_last_mouse_position(mouse_position);
state.dequeue()
}
Msg::SetLastMouseDownPosition(mouse_position) => {
check_focused_object(state, &mouse_position);
state
.table_mut()
.set_last_mouse_down_position(mouse_position);
match state.table().focused() {
state::table::Focused::Character(table_block)
| state::table::Focused::Tablemask(table_block)
| state::table::Focused::Boxblock(table_block) => {
let block_id = table_block.block_id.clone();
state.table_mut().set_floating_object(Some(block_id));
}
_ => (),
}
state.dequeue()
}
Msg::SetLastMouseUpPosition(mouse_position) => {
check_focused_object(state, &mouse_position);
state.table_mut().set_last_mouse_up_position(mouse_position);
state.table_mut().set_floating_object(None);
render_canvas(state);
state.dequeue()
}
Msg::SetCameraRotationWithMouseMovement(mouse_position) => {
let dx = mouse_position[0] - state.table().last_mouse_position()[0];
let dy = mouse_position[1] - state.table().last_mouse_position()[1];
let long_edge = state.canvas_size()[0].max(state.canvas_size()[1]);
let factor = 3.0 / long_edge * state.pixel_ratio();
let camera = state.camera_mut();
camera.set_x_axis_rotation(camera.x_axis_rotation() - dy * factor);
camera.set_z_axis_rotation(camera.z_axis_rotation() - dx * factor);
render_canvas(state);
state.dequeue()
}
Msg::SetCameraMovementWithMouseMovement(mouse_position) => {
let dx = mouse_position[0] - state.table().last_mouse_position()[0];
let dy = mouse_position[1] - state.table().last_mouse_position()[1];
let long_edge = state.canvas_size()[0].max(state.canvas_size()[1]);
let factor = 50.0 / long_edge * state.pixel_ratio();
let camera = state.camera_mut();
let mov = camera.movement();
let mov = [mov[0] - dx * factor, mov[1] + dy * factor, mov[2]];
camera.set_movement(mov);
render_canvas(state);
state.dequeue()
}
Msg::SetCameraMovementWithMouseWheel(delta_y) => {
let factor = 0.02;
let camera = state.camera_mut();
let mov = camera.movement();
let mov = [mov[0], mov[1], mov[2] + factor * delta_y];
camera.set_movement(mov);
render_canvas(state);
state.dequeue()
}
Msg::SetSelectingTableTool(table_tool) => {
state.table_mut().set_selecting_tool(table_tool);
state.dequeue()
}
Msg::SetCharacterPositionWithMousePosition(block_id, mouse_position) => {
let position = get_focused_position(
state,
&mouse_position,
state.pixel_ratio(),
&[0.0, 0.0, 0.0],
);
let timestamp = timestamp();
let updated = state
.block_field_mut()
.update(&block_id, timestamp, |character: &mut block::Character| {
character.set_position(position);
})
.is_none();
if updated {
render_canvas(state);
send_pack_cmd(state.block_field(), vec![block_id])
} else {
state.dequeue()
}
}
Msg::SetTablemaskPositionWithMousePosition(block_id, mouse_position) => {
let is_fixied = state
.block_field()
.get::<block::table_object::Tablemask>(&block_id)
.map(|tablemask| tablemask.is_fixed())
.unwrap_or(true);
if !is_fixied {
let [x, y] = get_table_position(state, false, &mouse_position, state.pixel_ratio());
let timestamp = timestamp();
let updated = state
.block_field_mut()
.update(
&block_id,
timestamp,
|tablemask: &mut block::table_object::Tablemask| {
tablemask.set_position([x, y]);
},
)
.is_none();
if updated {
render_canvas(state);
send_pack_cmd(state.block_field(), vec![block_id])
} else {
state.dequeue()
}
} else {
update(
state,
Msg::SetCameraMovementWithMouseMovement(mouse_position),
)
}
}
Msg::SetBoxblockPositionWithMousePosition(block_id, mouse_position) => {
let is_fixied = state
.block_field()
.get::<block::table_object::Boxblock>(&block_id)
.map(|boxblock| boxblock.is_fixed())
.unwrap_or(true);
if !is_fixied {
let s = state
.block_field()
.get::<block::table_object::Boxblock>(&block_id)
.map(|boxblock| boxblock.size().clone())
.unwrap_or([0.0, 0.0, 0.0]);
let position = get_focused_position(
state,
&mouse_position,
state.pixel_ratio(),
&[s[0] * 0.5, s[1] * 0.5, s[2] * 0.5],
);
let timestamp = timestamp();
let updated = state
.block_field_mut()
.update(
&block_id,
timestamp,
|boxblock: &mut block::table_object::Boxblock| {
boxblock.set_position(position);
},
)
.is_none();
if updated {
render_canvas(state);
send_pack_cmd(state.block_field(), vec![block_id])
} else {
state.dequeue()
}
} else {
update(
state,
Msg::SetCameraMovementWithMouseMovement(mouse_position),
)
}
}
Msg::DrawLineWithMousePosition(a, b, line_width, color) => {
let selecting_table = state.selecting_table();
let drawing_texture_id = if let Some(selecting_table) = selecting_table {
state
.block_field()
.get::<block::Table>(&selecting_table)
.map(|table| table.drawing_texture_id().clone())
} else {
None
};
if let Some(texture_id) = drawing_texture_id {
let [ax, ay] = get_table_position(state, true, &a, state.pixel_ratio());
let [bx, by] = get_table_position(state, true, &b, state.pixel_ratio());
draw_line_to_table(state, &texture_id, ax, ay, bx, by, &color, line_width);
state.room().send(skyway::Msg::DrawLine {
texture: texture_id.to_id(),
ax,
ay,
bx,
by,
color,
line_width,
});
render_canvas(state);
state.dequeue()
} else {
state.dequeue()
}
}
Msg::EraceLineWithMousePosition(a, b, line_width) => {
let selecting_table = state.selecting_table();
let drawing_texture_id = if let Some(selecting_table) = selecting_table {
state
.block_field()
.get::<block::Table>(&selecting_table)
.map(|table| table.drawing_texture_id().clone())
} else {
None
};
if let Some(texture_id) = drawing_texture_id {
let [ax, ay] = get_table_position(state, true, &a, state.pixel_ratio());
let [bx, by] = get_table_position(state, true, &b, state.pixel_ratio());
erace_line_of_texture(state, &texture_id, ax, ay, bx, by, line_width);
state.room().send(skyway::Msg::EraceLine {
texture: texture_id.to_id(),
ax,
ay,
bx,
by,
line_width,
});
render_canvas(state);
state.dequeue()
} else {
state.dequeue()
}
}
Msg::ClearTable => {
let selecting_table = state.selecting_table();
let drawing_texture_id = if let Some(selecting_table) = selecting_table {
state
.block_field()
.get::<block::Table>(&selecting_table)
.map(|table| table.drawing_texture_id().clone())
} else {
None
};
if let Some(texture_id) = drawing_texture_id {
state.block_field_mut().update(
&texture_id,
timestamp(),
|texture: &mut block::table::Texture| {
texture.clear();
},
);
state.room().send(skyway::Msg::ClearTable {
texture: texture_id.to_id(),
});
render_canvas(state);
state.dequeue()
} else {
state.dequeue()
}
}
Msg::MeasureLineWithMousePosition(a, b, block_id, color) => {
let [ax, ay, az] =
get_focused_position(state, &a, state.pixel_ratio(), &[0.0, 0.0, 0.0]);
let [bx, by, bz] =
get_focused_position(state, &b, state.pixel_ratio(), &[0.0, 0.0, 0.0]);
let len = ((bx - ax).powi(2) + (by - ay).powi(2) + (bz - az).powi(2)).sqrt();
state.table_mut().clear_info();
state
.table_mut()
.add_info("始点", format!("({:.1},{:.1},{:.1})", ax, ay, az));
state
.table_mut()
.add_info("終点", format!("({:.1},{:.1},{:.1})", bx, by, bz));
state.table_mut().add_info("距離", format!("{:.1}", len));
if let Some(block_id) = block_id {
let block_id = block_id.clone();
state.block_field_mut().update(
&block_id,
timestamp(),
|m: &mut block::table_object::Measure| {
m.set_org([ax, ay, az]);
m.set_vec([bx - ax, by - ay, bz - az]);
m.set_color(color);
},
);
} else {
let measure = block::table_object::Measure::new(
[ax, ay, az],
[bx - ax, by - ay, bz - az],
color,
);
let bid = state.block_field_mut().add(measure);
if let state::table::Tool::Measure { block_id, .. } =
state.table_mut().selecting_tool_mut()
{
*block_id = Some(bid);
}
}
render_canvas(state);
state.dequeue()
}
Msg::ClearMeasure => {
let measures = state
.block_field()
.all::<block::table_object::Measure>()
.into_iter()
.map(|(id, _)| id)
.collect::<Vec<_>>();
for measure_id in measures {
state.block_field_mut().remove(&measure_id);
}
if let state::table::Tool::Measure { block_id, .. } =
state.table_mut().selecting_tool_mut()
{
*block_id = None;
}
render_canvas(state);
state.dequeue()
}
Msg::SetAreaWithMousePosition(a, b, block_id, color_1, color_2, type_) => {
let [ax, ay] = get_table_position(state, false, &a, state.pixel_ratio());
let [bx, by] = get_table_position(state, false, &b, state.pixel_ratio());
let len = ((bx - ax).powi(2) + (by - ay).powi(2)).sqrt();
state.table_mut().clear_info();
state
.table_mut()
.add_info("始点", format!("({:.1},{:.1})", ax, ay));
state
.table_mut()
.add_info("終点", format!("({:.1},{:.1})", bx, by));
state.table_mut().add_info("距離", format!("{:.1}", len));
if let Some(block_id) = block_id {
let block_id = block_id.clone();
state.block_field_mut().update(
&block_id,
timestamp(),
|a: &mut block::table_object::Area| {
a.set_org([ax, ay, 0.0]);
a.set_vec([bx - ax, by - ay, 0.0]);
a.set_color_1(color_1);
a.set_color_2(color_2);
a.set_type(type_);
},
);
render_canvas(state);
send_pack_cmd(state.block_field(), vec![block_id])
} else if let Some(selecting_table) = state.selecting_table().map(|t| t.clone()) {
let area = block::table_object::Area::new(
[ax, ay, 0.0],
[bx - ax, by - ay, 0.0],
color_1,
color_2,
type_,
);
let bid = state.block_field_mut().add(area);
state.block_field_mut().update(
&selecting_table,
timestamp(),
|table: &mut block::Table| {
table.add_area(bid.clone());
},
);
if let state::table::Tool::Area { block_id, .. } =
state.table_mut().selecting_tool_mut()
{
*block_id = Some(bid.clone());
}
render_canvas(state);
send_pack_cmd(state.block_field(), vec![selecting_table, bid])
} else {
state.dequeue()
}
}
// World
Msg::AddTable => {
let texture = block::table::Texture::new(&[2048, 2048], [20.0, 20.0]);
let texture = state.block_field_mut().add(texture);
let table = block::Table::new(texture.clone(), [20.0, 20.0], "テーブル");
let table = state.block_field_mut().add(table);
let world = state.world().clone();
state
.block_field_mut()
.update(&world, timestamp(), |world: &mut block::World| {
world.add_table(table.clone())
});
render_canvas(state);
send_pack_cmd(
state.block_field(),
vec![texture, table, state.world().clone()],
)
}
Msg::SetSelectingTable(table_id) => {
state.update_world(timestamp(), move |world| {
world.set_selecting_table(table_id);
});
render_canvas(state);
send_pack_cmd(state.block_field(), vec![state.world().clone()])
}
Msg::RemoveTable(table_id) => {
state.update_world(timestamp(), |world| {
world.remove_table(&table_id);
});
state.block_field_mut().remove(&table_id);
render_canvas(state);
send_pack_cmd(state.block_field(), vec![state.world().clone(), table_id])
}
Msg::AddTag => {
let tag = block::Tag::new();
let tag_id = state.block_field_mut().add(tag);
state.update_world(timestamp(), |world| {
world.add_tag(tag_id);
});
state.dequeue()
}
Msg::RemoveTag(tag_id) => {
state.update_world(timestamp(), |world| {
world.remove_tag(&tag_id);
});
state.block_field_mut().remove(&tag_id);
state.dequeue()
}
Msg::AddMemo(tag_id) => {
let mut memo = block::Memo::new();
if let Some(tag_id) = tag_id {
memo.add_tag(tag_id);
}
let memo_id = state.block_field_mut().add(memo);
state.update_world(timestamp(), |world| {
world.add_memo(memo_id);
});
state.dequeue()
}
Msg::RemoveMemo(memo_id) => {
state.update_world(timestamp(), |world| {
world.remove_memo(&memo_id);
});
state.block_field_mut().remove(&memo_id);
state.dequeue()
}
// Table
Msg::SetTableSize(table, size) => {
let mut texture_id = None;
state
.block_field_mut()
.update(&table, timestamp(), |table: &mut block::Table| {
table.set_size(size.clone());
texture_id = Some(table.drawing_texture_id().clone());
});
if let Some(texture_id) = texture_id {
state.block_field_mut().update(
&texture_id,
timestamp(),
|texture: &mut block::table::Texture| {
texture.set_size([size[0] as f64, size[1] as f64]);
},
);
}
render_canvas(state);
send_pack_cmd(state.block_field(), vec![table])
}
Msg::SetTableImage(table, image) => {
state
.block_field_mut()
.update(&table, timestamp(), |table: &mut block::Table| {
table.set_image_texture_id(image);
});
render_canvas(state);
send_pack_cmd(state.block_field(), vec![table])
}
Msg::SetTableName(table_id, name) => {
state
.block_field_mut()
.update(&table_id, timestamp(), |table: &mut block::Table| {
table.set_name(name);
});
send_pack_cmd(state.block_field(), vec![table_id])
}
Msg::SetTableIsShowingGrid(table_id, is_showing_grid) => {
state
.block_field_mut()
.update(&table_id, timestamp(), |table: &mut block::Table| {
table.set_is_showing_grid(is_showing_grid);
});
render_canvas(state);
send_pack_cmd(state.block_field(), vec![table_id])
}
Msg::SetTableIsBindToGrid(table_id, is_bind_to_grid) => {
state
.block_field_mut()
.update(&table_id, timestamp(), |table: &mut block::Table| {
table.set_is_bind_to_grid(is_bind_to_grid);
});
render_canvas(state);
send_pack_cmd(state.block_field(), vec![table_id])
}
// Tag
Msg::SetTagName(tag_id, name) => {
state
.block_field_mut()
.update(&tag_id, timestamp(), |tag: &mut block::Tag| {
tag.set_name(name);
});
state.dequeue()
}
// PersonalData
Msg::SetPersonalDataWithPlayerName(player_name) => {
state.personal_data_mut().set_name(player_name);
state.dequeue()
}
Msg::SetPersonalDataWithIconImageToCloseModal(r_id) => {
state.personal_data_mut().set_icon(Some(r_id));
state.close_modal();
state.dequeue()
}
// Tablemask
Msg::SetTablemaskSize(tablemask_id, size) => {
state.block_field_mut().update(
&tablemask_id,
timestamp(),
|tablemask: &mut block::table_object::Tablemask| {
tablemask.set_size(&size);
},
);
render_canvas(state);
send_pack_cmd(state.block_field(), vec![tablemask_id])
}
Msg::SetTablemaskColor(tablemask_id, color) => {
state.block_field_mut().update(
&tablemask_id,
timestamp(),
|tablemask: &mut block::table_object::Tablemask| {
tablemask.set_color(color);
},
);
render_canvas(state);
send_pack_cmd(state.block_field(), vec![tablemask_id])
}
Msg::SetTablemaskIsFixed(tablemask_id, is_fixed) => {
state.block_field_mut().update(
&tablemask_id,
timestamp(),
|tablemask: &mut block::table_object::Tablemask| {
tablemask.set_is_fixed(is_fixed);
},
);
render_canvas(state);
send_pack_cmd(state.block_field(), vec![tablemask_id])
}
Msg::SetTablemaskIsRounded(tablemask_id, is_rounded) => {
state.block_field_mut().update(
&tablemask_id,
timestamp(),
|tablemask: &mut block::table_object::Tablemask| {
tablemask.set_is_rounded(is_rounded);
},
);
render_canvas(state);
send_pack_cmd(state.block_field(), vec![tablemask_id])
}
Msg::SetTablemaskIsInved(tablemask_id, is_inved) => {
state.block_field_mut().update(
&tablemask_id,
timestamp(),
|tablemask: &mut block::table_object::Tablemask| {
tablemask.set_is_inved(is_inved);
},
);
render_canvas(state);
send_pack_cmd(state.block_field(), vec![tablemask_id])
}
// Boxblock
Msg::SetBoxblockSize(boxblock_id, size) => {
state.block_field_mut().update(
&boxblock_id,
timestamp(),
|boxblock: &mut block::table_object::Boxblock| {
boxblock.set_size(size);
},
);
render_canvas(state);
send_pack_cmd(state.block_field(), vec![boxblock_id])
}
Msg::SetBoxblockColor(boxblock_id, color) => {
state.block_field_mut().update(
&boxblock_id,
timestamp(),
|boxblock: &mut block::table_object::Boxblock| {
boxblock.set_color(color);
},
);
render_canvas(state);
send_pack_cmd(state.block_field(), vec![boxblock_id])
}
Msg::SetBoxblockIsFixed(boxblock_id, is_fixed) => {
state.block_field_mut().update(
&boxblock_id,
timestamp(),
|boxblock: &mut block::table_object::Boxblock| {
boxblock.set_is_fixed(is_fixed);
},
);
render_canvas(state);
send_pack_cmd(state.block_field(), vec![boxblock_id])
}
// Character
Msg::SetCharacterName(character, name) => {
state.block_field_mut().update(
&character,
timestamp(),
|character: &mut block::Character| {
character.set_name(name);
},
);
send_pack_cmd(state.block_field(), vec![character])
}
Msg::SetCharacterSize(character, [w, h]) => {
if let (Some(w), Some(h)) = (w, h) {
state.block_field_mut().update(
&character,
timestamp(),
|character: &mut block::Character| {
character.set_size([w, w, h]);
},
);
} else if let Some(Data::Image { element, .. }) = state
.block_field()
.get::<block::Character>(&character)
.and_then(|character| character.texture_id())
.and_then(|t_id| state.resource().get(t_id))
{
let iw = element.width() as f32;
let ih = element.height() as f32;
if let Some(w) = w {
let h = w / iw * ih;
state.block_field_mut().update(
&character,
timestamp(),
|character: &mut block::Character| {
character.set_size([w, w, h]);
},
);
}
if let Some(h) = h {
let w = h / ih * iw;
state.block_field_mut().update(
&character,
timestamp(),
|character: &mut block::Character| {
character.set_size([w, w, h]);
},
);
}
}
render_canvas(state);
send_pack_cmd(state.block_field(), vec![character])
}
Msg::SetCharacterTextrureToCloseModal(character_id, texture_id) => {
state.close_modal();
state.block_field_mut().update(
&character_id,
timestamp(),
|character: &mut block::Character| {
character.set_texture_id(texture_id);
},
);
render_canvas(state);
send_pack_cmd(state.block_field(), vec![character_id])
}
Msg::SetCharacterPosition(character_id, pos) => {
state.block_field_mut().update(
&character_id,
timestamp(),
|character: &mut block::Character| {
character.set_position(pos);
},
);
render_canvas(state);
send_pack_cmd(state.block_field(), vec![character_id])
}
Msg::SetCharacterIsHidden(character_id, is_hidden) => {
state.block_field_mut().update(
&character_id,
timestamp(),
|character: &mut block::Character| {
character.set_is_hidden(is_hidden);
},
);
render_canvas(state);
send_pack_cmd(state.block_field(), vec![character_id])
}
// Property
Msg::AddChildToProprty(property_id) => {
let child_property = block::Property::new("");
let child_property_id = state.block_field_mut().add(child_property);
state.block_field_mut().update(
&property_id,
timestamp(),
|property: &mut block::Property| {
property.add_child(child_property_id.clone());
},
);
send_pack_cmd(state.block_field(), vec![property_id, child_property_id])
}
Msg::SetPropertyName(property_id, name) => {
state.block_field_mut().update(
&property_id,
timestamp(),
|property: &mut block::Property| {
property.set_name(name);
},
);
send_pack_cmd(state.block_field(), vec![property_id])
}
Msg::SetPropertyValue(property_id, mut value) => {
if let block::property::Value::Children(children) = &mut value {
if children.is_empty() {
let none = block::Property::new("");
let none = state.block_field_mut().add(none);
children.push(none);
}
}
state.block_field_mut().update(
&property_id,
timestamp(),
|property: &mut block::Property| {
property.set_value(value);
},
);
send_pack_cmd(state.block_field(), vec![property_id])
}
Msg::SetPropertyIsSelected(property_id, is_selected) => {
state.block_field_mut().update(
&property_id,
timestamp(),
|property: &mut block::Property| {
property.set_is_selected(is_selected);
},
);
send_pack_cmd(state.block_field(), vec![property_id])
}
Msg::SetPropertyIsCollapsed(property_id, is_collapsed) => {
state.block_field_mut().update(
&property_id,
timestamp(),
|property: &mut block::Property| {
property.set_is_collapsed(is_collapsed);
},
);
state.dequeue()
}
Msg::RemoveProperty(parent_id, self_id) => {
state.block_field_mut().update(
&parent_id,
timestamp(),
|property: &mut block::Property| {
property.remove_child(&self_id);
},
);
state.block_field_mut().remove(&self_id);
send_pack_cmd(state.block_field(), vec![parent_id, self_id])
}
// Chat
Msg::SetInputingChatMessage(msg) => {
state.chat_mut().set_inputing_message(msg);
state.dequeue()
}
Msg::SendInputingChatMessage => {
use block::chat::item::Icon;
use block::chat::item::Sender;
let sender = state.chat().selecting_sender().clone();
let (display_name, character_id, icon) = match &sender {
Sender::User => (
Some(state.personal_data().name().clone()),
None,
state.personal_data().icon().map(|r_id| r_id.clone()),
),
Sender::Character(character_id) => {
if let Some(character) =
state.block_field().get::<block::Character>(character_id)
{
(
Some(character.name().clone()),
Some(character_id.clone()),
character.texture_id().map(|r_id| r_id.clone()),
)
} else {
(None, None, None)
}
}
_ => (None, None, None),
};
if let (Some(display_name), Some(tab)) = (display_name, state.selecting_chat_tab_id()) {
let tab = tab.clone();
let text = state.chat_mut().drain_inputing_message();
let (left, _) = state.dicebot().delimit(&text);
let left = left.to_string();
let icon = icon
.map(|r_id| Icon::Resource(r_id))
.unwrap_or(Icon::DefaultUser);
let peer_id = state.peer().id();
if text != "" {
if let Some(left) = state.dicebot().bcdice().match_to_prefix(&left) {
let left = js_sys::encode_uri_component(&left).as_string().unwrap();
let query = state
.dicebot()
.bcdice()
.system_info()
.map(|si| format!("?system={}&command={}", si.game_type(), &left))
.unwrap_or(format!("?system=DiceBot&command={}", &left));
Cmd::task(task::http::get(
state.dicebot().bcdice().server() + r"/v1/diceroll" + &query,
task::http::Props::new(),
move |response| {
let result = if let Some(diceroll) =
response.ok().and_then(|r| r.text).and_then(|text| {
serde_json::from_str::<bcdice::DiceRoll>(&text).ok()
}) {
Some(diceroll.result().clone())
} else {
None
};
let item = block::chat::Item::new(
peer_id.clone(),
display_name.clone(),
icon.clone(),
sender.clone(),
text.clone(),
result,
);
Msg::InsertChatItem(tab.clone(), item, js_sys::Date::now())
},
))
} else {
let item =
block::chat::Item::new(peer_id, display_name, icon, sender, text, None);
update(state, Msg::InsertChatItem(tab, item, js_sys::Date::now()))
}
} else {
state.dequeue()
}
} else {
state.dequeue()
}
}
Msg::InsertChatItem(tab_id, item, timestamp) => {
let item_id = state.block_field_mut().add(item);
state
.block_field_mut()
.update(&tab_id, None, |tab: &mut block::chat::Tab| {
tab.insert(timestamp, item_id.clone());
});
state.room().send(skyway::Msg::InsertChatItem(
tab_id.to_id(),
item_id.to_id(),
timestamp,
));
send_pack_cmd(state.block_field(), vec![item_id])
}
Msg::AddChatSender(character_id) => {
state.chat_mut().add_sender(character_id);
state.dequeue()
}
Msg::RemoveChatSender(character_id) => {
state.chat_mut().remove_sender(&character_id);
state.dequeue()
}
Msg::SetSelectingChatSenderIdx(idx) => {
state.chat_mut().set_selecting_sender_idx(idx);
state.dequeue()
}
Msg::AddChatTab => {
let tab = block::chat::Tab::new("タブ");
let tab_id = state.block_field_mut().add(tab);
state.update_chat_block(timestamp(), |chat| {
chat.push(tab_id.clone());
});
send_pack_cmd(
state.block_field(),
vec![state.chat().block_id().clone(), tab_id],
)
}
Msg::SetSelectingChatTabIdx(idx) => {
state.chat_mut().set_selecting_tab_idx(idx);
state.dequeue()
}
Msg::SetChatTabName(tab_id, name) => {
state
.block_field_mut()
.update(&tab_id, timestamp(), |tab: &mut block::chat::Tab| {
tab.set_name(name);
});
send_pack_cmd(state.block_field(), vec![tab_id])
}
Msg::RemoveChatTab(tab) => {
state.update_chat_block(timestamp(), |chat| {
if let Some(tab_idx) = chat.iter().position(|t| tab == *t) {
if chat.len() > 1 {
chat.remove(tab_idx);
}
}
});
state.dequeue()
}
// 共有メモ
Msg::SetMemoName(memo_id, name) => {
state
.block_field_mut()
.update(&memo_id, timestamp(), |memo: &mut block::Memo| {
memo.set_name(name);
});
state.dequeue()
}
Msg::SetMemoText(memo_id, text) => {
state
.block_field_mut()
.update(&memo_id, timestamp(), |memo: &mut block::Memo| {
memo.set_text(text);
});
state.dequeue()
}
// ブロックフィールド
Msg::AssignFieldBlocks(blocks) => {
for (id, block) in blocks {
state.block_field_mut().assign_fb(id, block);
}
render_canvas(state);
state.dequeue()
}
// リソース
Msg::LoadFromFileList(file_list) => {
let len = file_list.length();
for i in 0..len {
if let Some(file) = file_list.item(i) {
let file_type = file.type_();
if Data::is_able_to_load(&file_type) {
let blob: web_sys::Blob = file.into();
let promise = Data::from_blob(blob);
let task = Cmd::task(move |resolve| {
promise.then(|data| {
if let Some(data) = data {
resolve(Msg::LoadDataToResource(data));
}
})
});
state.enqueue(task);
} else if file_type == "application/zip"
|| file_type == "application/x-zip-compressed"
{
let promise = udonarium::Character::from_blob(&file);
let task = Cmd::task(move |resolve| {
promise.then(|data| {
if let Some(data) = data {
resolve(Msg::LoadUdonariumCharacter(data));
}
});
});
state.enqueue(task);
}
}
}
state.dequeue()
}
Msg::LoadDataToResource(data) => {
let promise = data.pack();
let id = state.resource_mut().add(data);
Cmd::task(move |resolve| {
promise.then(move |data| {
if let Some(data) = data {
resolve(Msg::SendResourcePacks(
vec![(id, data)].into_iter().collect(),
))
}
})
})
}
Msg::AssignDataToResource(id, data) => {
state.resource_mut().assign(id, data);
render_canvas(state);
state.dequeue()
}
//BCDice
Msg::GetBcdiceServerList => Cmd::task(task::http::get(
r"https://raw.githubusercontent.com/bcdice/bcdice-api-servers/master/servers.yaml",
task::http::Props::new(),
|response| {
if let Some(servers) = response
.ok()
.and_then(|r| r.text)
.and_then(|text| serde_yaml::from_str(&text).ok())
{
Msg::SetBcdiceServerList(servers)
} else {
Msg::NoOp
}
},
)),
Msg::SetBcdiceServerList(servers) => {
state.dicebot_mut().bcdice_mut().set_servers(servers);
if !state.dicebot().bcdice().server().is_empty() {
Cmd::task(|r| r(Msg::GetBcdiceSystemNames))
} else {
state.dequeue()
}
}
Msg::GetBcdiceSystemNames => Cmd::task(task::http::get(
state.dicebot().bcdice().server() + r"/v1/names",
task::http::Props::new(),
|response| {
if let Some(names) = response
.ok()
.and_then(|r| r.text)
.and_then(|text| serde_json::from_str(&text).ok())
{
Msg::SetBcdiceSystemNames(names)
} else {
Msg::GetBcdiceServerList
}
},
)),
Msg::SetBcdiceSystemNames(names) => {
state.dicebot_mut().bcdice_mut().set_names(names);
state.dequeue()
}
Msg::GetBcdiceSystemInfo(system) => Cmd::task(task::http::get(
state.dicebot().bcdice().server() + r"/v1/systeminfo?system=" + &system,
task::http::Props::new(),
|response| {
if let Some(system_info) = response
.ok()
.and_then(|r| r.text)
.and_then(|text| serde_json::from_str(&text).ok())
{
Msg::SetBcdiceSystemInfo(system_info)
} else {
Msg::NoOp
}
},
)),
Msg::SetBcdiceSystemInfo(system_info) => {
state
.dicebot_mut()
.bcdice_mut()
.set_system_info(system_info);
state.dequeue()
}
// IDB
Msg::LoadToOpenTable(table_id, blocks, resources) => {
let mut block_ids = vec![state.world().clone()];
state.update_world(timestamp(), |world| {
let selecting_table = world.selecting_table().clone();
world.replace_table(&selecting_table, table_id.clone());
world.set_selecting_table(table_id);
});
for (id, block) in blocks {
block_ids.push(id.clone());
state.block_field_mut().assign_fb(id, block);
}
let mut r_ids = vec![];
for (r_id, data) in resources {
r_ids.push(r_id.clone());
state.resource_mut().assign(r_id, data);
}
render_canvas(state);
state.enqueue(send_pack_cmd(state.block_field(), block_ids));
let promise = state.resource().pack_listed(r_ids);
state.enqueue(Cmd::task({
let room = state.room();
move |_| {
promise.then(move |packs| {
if let Some(packs) = packs {
room.send(skyway::Msg::SetResourcePacks(packs.into_iter().collect()));
}
})
}
}));
state.dequeue()
}
// Udonarium互換
Msg::LoadUdonariumCharacter(character) => Cmd::task(move |resolve| {
character.texture().then(|texture| {
resolve(Msg::AddCharacterWithUdonariumData(character.data, texture))
})
}),
Msg::AddCharacterWithUdonariumData(data, texture) => {
let name = match data.find("name") {
Some(udonarium::data::Value::Text(name)) => name.clone(),
_ => String::new(),
};
let size = match data.find("size") {
Some(udonarium::data::Value::Text(size)) => size.parse().unwrap_or(1.0),
_ => 1.0,
};
let mut property = block::Property::new("");
property.set_value(block::property::Value::Children(vec![]));
if let Some(data) = data.find("detail") {
if let udonarium::data::Value::Children(children) = data {
for child in children {
if let Some(child) =
property_from_udonarium_data(state.block_field_mut(), child)
{
property.add_child(child);
}
}
}
}
let property_id = state.block_field_mut().add(property);
let mut character = block::Character::new(
property_id.clone(),
name,
state.client_id().as_ref().clone(),
);
if let Some(texture) = texture {
let size_ratio = texture
.as_image()
.map(|el| el.height() as f32 / el.width() as f32)
.unwrap_or(0.0);
let promise = texture.pack();
let texture_id = state.resource_mut().add(texture);
character.set_texture_id(Some(texture_id.clone()));
state.enqueue(Cmd::task(move |resolve| {
promise.then(move |data| {
if let Some(data) = data {
resolve(Msg::SendResourcePacks(
vec![(texture_id, data)].into_iter().collect(),
))
}
})
}));
character.set_size([size, size, size * size_ratio]);
} else {
character.set_size([size, size, 0.0]);
}
let character_id = state.block_field_mut().add(character);
state.update_world(timestamp(), |world| {
world.add_character(character_id.clone());
});
render_canvas(state);
send_pack_cmd(
state.block_field(),
vec![property_id, character_id, state.world().clone()],
)
}
// 接続に関する操作
Msg::SendBlockPacks(packs) => {
let packs = packs
.into_iter()
.map(|(id, data)| (id.to_id(), data))
.collect();
state.room().send(skyway::Msg::SetBlockPacks(packs));
state.dequeue()
}
Msg::SendResourcePacks(packs) => {
state.room().send(skyway::Msg::SetResourcePacks(packs));
state.dequeue()
}
Msg::ReceiveMsg(msg) => match msg {
skyway::Msg::None => state.dequeue(),
skyway::Msg::SetContext { chat, world } => {
let chat = state.block_field_mut().block_id(chat);
let world = state.block_field_mut().block_id(world);
state.chat_mut().set_block_id(chat);
state.set_world(world);
Cmd::task(|resolve| resolve(Msg::InitDomDependents))
}
skyway::Msg::SetBlockPacks(packs) => {
let promise = state.block_field_mut().unpack_listed(packs.into_iter());
Cmd::task(move |resolve| {
promise.then(move |blocks| {
blocks.map(move |blocks| resolve(Msg::AssignFieldBlocks(blocks)));
});
})
}
skyway::Msg::SetResourcePacks(packs) => {
for (id, data) in packs {
let promise = Data::unpack(data);
let task = Cmd::task(move |resolve| {
promise.then(move |data| {
if let Some(data) = data {
resolve(Msg::AssignDataToResource(id, data));
}
})
});
state.enqueue(task);
}
state.dequeue()
}
skyway::Msg::InsertChatItem(tab_id, item_id, timestamp) => {
let tab_id = state.block_field_mut().block_id(tab_id);
let item_id = state.block_field_mut().block_id(item_id);
state
.block_field_mut()
.update(&tab_id, None, |tab: &mut block::chat::Tab| {
tab.insert(timestamp, item_id);
});
state.dequeue()
}
skyway::Msg::DrawLine {
texture,
ax,
ay,
bx,
by,
color,
line_width,
} => {
let texture_id = state.block_field_mut().block_id(texture);
draw_line_to_table(state, &texture_id, ax, ay, bx, by, &color, line_width);
render_canvas(state);
state.dequeue()
}
skyway::Msg::EraceLine {
texture,
ax,
ay,
bx,
by,
line_width,
} => {
let texture_id = state.block_field_mut().block_id(texture);
erace_line_of_texture(state, &texture_id, ax, ay, bx, by, line_width);
render_canvas(state);
state.dequeue()
}
skyway::Msg::ClearTable { texture } => {
let texture_id = state.block_field_mut().block_id(texture);
state.block_field_mut().update(
&texture_id,
timestamp(),
|texture: &mut block::table::Texture| {
texture.clear();
},
);
render_canvas(state);
state.dequeue()
}
},
Msg::PeerJoin(peer_id) => {
state.peers_mut().insert(peer_id);
let chat = state.chat().block_id().to_id();
let world = state.world().to_id();
state.room().send(skyway::Msg::SetContext { chat, world });
let packs = state.resource().pack_all();
state.enqueue(Cmd::task(move |resolve| {
packs.then(|packs| {
if let Some(packs) = packs {
resolve(Msg::SendResourcePacks(packs.into_iter().collect()));
}
})
}));
let packs = state.block_field_mut().pack_all();
Cmd::task(move |resolve| {
packs.then(|packs| {
if let Some(packs) = packs {
resolve(Msg::SendBlockPacks(packs.into_iter().collect()));
}
})
})
}
Msg::PeerLeave(peer_id) => {
state.peers_mut().remove(&peer_id);
state.dequeue()
}
Msg::DisconnectFromRoom => Cmd::Sub(Sub::DisconnectFromRoom),
}
}
fn get_element_by_id(id: &str) -> Option<web_sys::Element> {
web_sys::window()
.unwrap()
.document()
.unwrap()
.get_element_by_id(id)
}
fn get_table_canvas_element() -> Option<web_sys::HtmlCanvasElement> {
get_element_by_id("table").and_then(|x| x.dyn_into::<web_sys::HtmlCanvasElement>().ok())
}
fn reset_canvas_size(pixel_ratio: f32) -> Option<[f32; 2]> {
if let Some(canvas) = get_table_canvas_element() {
let canvas_size = [
canvas.client_width() as f32 * pixel_ratio,
canvas.client_height() as f32 * pixel_ratio,
];
canvas.set_width(canvas_size[0] as u32);
canvas.set_height(canvas_size[1] as u32);
Some(canvas_size)
} else {
None
}
}
fn get_table_position(
state: &State,
ignore_binding: bool,
screen_position: &[f32; 2],
pixel_ratio: f32,
) -> [f32; 2] {
let mouse_coord = [
screen_position[0] * pixel_ratio,
screen_position[1] * pixel_ratio,
];
let p = state
.camera()
.collision_point_on_xy_plane(state.canvas_size(), &mouse_coord);
if state
.block_field()
.get::<block::World>(state.world())
.and_then(|w| state.block_field().get::<block::Table>(w.selecting_table()))
.map(|t| t.is_bind_to_grid())
.unwrap_or(false)
&& (!ignore_binding)
{
[(p[0] * 2.0).round() / 2.0, (p[1] * 2.0).round() / 2.0]
} else {
[p[0], p[1]]
}
}
fn get_focused_position(
state: &State,
screen_position: &[f32; 2],
pixel_ratio: f32,
offset: &[f32; 3],
) -> [f32; 3] {
let canvas_pos = [
screen_position[0] * pixel_ratio,
screen_position[1] * pixel_ratio,
];
let pos = if let Some(tableblock) = state.renderer().and_then(|r| {
r.table_object_id(state.canvas_size(), &canvas_pos)
.map(|t| t.clone())
}) {
if let Some(boxblock) = state
.block_field()
.get::<block::table_object::Boxblock>(&tableblock.block_id)
{
let (r, s, t) =
box_surface(boxblock.position(), boxblock.size(), tableblock.surface_idx);
let p = state
.camera()
.collision_point(state.canvas_size(), &canvas_pos, &r, &s, &t);
let p = bind_to_grid(state, false, &p);
let p = match tableblock.surface_idx {
0 => [p[0], p[1], p[2] + offset[2]],
1 => [p[0], p[1] + offset[1], p[2]],
2 => [p[0] + offset[0], p[1], p[2]],
3 => [p[0] - offset[0], p[1], p[2]],
4 => [p[0], p[1] - offset[1], p[2]],
5 => [p[0], p[1], p[2] - offset[2]],
_ => unreachable!(),
};
Some(p)
} else if let Some(character) = state
.block_field()
.get::<block::Character>(&tableblock.block_id)
{
let r = character.position();
let s = [1.0, 0.0, 0.0];
let t = [0.0, 1.0, 0.0];
let p = state
.camera()
.collision_point(state.canvas_size(), &canvas_pos, &r, &s, &t);
let p = bind_to_grid(state, false, &p);
let p = [p[0], p[1], p[2] + offset[2]];
Some(p)
} else {
None
}
} else {
None
};
pos.unwrap_or({
let [x, y] = get_table_position(state, false, screen_position, pixel_ratio);
[x, y, offset[2]]
})
}
fn box_surface(p: &[f32; 3], s: &[f32; 3], s_idx: usize) -> ([f32; 3], [f32; 3], [f32; 3]) {
match s_idx {
0 => {
let r = [p[0], p[1], p[2] + s[2] * 0.5];
let s = [1.0, 0.0, 0.0];
let t = [0.0, 1.0, 0.0];
(r, s, t)
}
1 => {
let r = [p[0], p[1] + s[1] * 0.5, p[2]];
let s = [1.0, 0.0, 0.0];
let t = [0.0, 0.0, 1.0];
(r, s, t)
}
2 => {
let r = [p[0] + s[0] * 0.5, p[1], p[2]];
let s = [0.0, 1.0, 0.0];
let t = [0.0, 0.0, 1.0];
(r, s, t)
}
3 => {
let r = [p[0] - s[0] * 0.5, p[1], p[2]];
let s = [0.0, 1.0, 0.0];
let t = [0.0, 0.0, 1.0];
(r, s, t)
}
4 => {
let r = [p[0], p[1] - s[1] * 0.5, p[2]];
let s = [1.0, 0.0, 0.0];
let t = [0.0, 0.0, 1.0];
(r, s, t)
}
5 => {
let r = [p[0], p[1], p[2] - s[2] * 0.5];
let s = [1.0, 0.0, 0.0];
let t = [0.0, 1.0, 0.0];
(r, s, t)
}
_ => unreachable!(),
}
}
fn bind_to_grid(state: &State, ignore_binding: bool, p: &[f32; 3]) -> [f32; 3] {
if state
.block_field()
.get::<block::World>(state.world())
.and_then(|w| state.block_field().get::<block::Table>(w.selecting_table()))
.map(|t| t.is_bind_to_grid())
.unwrap_or(false)
&& (!ignore_binding)
{
[
(p[0] * 2.0).round() / 2.0,
(p[1] * 2.0).round() / 2.0,
(p[2] * 2.0).round() / 2.0,
]
} else {
[p[0], p[1], p[2]]
}
}
fn render_canvas(state: &mut State) {
state.render();
}
fn timestamp() -> Option<f64> {
Some(js_sys::Date::now())
}
fn send_pack_cmd(block_field: &block::Field, packs: Vec<BlockId>) -> Cmd<Msg, Sub> {
let packs = block_field.pack_listed(packs);
Cmd::task(move |resolve| {
packs.then(|packs| {
if let Some(packs) = packs {
resolve(Msg::SendBlockPacks(packs.into_iter().collect()));
}
})
})
}
fn clone_prop(block_field: &mut block::Field, prop: &BlockId) -> Option<block::Property> {
let mut prop = if let Some(prop) = block_field.get::<block::Property>(prop) {
Some(prop.clone())
} else {
None
};
if let Some(prop) = &mut prop {
if let block::property::Value::Children(children) = prop.value() {
let mut new_children = vec![];
for child in children {
let child = clone_prop(block_field, child);
if let Some(child) = child {
let child = block_field.add(child);
new_children.push(child);
}
}
prop.set_value(block::property::Value::Children(new_children));
}
}
prop
}
fn trace_prop_id(block_field: &block::Field, prop: &BlockId) -> Vec<BlockId> {
let mut prop_ids = vec![prop.clone()];
if let Some(block::property::Value::Children(children)) =
block_field.get::<block::Property>(&prop).map(|p| p.value())
{
for child in children {
let child_children = trace_prop_id(block_field, child);
for child_child in child_children {
prop_ids.push(child_child);
}
}
}
prop_ids
}
fn check_focused_object(state: &mut State, mouse_position: &[f32; 2]) {
let pixel_ratio = state.pixel_ratio();
let canvas_pos = [
mouse_position[0] * pixel_ratio,
mouse_position[1] * pixel_ratio,
];
if let Some(tableblock) = state.renderer().and_then(|r| {
r.table_object_id(state.canvas_size(), &canvas_pos)
.map(|t| t.clone())
}) {
if state
.block_field()
.get::<block::Character>(&tableblock.block_id)
.is_some()
{
let table = state.table_mut();
table.set_focused(state::table::Focused::Character(tableblock.clone()));
} else if state
.block_field()
.get::<block::table_object::Tablemask>(&tableblock.block_id)
.is_some()
{
let table = state.table_mut();
table.set_focused(state::table::Focused::Tablemask(tableblock.clone()));
} else if state
.block_field()
.get::<block::table_object::Area>(&tableblock.block_id)
.is_some()
{
let table = state.table_mut();
table.set_focused(state::table::Focused::Area(tableblock.clone()));
} else if state
.block_field()
.get::<block::table_object::Boxblock>(&tableblock.block_id)
.is_some()
{
let table = state.table_mut();
table.set_focused(state::table::Focused::Boxblock(tableblock.clone()));
}
} else {
state.table_mut().set_focused(state::table::Focused::None);
}
}
fn property_from_udonarium_data(
block_field: &mut block::Field,
data: &udonarium::Data,
) -> Option<BlockId> {
use udonarium::data::Value;
let name = data.name.clone();
match &data.value {
Value::Text(text) => {
if let Ok(num) = text.parse() {
let mut prop = block::Property::new(name);
prop.set_value(block::property::Value::Num(num));
Some(block_field.add(prop))
} else if data.type_ == "note" {
None
} else {
let mut prop = block::Property::new(name);
prop.set_value(block::property::Value::Str(text.clone()));
Some(block_field.add(prop))
}
}
Value::None => {
let mut prop = block::Property::new(name);
prop.set_value(block::property::Value::Str(String::new()));
Some(block_field.add(prop))
}
Value::Children(children) => {
let mut prop = block::Property::new(name);
prop.set_is_collapsed(false);
prop.set_value(block::property::Value::Children(vec![]));
for child in children {
if let Some(child) = property_from_udonarium_data(block_field, child) {
prop.add_child(child);
}
}
Some(block_field.add(prop))
}
}
}
fn draw_line_to_table(
state: &mut State,
texture_id: &BlockId,
ax: f32,
ay: f32,
bx: f32,
by: f32,
color: &Color,
line_width: f64,
) {
state.block_field_mut().update(
texture_id,
timestamp(),
|texture: &mut block::table::Texture| {
let [ax, ay] = texture.texture_position(&[ax as f64, ay as f64]);
let [bx, by] = texture.texture_position(&[bx as f64, by as f64]);
let context = texture.context();
context.set_line_width(line_width);
context.set_line_cap("round");
context.set_stroke_style(&color.to_jsvalue());
context
.set_global_composite_operation("source-over")
.unwrap();
context.begin_path();
context.move_to(ax, ay);
context.line_to(bx, by);
context.fill();
context.stroke();
},
);
}
fn erace_line_of_texture(
state: &mut State,
texture_id: &BlockId,
ax: f32,
ay: f32,
bx: f32,
by: f32,
line_width: f64,
) {
state.block_field_mut().update(
&texture_id,
timestamp(),
|texture: &mut block::table::Texture| {
let [ax, ay] = texture.texture_position(&[ax as f64, ay as f64]);
let [bx, by] = texture.texture_position(&[bx as f64, by as f64]);
let context = texture.context();
context.set_line_width(line_width);
context.set_line_cap("round");
context.set_stroke_style(&color_system::gray(255, 9).to_jsvalue());
context
.set_global_composite_operation("destination-out")
.unwrap();
context.begin_path();
context.move_to(ax, ay);
context.line_to(bx, by);
context.fill();
context.stroke();
},
);
}
|
use iron::prelude::*;
use serde_json::Value;
use common::http::*;
use common::utils::*;
use common::utils::is_admin as check_is_admin;
use services::user::{get_username, get_user, get_user_id};
use services::topic::*;
use services::topic::create_topic as service_create_topic;
use services::topic::delete_topic as service_delete_topic;
use services::comment::{get_comments_by_topic_id};
use services::category::get_categories;
use services::collection::*;
use services::collection::is_collected as collection_is_collected;
use services::topic_vote::*;
use services::topic_vote::is_agreed as topic_is_agreed;
use services::topic_vote::is_disagreed as topic_is_disagreed;
use services::comment_vote::is_agreed as comment_is_agreed;
use services::comment_vote::is_disagreed as comment_is_disagreed;
use models::comment::Comment;
use models::category::Category;
use controllers::upload::sync_upload_file;
pub fn render_topic(req: &mut Request) -> IronResult<Response> {
let is_login = is_login(req);
let params = get_router_params(req);
let topic_id = params.find("topic_id").unwrap();
let topic_wrapper = get_topic(topic_id);
if topic_wrapper.is_none() {
return redirect_to("/not-found");
}
let mut user_id_string = "".to_string();
let mut cur_username = "".to_string();
if is_login { // 用户已登录
let session = get_session_obj(req);
let username = session["username"].as_str().unwrap();
user_id_string = get_user_id(username).to_string();
cur_username = username.to_string();
}
let user_id = &*user_id_string;
let mut topic = topic_wrapper.unwrap();
increment_topic_view_count(topic_id);
let author_id = topic.user_id;
let author_name = get_username(author_id).unwrap();
let author = get_user(&*author_name).unwrap();
let mut data = ViewData::new(req);
topic.content = parse_to_html(&*topic.content);
let comments = get_comments_by_topic_id(topic_id);
let related_topics = get_user_other_topics(author_id, topic_id);
let mut is_collected = false;
let mut is_agreed = false;
let mut is_disagreed = false;
let mut is_admin = false;
if user_id != "" { // 用户已登录
is_collected = collection_is_collected(user_id, topic_id);
is_agreed = topic_is_agreed(user_id, topic_id);
is_disagreed = topic_is_disagreed(user_id, topic_id);
is_admin = check_is_admin(&*cur_username);
}
let list = rebuild_comments(&*author_name, user_id, is_admin, &comments);
data.insert("title", json!(topic.title));
data.insert("is_login", json!(is_login));
data.insert("is_topic_page", json!(true));
data.insert("topic", json!(topic));
data.insert("is_admin", json!(is_admin));
data.insert("is_user_self", json!(&*author_id.to_string() == user_id));
data.insert("is_collected", json!(is_collected));
data.insert("is_agreed", json!(is_agreed));
data.insert("is_disagreed", json!(is_disagreed));
data.insert("comments", json!(list));
data.insert("comment_count", json!(list.len()));
data.insert("author", json!(author));
data.insert("related_topics", json!(related_topics));
data.insert("is_has_related_topics", json!(related_topics.len() != 0));
respond_view("topic", &data)
}
fn rebuild_comments(author_name: &str, user_id: &str, is_admin: bool, comments: &Vec<Comment>) -> Vec<Value> {
let mut vec = Vec::new();
let mut index = 0;
if user_id == "" { // 用户未登录
for comment in comments.into_iter() {
index = index + 1;
vec.push(json!({
"index": index,
"comment": comment,
"is_author": author_name == comment.username,
"is_admin": false,
"is_user_self": false,
"is_highlight": comment.agree_count >= 10,
"is_agreed": false,
"is_disagreed": false
}));
}
} else {
for comment in comments.into_iter() {
index = index + 1;
vec.push(json!({
"index": index,
"comment": comment,
"is_author": author_name == comment.username,
"is_admin": is_admin,
"is_user_self": user_id == &*comment.user_id.to_string(),
"is_highlight": comment.agree_count >= 10,
"is_agreed": comment_is_agreed(user_id, &*comment.id),
"is_disagreed": comment_is_disagreed(user_id, &*comment.id)
}));
}
}
vec
}
pub fn render_create_topic(req: &mut Request) -> IronResult<Response> {
let mut data = ViewData::new(req);
let categories = get_categories();
let list = rebuild_categories(0, &categories);
data.insert("title", json!("发布话题"));
data.insert("categories", json!(list));
respond_view("topic-editor", &data)
}
pub fn render_edit_topic(req: &mut Request) -> IronResult<Response> {
let params = get_router_params(req);
let topic_id = params.find("topic_id").unwrap();
if !is_topic_created(topic_id) {
return redirect_to("/not-found");
}
let topic_wrapper = get_topic(topic_id);
if topic_wrapper.is_none() {
return redirect_to("/not-found");
}
let topic = topic_wrapper.unwrap();
let categories = get_categories();
let list = rebuild_categories(topic.category_id, &categories);
let mut data = ViewData::new(req);
data.insert("title", json!("编辑话题"));
data.insert("topic", json!(&topic));
data.insert("categories", json!(list));
respond_view("topic-editor", &data)
}
fn rebuild_categories(category_id: u8, categories: &Vec<Category>) -> Vec<Value> {
let mut vec = Vec::new();
for category in categories.into_iter() {
vec.push(json!({
"category": category,
"is_selected": category_id == category.id
}));
}
vec
}
pub fn create_topic(req: &mut Request) -> IronResult<Response> {
let session = get_session_obj(req);
let params = get_request_body(req);
let user_id = session["id"].as_u64().unwrap();
let category = ¶ms.get("category").unwrap()[0];
let title = ¶ms.get("title").unwrap()[0];
let content = ¶ms.get("content").unwrap()[0];
let obj = json!({
"user_id": user_id,
"category_id": category.to_owned(),
"title": title.to_owned(),
"content": sync_upload_file(content)
});
let result = service_create_topic(&obj);
let mut data = JsonData::new();
if result.is_none() {
data.success = false;
data.message = "发布话题失败".to_string();
return respond_json(&data);
}
let topic_id = result.unwrap();
data.message = "发布话题成功".to_owned();
data.data = json!("/topic/".to_string() + &*topic_id);
respond_json(&data)
}
pub fn edit_topic(req: &mut Request) -> IronResult<Response> {
let params = get_router_params(req);
let body = get_request_body(req);
let topic_id = params.find("topic_id").unwrap();
let category = &body.get("category").unwrap()[0];
let title = &body.get("title").unwrap()[0];
let content = &body.get("content").unwrap()[0];
let mut data = JsonData::new();
if !is_topic_created(topic_id) {
data.success = false;
data.message = "未找到该话题".to_owned();
return respond_json(&data);
}
let result = update_topic(topic_id, &json!({
"category_id": category.to_owned(),
"title": title.to_owned(),
"content": sync_upload_file(content)
}));
if result.is_none() {
data.success = false;
data.message = "修改话题失败".to_owned();
return respond_json(&data);
}
data.message = "修改话题成功".to_owned();
data.data = json!("/topic/".to_string() + topic_id);
respond_json(&data)
}
pub fn delete_topic(req: &mut Request) -> IronResult<Response> {
let params = get_router_params(req);
let topic_id = params.find("topic_id").unwrap();
let mut data = JsonData::new();
if !is_topic_created(topic_id) {
data.success = false;
data.message = "未找到该话题".to_owned();
return respond_json(&data);
}
let result = service_delete_topic(topic_id);
if result.is_none() {
data.success = false;
data.message = "删除话题失败".to_owned();
return respond_json(&data);
}
data.message = "删除话题成功".to_owned();
data.data = json!("/");
respond_json(&data)
}
pub fn collect_topic(req: &mut Request) -> IronResult<Response> {
let params = get_router_params(req);
let topic_id = params.find("topic_id").unwrap();
let body = get_request_body(req);
let user_id = &body.get("userId").unwrap()[0];
let is_collect = &body.get("isCollect").unwrap()[0];
let result;
if is_collect == "true" {
if !is_collected(user_id, topic_id) {
result = create_collection(user_id, topic_id);
} else {
result = None;
}
} else {
result = delete_collection(user_id, topic_id);
}
let mut data = JsonData::new();
if result.is_none() {
data.success = false;
data.message = "更新收藏失败".to_owned();
}
respond_json(&data)
}
pub fn stick_topic(req: &mut Request) -> IronResult<Response> {
let params = get_router_params(req);
let topic_id = params.find("topic_id").unwrap();
let body = get_request_body(req);
let is_stick = &body.get("isSticked").unwrap()[0];
let result;
if is_stick == "true" {
result = update_topic_sticky(topic_id, 1);
} else {
result = update_topic_sticky(topic_id, 0);
}
let mut data = JsonData::new();
if result.is_none() {
data.success = false;
data.message = "更新置顶失败".to_owned();
}
respond_json(&data)
}
pub fn essence_topic(req: &mut Request) -> IronResult<Response> {
let params = get_router_params(req);
let topic_id = params.find("topic_id").unwrap();
let body = get_request_body(req);
let is_essence = &body.get("isEssenced").unwrap()[0];
let result;
if is_essence == "true" {
result = update_topic_essence(topic_id, 1);
} else {
result = update_topic_essence(topic_id, 0);
}
let mut data = JsonData::new();
if result.is_none() {
data.success = false;
data.message = "更新精华失败".to_owned();
}
respond_json(&data)
}
pub fn vote_topic(req: &mut Request) -> IronResult<Response> {
let params = get_router_params(req);
let topic_id = params.find("topic_id").unwrap();
let body = get_request_body(req);
let user_id = &body.get("userId").unwrap()[0];
let state = &body.get("state").unwrap()[0];
let result;
if state == "0" {
result = delete_topic_vote(user_id, topic_id);
} else {
if is_voted(user_id, topic_id) {
result = update_topic_vote(user_id, topic_id, state);
} else {
result = create_topic_vote(user_id, topic_id, state);
}
}
let mut data = JsonData::new();
if result.is_none() {
data.success = false;
data.message = "更新失败".to_owned();
}
respond_json(&data)
} |
extern crate bytes;
extern crate mio;
extern crate eventual;
extern crate eventual_io;
use mio::tcp;
use eventual::Async;
use eventual_io as eio;
pub fn main() {
// Create the socket
let reactor = eio::Reactor::start().unwrap();
let r = reactor.clone();
// Create a server socket
let srv = tcp::listen(&"127.0.0.1:3000".parse().unwrap()).unwrap();
println!(" + Accepting connections");
reactor.accept(srv)
// Process client connections with at most 10 in-flight at any given
// time.
.process(10, move |(src_tx, src_rx)| {
println!(" + Handling socket");
// Hard coded to a google IP
let (client, _) = tcp::connect(&"216.58.216.164:80".parse().unwrap()).unwrap();
let (dst_tx, dst_rx) = r.stream(client);
let a = dst_tx.send_all(src_rx).map_err(|_| ());
let b = src_tx.send_all(dst_rx).map_err(|_| ());
eventual::join((a, b)).and_then(|v| {
println!(" + Socket done");
Ok(v)
})
})
.reduce((), |_, _| ()) // TODO: .consume()
.await().unwrap();
}
|
use std::{marker::PhantomData, ops::Bound};
use chrono::serde::ts_seconds;
use chrono::{DateTime, Utc};
use sqlx::postgres::{types::PgRange, PgConnection};
use svc_agent::AgentId;
use uuid::Uuid;
use serde_derive::{Deserialize, Serialize};
use serde_json::Value as JsonValue;
pub type BoundedDateTimeTuple = (Bound<DateTime<Utc>>, Bound<DateTime<Utc>>);
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
pub struct KeyValueProperties(serde_json::Map<String, JsonValue>);
impl KeyValueProperties {
pub fn new() -> Self {
Self(serde_json::Map::new())
}
pub fn into_json(self) -> JsonValue {
JsonValue::Object(self.0)
}
}
impl From<serde_json::Map<String, JsonValue>> for KeyValueProperties {
fn from(map: serde_json::Map<String, JsonValue>) -> Self {
Self(map)
}
}
impl std::ops::Deref for KeyValueProperties {
type Target = serde_json::Map<String, JsonValue>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl std::ops::DerefMut for KeyValueProperties {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl sqlx::Encode<'_, sqlx::Postgres> for KeyValueProperties {
fn encode_by_ref<'q>(
&self,
buf: &mut <sqlx::Postgres as sqlx::database::HasArguments<'q>>::ArgumentBuffer,
) -> sqlx::encode::IsNull {
self.clone().into_json().encode_by_ref(buf)
}
}
impl sqlx::Decode<'_, sqlx::Postgres> for KeyValueProperties {
fn decode(
value: <sqlx::Postgres as sqlx::database::HasValueRef<'_>>::ValueRef,
) -> Result<Self, sqlx::error::BoxDynError> {
let raw_value = serde_json::Value::decode(value)?;
match raw_value {
JsonValue::Object(map) => Ok(map.into()),
_ => Err("failed to decode jsonb value as json object"
.to_owned()
.into()),
}
}
}
impl sqlx::Type<sqlx::Postgres> for KeyValueProperties {
fn type_info() -> <sqlx::Postgres as sqlx::Database>::TypeInfo {
<JsonValue as sqlx::Type<sqlx::Postgres>>::type_info()
}
}
#[derive(Clone, Copy, Debug, sqlx::Type, PartialEq, Eq)]
#[sqlx(type_name = "class_type", rename_all = "lowercase")]
pub enum ClassType {
Webinar,
P2P,
Minigroup,
}
#[derive(Clone, Copy, Debug)]
pub enum RtcSharingPolicy {
Shared,
Owned,
}
impl ToString for RtcSharingPolicy {
fn to_string(&self) -> String {
match self {
RtcSharingPolicy::Shared => "shared".to_string(),
RtcSharingPolicy::Owned => "owned".to_string(),
}
}
}
impl From<ClassType> for Option<RtcSharingPolicy> {
fn from(v: ClassType) -> Self {
match v {
ClassType::Webinar => Some(RtcSharingPolicy::Shared),
ClassType::Minigroup => Some(RtcSharingPolicy::Owned),
ClassType::P2P => None,
}
}
}
pub struct WebinarType;
pub struct P2PType;
pub struct MinigroupType;
pub trait AsClassType {
fn as_class_type() -> ClassType;
fn as_str() -> &'static str;
}
impl AsClassType for WebinarType {
fn as_class_type() -> ClassType {
ClassType::Webinar
}
fn as_str() -> &'static str {
"webinar"
}
}
impl AsClassType for P2PType {
fn as_class_type() -> ClassType {
ClassType::P2P
}
fn as_str() -> &'static str {
"p2p"
}
}
impl AsClassType for MinigroupType {
fn as_class_type() -> ClassType {
ClassType::Minigroup
}
fn as_str() -> &'static str {
"minigroup"
}
}
#[derive(Clone, Debug, Serialize, sqlx::FromRow)]
pub struct Object {
id: Uuid,
#[serde(skip)]
kind: ClassType,
scope: String,
#[serde(with = "serde::time")]
time: Time,
audience: String,
#[serde(with = "ts_seconds")]
created_at: DateTime<Utc>,
#[serde(skip_serializing_if = "Option::is_none")]
tags: Option<JsonValue>,
properties: KeyValueProperties,
conference_room_id: Uuid,
event_room_id: Uuid,
#[serde(skip_serializing_if = "Option::is_none")]
original_event_room_id: Option<Uuid>,
#[serde(skip_serializing_if = "Option::is_none")]
modified_event_room_id: Option<Uuid>,
preserve_history: bool,
reserve: Option<i32>,
room_events_uri: Option<String>,
host: Option<AgentId>,
timed_out: bool,
#[serde(skip_serializing_if = "Option::is_none")]
original_class_id: Option<Uuid>,
#[serde(skip_serializing_if = "Option::is_none")]
content_id: Option<String>,
}
pub fn default_locked_chat() -> bool {
true
}
pub fn default_locked_questions() -> bool {
true
}
pub fn default_whiteboard() -> bool {
true
}
impl Object {
pub fn id(&self) -> Uuid {
self.id
}
pub fn kind(&self) -> ClassType {
self.kind
}
pub fn scope(&self) -> &str {
&self.scope
}
pub fn event_room_id(&self) -> Uuid {
self.event_room_id
}
pub fn conference_room_id(&self) -> Uuid {
self.conference_room_id
}
pub fn audience(&self) -> &str {
&self.audience
}
pub fn tags(&self) -> Option<&JsonValue> {
self.tags.as_ref()
}
pub fn properties(&self) -> &KeyValueProperties {
&self.properties
}
pub fn original_event_room_id(&self) -> Option<Uuid> {
self.original_event_room_id
}
pub fn modified_event_room_id(&self) -> Option<Uuid> {
self.modified_event_room_id
}
pub fn reserve(&self) -> Option<i32> {
self.reserve
}
pub fn time(&self) -> &Time {
&self.time
}
pub fn room_events_uri(&self) -> Option<&String> {
self.room_events_uri.as_ref()
}
pub fn timed_out(&self) -> bool {
self.timed_out
}
#[cfg(test)]
pub fn host(&self) -> Option<&AgentId> {
self.host.as_ref()
}
pub fn rtc_sharing_policy(&self) -> Option<RtcSharingPolicy> {
self.kind.into()
}
pub fn original_class_id(&self) -> Option<Uuid> {
self.original_class_id
}
pub fn content_id(&self) -> Option<&String> {
self.content_id.as_ref()
}
}
impl crate::app::services::Creatable for Object {
fn id(&self) -> Uuid {
self.id()
}
fn audience(&self) -> &str {
self.audience()
}
fn reserve(&self) -> Option<i32> {
self.reserve()
}
fn tags(&self) -> Option<&serde_json::Value> {
self.tags()
}
fn rtc_sharing_policy(&self) -> Option<RtcSharingPolicy> {
self.rtc_sharing_policy()
}
}
////////////////////////////////////////////////////////////////////////////////
#[derive(Debug)]
pub struct WrongKind {
id: Uuid,
source: ClassType,
destination: ClassType,
}
impl WrongKind {
fn new(value: &Object, destination: ClassType) -> Self {
Self {
id: value.id(),
source: value.kind(),
destination,
}
}
}
impl std::fmt::Display for WrongKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Error converting class = {} of type {:?} to {:?}",
self.id, self.source, self.destination
)
}
}
impl std::error::Error for WrongKind {}
////////////////////////////////////////////////////////////////////////////////
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq, sqlx::Type)]
#[sqlx(transparent)]
#[serde(from = "BoundedDateTimeTuple")]
#[serde(into = "BoundedDateTimeTuple")]
pub struct Time(PgRange<DateTime<Utc>>);
impl From<Time> for BoundedDateTimeTuple {
fn from(time: Time) -> BoundedDateTimeTuple {
(time.0.start, time.0.end)
}
}
impl From<BoundedDateTimeTuple> for Time {
fn from(time: BoundedDateTimeTuple) -> Time {
Self(PgRange::from(time))
}
}
impl From<Time> for PgRange<DateTime<Utc>> {
fn from(time: Time) -> Self {
time.0
}
}
impl From<&Time> for PgRange<DateTime<Utc>> {
fn from(time: &Time) -> PgRange<DateTime<Utc>> {
time.0.clone()
}
}
impl Time {
pub fn end(&self) -> Option<&DateTime<Utc>> {
use std::ops::RangeBounds;
match self.0.end_bound() {
Bound::Included(t) => Some(t),
Bound::Excluded(t) => Some(t),
Bound::Unbounded => None,
}
}
}
////////////////////////////////////////////////////////////////////////////////
enum ReadQueryPredicate {
Id(Uuid),
Scope { audience: String, scope: String },
ConferenceRoom(Uuid),
EventRoom(Uuid),
OriginalEventRoom(Uuid),
}
pub struct ReadQuery {
condition: ReadQueryPredicate,
original: bool,
}
impl ReadQuery {
pub fn by_scope(audience: &str, scope: &str) -> Self {
Self {
condition: ReadQueryPredicate::Scope {
audience: audience.to_owned(),
scope: scope.to_owned(),
},
original: false,
}
}
pub fn by_conference_room(id: Uuid) -> Self {
Self {
condition: ReadQueryPredicate::ConferenceRoom(id),
original: false,
}
}
pub fn by_event_room(id: Uuid) -> Self {
Self {
condition: ReadQueryPredicate::EventRoom(id),
original: false,
}
}
pub fn by_original_event_room(id: Uuid) -> Self {
Self {
condition: ReadQueryPredicate::OriginalEventRoom(id),
original: false,
}
}
pub fn by_id(id: Uuid) -> Self {
Self {
condition: ReadQueryPredicate::Id(id),
original: false,
}
}
pub fn original(self) -> Self {
Self {
original: true,
..self
}
}
pub async fn execute(self, conn: &mut PgConnection) -> sqlx::Result<Option<Object>> {
use quaint::ast::{Comparable, Select};
use quaint::visitor::{Postgres, Visitor};
let q = Select::from_table("class");
let mut q = match self.condition {
ReadQueryPredicate::Id(_) => q.and_where("id".equals("_placeholder_")),
ReadQueryPredicate::Scope { .. } => q
.and_where("audience".equals("_placeholder_"))
.and_where("scope".equals("_placeholder_")),
ReadQueryPredicate::ConferenceRoom(_) => {
q.and_where("conference_room_id".equals("_placeholder_"))
}
ReadQueryPredicate::EventRoom(_) => {
q.and_where("event_room_id".equals("_placeholder_"))
}
ReadQueryPredicate::OriginalEventRoom(_) => {
q.and_where("original_event_room_id".equals("_placeholder_"))
}
};
if self.original {
q = q.and_where("original_class_id".is_null())
}
let (sql, _bindings) = Postgres::build(q);
let query = sqlx::query_as(&sql);
let query = match self.condition {
ReadQueryPredicate::Id(id) => query.bind(id),
ReadQueryPredicate::Scope { audience, scope } => query.bind(audience).bind(scope),
ReadQueryPredicate::ConferenceRoom(id) => query.bind(id),
ReadQueryPredicate::EventRoom(id) => query.bind(id),
ReadQueryPredicate::OriginalEventRoom(id) => query.bind(id),
};
query.fetch_optional(conn).await
}
}
////////////////////////////////////////////////////////////////////////////////
pub struct GenericReadQuery<T: AsClassType> {
condition: ReadQueryPredicate,
class_type: ClassType,
phantom: PhantomData<T>,
}
impl<T: AsClassType> GenericReadQuery<T> {
pub fn by_id(id: Uuid) -> Self {
Self {
condition: ReadQueryPredicate::Id(id),
class_type: T::as_class_type(),
phantom: PhantomData,
}
}
pub fn by_scope(audience: &str, scope: &str) -> Self {
Self {
condition: ReadQueryPredicate::Scope {
audience: audience.to_owned(),
scope: scope.to_owned(),
},
class_type: T::as_class_type(),
phantom: PhantomData,
}
}
pub async fn execute(self, conn: &mut PgConnection) -> sqlx::Result<Option<Object>> {
use quaint::ast::{Comparable, Select};
use quaint::visitor::{Postgres, Visitor};
let q = Select::from_table("class");
let q = match self.condition {
ReadQueryPredicate::Id(_) => q.and_where("id".equals("_placeholder_")),
ReadQueryPredicate::Scope { .. } => q
.and_where("audience".equals("_placeholder_"))
.and_where("scope".equals("_placeholder_")),
ReadQueryPredicate::ConferenceRoom(_) => {
q.and_where("conference_room_id".equals("_placeholder_"))
}
ReadQueryPredicate::EventRoom(_) => {
q.and_where("event_room_id".equals("_placeholder_"))
}
ReadQueryPredicate::OriginalEventRoom(_) => {
q.and_where("original_event_room_id".equals("_placeholder_"))
}
};
let q = q.and_where("kind".equals("_placeholder_"));
let (sql, _bindings) = Postgres::build(q);
let query = sqlx::query_as(&sql);
let query = match self.condition {
ReadQueryPredicate::Id(id) => query.bind(id),
ReadQueryPredicate::Scope { audience, scope } => query.bind(audience).bind(scope),
ReadQueryPredicate::ConferenceRoom(id) => query.bind(id),
ReadQueryPredicate::EventRoom(id) => query.bind(id),
ReadQueryPredicate::OriginalEventRoom(id) => query.bind(id),
};
let query = query.bind(self.class_type);
query.fetch_optional(conn).await
}
}
////////////////////////////////////////////////////////////////////////////////
pub struct UpdateDumpEventsQuery {
modified_event_room_id: Uuid,
room_events_uri: String,
}
impl UpdateDumpEventsQuery {
pub fn new(modified_event_room_id: Uuid, room_events_uri: String) -> Self {
Self {
modified_event_room_id,
room_events_uri,
}
}
pub async fn execute(self, conn: &mut PgConnection) -> sqlx::Result<()> {
sqlx::query!(
r"
UPDATE class
SET room_events_uri = $1
WHERE modified_event_room_id = $2
",
self.room_events_uri,
self.modified_event_room_id,
)
.execute(conn)
.await?;
Ok(())
}
}
pub struct UpdateAdjustedRoomsQuery {
id: Uuid,
original_event_room_id: Uuid,
modified_event_room_id: Uuid,
}
impl UpdateAdjustedRoomsQuery {
pub fn new(id: Uuid, original_event_room_id: Uuid, modified_event_room_id: Uuid) -> Self {
Self {
id,
original_event_room_id,
modified_event_room_id,
}
}
pub async fn execute(self, conn: &mut PgConnection) -> sqlx::Result<Object> {
sqlx::query_as!(
Object,
r#"
UPDATE class
SET original_event_room_id = $2,
modified_event_room_id = $3
WHERE id = $1
RETURNING
id,
scope,
kind AS "kind!: ClassType",
audience,
time AS "time!: Time",
tags,
properties AS "properties: _",
preserve_history,
created_at,
event_room_id AS "event_room_id!: Uuid",
conference_room_id AS "conference_room_id!: Uuid",
original_event_room_id,
modified_event_room_id,
reserve,
room_events_uri,
host AS "host: AgentId",
timed_out,
original_class_id,
content_id
"#,
self.id,
self.original_event_room_id,
self.modified_event_room_id,
)
.fetch_one(conn)
.await
}
}
pub struct EstablishQuery {
id: Uuid,
event_room_id: Uuid,
conference_room_id: Uuid,
}
impl EstablishQuery {
pub fn new(id: Uuid, event_room_id: Uuid, conference_room_id: Uuid) -> Self {
Self {
id,
event_room_id,
conference_room_id,
}
}
pub async fn execute(self, conn: &mut PgConnection) -> sqlx::Result<Object> {
sqlx::query_as!(
Object,
r#"
UPDATE class
SET event_room_id = $2,
conference_room_id = $3,
established = 't'
WHERE id = $1
RETURNING
id,
scope,
kind AS "kind!: ClassType",
audience,
time AS "time!: Time",
tags,
properties AS "properties: _",
preserve_history,
created_at,
event_room_id AS "event_room_id!: Uuid",
conference_room_id AS "conference_room_id!: Uuid",
original_event_room_id,
modified_event_room_id,
reserve,
room_events_uri,
host AS "host: AgentId",
timed_out,
original_class_id,
content_id
"#,
self.id,
self.event_room_id,
self.conference_room_id,
)
.fetch_one(conn)
.await
}
}
////////////////////////////////////////////////////////////////////////////////
pub struct RecreateQuery {
id: Uuid,
time: Time,
event_room_id: Uuid,
conference_room_id: Uuid,
}
impl RecreateQuery {
pub fn new(id: Uuid, time: Time, event_room_id: Uuid, conference_room_id: Uuid) -> Self {
Self {
id,
time,
event_room_id,
conference_room_id,
}
}
pub async fn execute(self, conn: &mut PgConnection) -> sqlx::Result<Object> {
let time: PgRange<DateTime<Utc>> = self.time.into();
sqlx::query_as!(
Object,
r#"
UPDATE class
SET time = $2,
event_room_id = $3,
conference_room_id = $4,
original_event_room_id = NULL,
modified_event_room_id = NULL
WHERE id = $1
RETURNING
id,
scope,
kind AS "kind!: ClassType",
audience,
time AS "time!: Time",
tags,
properties AS "properties: _",
preserve_history,
created_at,
event_room_id AS "event_room_id!: Uuid",
conference_room_id AS "conference_room_id!: Uuid",
original_event_room_id,
modified_event_room_id,
reserve,
room_events_uri,
host AS "host: AgentId",
timed_out,
original_class_id,
content_id
"#,
self.id,
time,
self.event_room_id,
Some(self.conference_room_id),
)
.fetch_one(conn)
.await
}
}
////////////////////////////////////////////////////////////////////////////////
pub struct ClassUpdateQuery {
id: Uuid,
time: Option<Time>,
reserve: Option<i32>,
host: Option<AgentId>,
properties: Option<KeyValueProperties>,
}
impl ClassUpdateQuery {
pub fn new(id: Uuid) -> Self {
Self {
id,
time: None,
reserve: None,
host: None,
properties: None,
}
}
pub fn time(mut self, time: Time) -> Self {
self.time = Some(time);
self
}
pub fn reserve(mut self, reserve: i32) -> Self {
self.reserve = Some(reserve);
self
}
pub fn host(mut self, host: AgentId) -> Self {
self.host = Some(host);
self
}
pub fn properties(self, properties: KeyValueProperties) -> Self {
Self {
properties: Some(properties),
..self
}
}
pub async fn execute(self, conn: &mut PgConnection) -> sqlx::Result<Object> {
let time: Option<PgRange<DateTime<Utc>>> = self.time.map(Into::into);
let query = sqlx::query_as!(
Object,
r#"
UPDATE class
SET
time = COALESCE($2, time),
reserve = COALESCE($3, reserve),
host = COALESCE($4, host),
properties = COALESCE($5, properties)
WHERE id = $1
RETURNING
id,
scope,
kind AS "kind!: ClassType",
audience,
time AS "time!: Time",
tags,
properties AS "properties!: KeyValueProperties",
preserve_history,
created_at,
event_room_id AS "event_room_id!: Uuid",
conference_room_id AS "conference_room_id!: Uuid",
original_event_room_id,
modified_event_room_id,
reserve,
room_events_uri,
host AS "host: AgentId",
timed_out,
original_class_id,
content_id
"#,
self.id,
time,
self.reserve,
self.host as Option<AgentId>,
self.properties.unwrap_or_default() as KeyValueProperties,
);
query.fetch_one(conn).await
}
}
////////////////////////////////////////////////////////////////////////////////
pub struct RoomCloseQuery {
id: Uuid,
timed_out: bool,
}
impl RoomCloseQuery {
pub fn new(id: Uuid, timed_out: bool) -> Self {
Self { id, timed_out }
}
pub async fn execute(self, conn: &mut PgConnection) -> sqlx::Result<Object> {
sqlx::query_as!(
Object,
r#"
UPDATE class
SET time = TSTZRANGE(LOWER(time),
LEAST(UPPER(time), NOW())),
timed_out = $2
WHERE id = $1
RETURNING
id,
scope,
kind AS "kind!: ClassType",
audience,
time AS "time!: Time",
tags,
properties AS "properties: _",
preserve_history,
created_at,
event_room_id AS "event_room_id!: Uuid",
conference_room_id AS "conference_room_id!: Uuid",
original_event_room_id,
modified_event_room_id,
reserve,
room_events_uri,
host AS "host: AgentId",
timed_out,
original_class_id,
content_id
"#,
self.id,
self.timed_out
)
.fetch_one(conn)
.await
}
}
////////////////////////////////////////////////////////////////////////////////
pub struct DeleteQuery {
id: Uuid,
}
impl DeleteQuery {
pub fn new(id: Uuid) -> Self {
Self { id }
}
pub async fn execute(self, conn: &mut PgConnection) -> sqlx::Result<u64> {
sqlx::query_as!(
Object,
r#"
DELETE FROM class
WHERE id = $1
"#,
self.id,
)
.execute(conn)
.await
.map(|r| r.rows_affected())
}
}
////////////////////////////////////////////////////////////////////////////////
pub(crate) mod serde {
pub(crate) mod time {
use super::super::Time;
use crate::serde::ts_seconds_bound_tuple;
use serde::{de, ser};
pub(crate) fn serialize<S>(value: &Time, serializer: S) -> Result<S::Ok, S::Error>
where
S: ser::Serializer,
{
ts_seconds_bound_tuple::serialize(&value.to_owned().into(), serializer)
}
#[allow(dead_code)]
pub(crate) fn deserialize<'de, D>(d: D) -> Result<Time, D::Error>
where
D: de::Deserializer<'de>,
{
let time = ts_seconds_bound_tuple::deserialize(d)?;
Ok(Time::from(time))
}
}
}
mod insert_query;
mod minigroup;
mod p2p;
mod webinar;
pub use insert_query::{Dummy, InsertQuery};
pub use minigroup::*;
pub use p2p::*;
pub use webinar::*;
|
extern crate peroxide;
use peroxide::*;
fn main() {
let a: Matrix = MATLAB::new("1 2; 3 4");
a.print();
let b: Matrix = PYTHON::new(vec![c!(1, 2), c!(3, 4)]);
b.print();
let c: Matrix = R::new(c!(1, 2, 3, 4), 2, 2, Row);
c.print();
let d: Matrix = Matrix::from_index(|x, y| (x * 3 + y + 1) as f64, (4, 3));
d.print();
}
|
// Copyright (c) 2019 - 2020 ESRLabs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use async_once::AsyncOnce;
use color_eyre::eyre::WrapErr;
use escargot::CargoBuild;
use lazy_static::lazy_static;
use log::debug;
use northstar::api::model::Container;
use npk::npk;
use std::{
convert::TryInto,
path::{Path, PathBuf},
};
use tempfile::TempDir;
use tokio::fs;
pub const TEST_CONTAINER: &str = "test_container:0.0.1:test";
pub const TEST_RESOURCE: &str = "test_resource:0.0.1:test";
const MANIFEST: &str = "northstar_tests/test_container/Cargo.toml";
lazy_static! {
static ref REPOSITORY: TempDir = TempDir::new().unwrap();
static ref TEST_CONTAINER_NPK: AsyncOnce<PathBuf> = AsyncOnce::new(async {
let package_dir = TempDir::new().unwrap();
let root = package_dir.path().join("root");
debug!("Building test container binary");
let binary_path = CargoBuild::new()
.manifest_path(MANIFEST)
.run()
.wrap_err("Failed to build the test_container")
.unwrap()
.path()
.to_owned();
debug!("Creating test container binary npk");
fs::create_dir_all(&root).await.unwrap();
async fn copy_file(file: &Path, dir: &Path) {
assert!(file.is_file());
assert!(dir.is_dir());
let filename = file.file_name().unwrap();
fs::copy(file, dir.join(filename)).await.unwrap();
}
copy_file(&binary_path, &root).await;
copy_file(
Path::new("northstar_tests/test_container/manifest.yaml"),
package_dir.path(),
)
.await;
npk::pack(
package_dir
.path()
.join("manifest")
.with_extension("yaml")
.as_path(),
package_dir.path().join("root").as_path(),
REPOSITORY.path(),
Some(Path::new("examples/keys/northstar.key")),
)
.await
.unwrap();
REPOSITORY.path().join("test_container-0.0.1.npk")
});
static ref TEST_RESOURCE_NPK: AsyncOnce<PathBuf> = AsyncOnce::new(async {
npk::pack(
Path::new("northstar_tests/test_resource/manifest.yaml"),
Path::new("northstar_tests/test_resource/root"),
REPOSITORY.path(),
Some(Path::new("examples/keys/northstar.key")),
)
.await
.unwrap();
REPOSITORY.path().join("test_resource-0.0.1.npk")
});
}
/// Path to the test container npk
pub async fn test_container_npk() -> &'static Path {
&TEST_CONTAINER_NPK.get().await
}
/// Test container key
pub fn test_container() -> Container {
TEST_CONTAINER.try_into().unwrap()
}
// Path to the test resource npk
pub async fn test_resource_npk() -> &'static Path {
&TEST_RESOURCE_NPK.get().await
}
|
#![feature(rc_unique)]
pub mod first;
pub mod second;
pub mod third;
pub mod fourth;
|
pub(crate) mod table_constraint_kind;
pub(crate) mod table_constraints;
pub(crate) mod table_name;
|
use std::f32;
use std::ops::Add;
use std::ops::Div;
use std::ops::Mul;
use std::ops::Sub;
#[derive(Copy, Clone)]
pub struct Vec3 {
pub e: [f32; 3],
}
impl Vec3 {
pub fn new() -> Vec3 {
Vec3 {
e: [0f32, 0f32, 0f32],
}
}
pub fn from_scalar(t: f32) -> Vec3 {
Vec3 { e: [t, t, t] }
}
pub fn from_values(x: f32, y: f32, z: f32) -> Vec3 {
Vec3 { e: [x, y, z] }
}
pub fn from_other(other: Vec3) -> Vec3 {
Vec3 {
e: [other.x(), other.y(), other.z()],
}
}
pub fn dot(a: Vec3, b: Vec3) -> f32 {
a.x() * b.x() + a.y() * b.y() + a.z() * b.z()
}
pub fn cross(a: Vec3, b: Vec3) -> Vec3 {
Vec3 {
e: [
a.y() * b.z() - a.z() * b.y(),
a.z() * b.x() - a.x() * b.z(),
a.x() * b.y() - a.y() * b.x(),
],
}
}
}
impl Vec3 {
pub fn x(&self) -> f32 {
self.e[0]
}
pub fn y(&self) -> f32 {
self.e[1]
}
pub fn z(&self) -> f32 {
self.e[2]
}
pub fn set_x(&mut self, t: f32) {
self.e[0] = t;
}
pub fn set_y(&mut self, t: f32) {
self.e[1] = t;
}
pub fn set_z(&mut self, t: f32) {
self.e[2] = t;
}
pub fn r(&self) -> f32 {
self.e[0]
}
pub fn g(&self) -> f32 {
self.e[1]
}
pub fn b(&self) -> f32 {
self.e[2]
}
pub fn set_r(&mut self, t: f32) {
self.e[0] = t;
}
pub fn set_g(&mut self, t: f32) {
self.e[1] = t;
}
pub fn set_b(&mut self, t: f32) {
self.e[2] = t;
}
pub fn set(&mut self, x: f32, y: f32, z: f32) {
self.e[0] = x;
self.e[1] = y;
self.e[2] = z;
}
pub fn length(&self) -> f32 {
(self.e[0] * self.e[0] + self.e[1] * self.e[1] + self.e[2] * self.e[2]).sqrt()
}
pub fn sqr_length(&self) -> f32 {
self.e[0] * self.e[0] + self.e[1] * self.e[1] + self.e[2] * self.e[2]
}
pub fn normalize(&mut self) {
*self = *self / self.length();
}
pub fn normalized(self) -> Vec3 {
self / self.length()
}
}
impl Add<Vec3> for Vec3 {
type Output = Vec3;
fn add(self, other: Vec3) -> Vec3 {
Vec3 {
e: [
self.e[0] + other.e[0],
self.e[1] + other.e[1],
self.e[2] + other.e[2],
],
}
}
}
impl Add<f32> for Vec3 {
type Output = Vec3;
fn add(self, other: f32) -> Vec3 {
Vec3 {
e: [self.e[0] + other, self.e[1] + other, self.e[2] + other],
}
}
}
impl Add<Vec3> for f32 {
type Output = Vec3;
fn add(self, other: Vec3) -> Vec3 {
Vec3 {
e: [other.e[0] + self, other.e[1] + self, other.e[2] + self],
}
}
}
impl Sub<Vec3> for Vec3 {
type Output = Vec3;
fn sub(self, other: Vec3) -> Vec3 {
Vec3 {
e: [
self.e[0] - other.e[0],
self.e[1] - other.e[1],
self.e[2] - other.e[2],
],
}
}
}
impl Sub<f32> for Vec3 {
type Output = Vec3;
fn sub(self, other: f32) -> Vec3 {
Vec3 {
e: [self.e[0] - other, self.e[1] - other, self.e[2] - other],
}
}
}
impl Mul<Vec3> for Vec3 {
type Output = Vec3;
fn mul(self, other: Vec3) -> Vec3 {
Vec3 {
e: [
self.e[0] * other.e[0],
self.e[1] * other.e[1],
self.e[2] * other.e[2],
],
}
}
}
impl Mul<f32> for Vec3 {
type Output = Vec3;
fn mul(self, other: f32) -> Vec3 {
Vec3 {
e: [self.e[0] * other, self.e[1] * other, self.e[2] * other],
}
}
}
impl Mul<Vec3> for f32 {
type Output = Vec3;
fn mul(self, other: Vec3) -> Vec3 {
Vec3 {
e: [other.e[0] * self, other.e[1] * self, other.e[2] * self],
}
}
}
impl Div<Vec3> for Vec3 {
type Output = Vec3;
fn div(self, other: Vec3) -> Vec3 {
Vec3 {
e: [
self.e[0] / other.e[0],
self.e[1] / other.e[1],
self.e[2] / other.e[2],
],
}
}
}
impl Div<f32> for Vec3 {
type Output = Vec3;
fn div(self, other: f32) -> Vec3 {
Vec3 {
e: [self.e[0] / other, self.e[1] / other, self.e[2] / other],
}
}
}
impl Div<Vec3> for f32 {
type Output = Vec3;
fn div(self, other: Vec3) -> Vec3 {
Vec3 {
e: [self / other.e[0], self / other.e[1], self / other.e[2]],
}
}
}
|
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
// Defining methods
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
// Associated function
fn square(size: u32) -> Rectangle {
Rectangle { width: size, height: size }
}
}
fn main() {
let rect = Rectangle { width: 50, height: 30 };
// Printing the rectangle using a Debug trait -> {:?}
println!("The rectangle: {:?}", rect);
// Each member in new line -> {:#?}
println!("The rectangle: {:#?}", rect);
println!("The area of the rectangle is {} square units.",
get_area(&rect));
println!("The area of the rectangle is {} square units.",
rect.area());
let rect_small = Rectangle { width: 20, height: 10 };
let rect_large = Rectangle { width: 70, height: 30 };
println!("Can rect hold rect_small? Answer: {}", rect.can_hold(&rect_small));
println!("Can rect hold rect_large? Answer: {}", rect.can_hold(&rect_large));
let square = Rectangle::square(30);
println!("The area of the square is {} square units.",
square.area());
}
fn get_area(rect: &Rectangle) -> u32 {
rect.width * rect.height
}
|
#![no_std]
#![no_main]
#![feature(custom_test_frameworks)]
#![test_runner(bentos::test_runner)]
#![reexport_test_harness_main = "test_main"]
extern crate alloc;
use core::panic::PanicInfo;
use alloc::{boxed::Box,vec,vec::Vec,rc::Rc};
use bentos::{print,println};
use bootloader::{BootInfo,entry_point};
entry_point!(kernel_main);
fn kernel_main(boot_info: &'static BootInfo) ->! {
use bentos::memory::{self,BootInfoFrameAllocator};
use bentos::allocator;
use x86_64::{VirtAddr,structures::paging::MapperAllSizes,structures::paging::Page};//import the MapperAllSizes trait in order to use the translate_addr method it provides.
bentos::init();
let phys_mem_offset = VirtAddr::new(boot_info.physical_memory_offset);//get virt addr offset from boot info
let mut mapper = unsafe {memory::init(phys_mem_offset)};//init a new Offsetpage mapper
let mut frame_allocator = unsafe{BootInfoFrameAllocator::init(&boot_info.memory_map)};//get usable physical memory info
/*map an unused page
let page = Page::containing_address(VirtAddr::new(0xdeadbeaf000));//build a page contain VirtAddr deadbeaf000
memory::create_example_mapping(page, &mut mapper, &mut frame_allocator);//map virtaar deadbeaf000 to 0xb8000(VGA)
let page_ptr:*mut u64 = page.start_address().as_mut_ptr();
unsafe{page_ptr.offset(300).write_volatile(0x_f021_f077_f065_f04e)};
*/
allocator::init_heap(&mut mapper, &mut frame_allocator).expect("heap initialization failed");
let x = Box::new(41);
println!("heap value address:{:p}",x);
println!("heap value :{}",*x);
let mut vec = Vec::new();
for i in 0..500{
vec.push(i);
}
println!("vec at {:p}",vec.as_slice());
let refcnt = Rc::new(vec![1,2,3]);
let clo = refcnt.clone();
println!("current refcnt is {}",Rc::strong_count(&clo));
core::mem::drop(refcnt);
println!("current refcnt is {}",Rc::strong_count(&clo));
#[cfg(test)]
test_main();
println!("bentOS is an embedded system lives on tender materials." );
bentos::hlt_loop();
}
///This function is called on panic.
#[cfg(not(test))]
#[panic_handler]
fn panic(info:&PanicInfo) -> ! {
println!("{}",info);
bentos::hlt_loop();
}
///Specify panic function in test-mode.
#[cfg(test)]
#[panic_handler]
fn panic(info:&PanicInfo) -> !{
bentos::test_panic_handler(info)
} |
use std::io::Cursor;
use byteorder::{LittleEndian, ReadBytesExt};
use failure::{ensure, format_err, Error};
use log::debug;
use crate::model::{
owned::{ComplexEntry, Entry, EntryHeader, SimpleEntry, TableTypeBuf},
TableType,
};
pub use self::configuration::{ConfigurationWrapper, Region};
mod configuration;
#[derive(Debug)]
pub struct TableTypeWrapper<'a> {
raw_data: &'a [u8],
data_offset: u64,
}
impl<'a> TableTypeWrapper<'a> {
pub fn new(raw_data: &'a [u8], data_offset: u64) -> Self {
Self {
raw_data,
data_offset,
}
}
pub fn to_buffer(&self) -> Result<TableTypeBuf, Error> {
let id = self.get_id()?;
let amount = self.get_amount()?;
let config = self.get_configuration()?.to_buffer()?;
let mut owned = TableTypeBuf::new(id & 0xF, config);
for i in 0..amount {
let entry = self.get_entry(i)?;
owned.add_entry(entry);
}
Ok(owned)
}
pub fn get_entries(&self) -> Result<Vec<Entry>, Error> {
let mut cursor = Cursor::new(self.raw_data);
cursor.set_position(self.data_offset);
self.decode_entries(&mut cursor)
}
fn decode_entries(&self, cursor: &mut Cursor<&[u8]>) -> Result<Vec<Entry>, Error> {
let mut offsets = Vec::new();
let mut entries = Vec::new();
for _ in 0..self.get_amount()? {
offsets.push(cursor.read_u32::<LittleEndian>()?);
}
for i in 0..self.get_amount()? {
let id = i & 0xFFFF;
if offsets[i as usize] == 0xFFFF_FFFF {
entries.push(Entry::Empty(id, id));
} else {
let maybe_entry = Self::decode_entry(cursor, id)?;
if let Some(e) = maybe_entry {
entries.push(e);
} else {
debug!("Entry with a negative count");
}
}
}
Ok(entries)
}
fn decode_entry(cursor: &mut Cursor<&[u8]>, id: u32) -> Result<Option<Entry>, Error> {
let header_size = cursor.read_u16::<LittleEndian>()?;
let flags = cursor.read_u16::<LittleEndian>()?;
let key_index = cursor.read_u32::<LittleEndian>()?;
let header_entry = EntryHeader::new(header_size, flags, key_index);
if header_entry.is_complex() {
Self::decode_complex_entry(cursor, header_entry, id)
} else {
Self::decode_simple_entry(cursor, header_entry, id)
}
}
fn decode_simple_entry(
cursor: &mut Cursor<&[u8]>,
header: EntryHeader,
id: u32,
) -> Result<Option<Entry>, Error> {
cursor.read_u16::<LittleEndian>()?;
// Padding
cursor.read_u8()?;
let val_type = cursor.read_u8()?;
let data = cursor.read_u32::<LittleEndian>()?;
let simple = SimpleEntry::new(id, header.get_key_index(), val_type, data);
let entry = Entry::Simple(simple);
Ok(Some(entry))
}
fn decode_complex_entry(
cursor: &mut Cursor<&[u8]>,
header: EntryHeader,
id: u32,
) -> Result<Option<Entry>, Error> {
let parent_entry = cursor.read_u32::<LittleEndian>()?;
let value_count = cursor.read_u32::<LittleEndian>()?;
let mut entries = Vec::with_capacity(value_count as usize);
if value_count == 0xFFFF_FFFF {
return Ok(None);
}
for _ in 0..value_count {
let val_id = cursor.read_u32::<LittleEndian>()?;
cursor.read_u16::<LittleEndian>()?;
// Padding
cursor.read_u8()?;
let val_type = cursor.read_u8()?;
let data = cursor.read_u32::<LittleEndian>()?;
let simple_entry = SimpleEntry::new(val_id, header.get_key_index(), val_type, data);
entries.push(simple_entry);
}
let complex = ComplexEntry::new(id, header.get_key_index(), parent_entry, entries);
let entry = Entry::Complex(complex);
Ok(Some(entry))
}
}
impl<'a> TableType for TableTypeWrapper<'a> {
type Configuration = ConfigurationWrapper<'a>;
fn get_id(&self) -> Result<u8, Error> {
let mut cursor = Cursor::new(self.raw_data);
cursor.set_position(8);
let out_value = cursor.read_u32::<LittleEndian>()? & 0xF;
Ok(out_value as u8)
}
fn get_amount(&self) -> Result<u32, Error> {
let mut cursor = Cursor::new(self.raw_data);
cursor.set_position(12);
Ok(cursor.read_u32::<LittleEndian>()?)
}
fn get_configuration(&self) -> Result<Self::Configuration, Error> {
let ini = 20;
let end = self.data_offset as usize;
ensure!(
ini <= end
&& (end - ini) > 28
&& self.raw_data.len() >= ini
&& self.raw_data.len() >= end,
"configuration slice is not valid"
);
let slice = &self.raw_data[ini..end];
let wrapper = ConfigurationWrapper::new(slice);
Ok(wrapper)
}
fn get_entry(&self, index: u32) -> Result<Entry, Error> {
let entries = self.get_entries()?;
entries
.get(index as usize)
.cloned()
.ok_or_else(|| format_err!("entry not found"))
}
}
|
// q0035_search_insert_position
struct Solution;
impl Solution {
pub fn search_insert(nums: Vec<i32>, target: i32) -> i32 {
match nums.binary_search(&target) {
Ok(n) => n as i32,
Err(n) => n as i32,
}
}
}
#[cfg(test)]
mod tests {
use super::Solution;
#[test]
fn it_works() {
assert_eq!(2, Solution::search_insert(vec![1, 3, 5, 6], 5));
assert_eq!(1, Solution::search_insert(vec![1, 3, 5, 6], 2));
assert_eq!(4, Solution::search_insert(vec![1, 3, 5, 6], 7));
assert_eq!(0, Solution::search_insert(vec![1, 3, 5, 6], 0));
}
}
|
#![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 FeatureProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub state: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FeatureResult {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<FeatureProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FeatureOperationsListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<FeatureResult>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Operation {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display: Option<operation::Display>,
}
pub mod operation {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Display {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub provider: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resource: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub operation: Option<String>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OperationListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Operation>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorResponse {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<ErrorDefinition>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorDefinition {
#[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 = "Vec::is_empty")]
pub details: Vec<ErrorDefinition>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ProxyResource {
#[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 SubscriptionFeatureRegistration {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<subscription_feature_registration::Properties>,
}
pub mod subscription_feature_registration {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")]
pub tenant_id: Option<String>,
#[serde(rename = "subscriptionId", default, skip_serializing_if = "Option::is_none")]
pub subscription_id: Option<String>,
#[serde(rename = "featureName", default, skip_serializing_if = "Option::is_none")]
pub feature_name: Option<String>,
#[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(rename = "providerNamespace", default, skip_serializing_if = "Option::is_none")]
pub provider_namespace: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub state: Option<properties::State>,
#[serde(rename = "authorizationProfile", default, skip_serializing_if = "Option::is_none")]
pub authorization_profile: Option<AuthorizationProfile>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub metadata: Option<serde_json::Value>,
#[serde(rename = "releaseDate", default, skip_serializing_if = "Option::is_none")]
pub release_date: Option<String>,
#[serde(rename = "registrationDate", default, skip_serializing_if = "Option::is_none")]
pub registration_date: Option<String>,
#[serde(rename = "documentationLink", default, skip_serializing_if = "Option::is_none")]
pub documentation_link: Option<String>,
#[serde(rename = "approvalType", default, skip_serializing_if = "Option::is_none")]
pub approval_type: Option<properties::ApprovalType>,
#[serde(rename = "shouldFeatureDisplayInPortal", default, skip_serializing_if = "Option::is_none")]
pub should_feature_display_in_portal: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
pub mod properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum State {
NotSpecified,
NotRegistered,
Pending,
Registering,
Registered,
Unregistering,
Unregistered,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ApprovalType {
NotSpecified,
ApprovalRequired,
AutoApproval,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AuthorizationProfile {
#[serde(rename = "requestedTime", default, skip_serializing_if = "Option::is_none")]
pub requested_time: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub requester: Option<String>,
#[serde(rename = "requesterObjectId", default, skip_serializing_if = "Option::is_none")]
pub requester_object_id: Option<String>,
#[serde(rename = "approvedTime", default, skip_serializing_if = "Option::is_none")]
pub approved_time: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub approver: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SubscriptionFeatureRegistrationList {
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<SubscriptionFeatureRegistration>,
}
|
fn challenge1() -> usize {
// Parse input into our own arrival time at the bus station and all
// the IDs of the buses currently in service.
let (arrival_time, bus_ids) = {
let input = aoc20::read_input_to_string("day13");
let arrival_time: usize = input
.lines()
.nth(0)
.expect("Input must have 2 lines")
.parse()
.expect("First line must contain a number");
// Parse out ids of buses currently in service.
let ids = input
.lines()
.nth(1)
.expect("Input must have 2 lines")
.split(',')
.filter_map(|id| id.parse().ok())
.collect::<Vec<usize>>();
(arrival_time, ids)
};
let (time_to_depart, bus_id) = bus_ids
.iter()
// Compute distance of next depature time of bus `id` from our arrival time.
.map(|id| match arrival_time % id {
rem if rem == 0 => (0, id),
rem => (id - rem, id),
})
.min_by_key(|&(time_to_depart, _)| time_to_depart)
.expect("There is at least one bus");
time_to_depart * bus_id
}
fn challenge2() -> usize {
aoc20::read_input_to_string("day13")
.lines()
.nth(1)
.expect("Input must have 2 lines")
.split(',')
.enumerate()
.filter_map(|(offset, id)| match id.parse::<usize>() {
Ok(id) => Some((offset, id)),
Err(_) => None,
})
.fold(
(0 /* initial time */, 1 /* initial lcm */),
|(mut time, lcm), (offset, id)| {
// For the current bus `id` advance time by the LCM of
// the already computed busses until we find a time
// where the offset requirement holds for the current
// bus.
// Stepping by the LCM ensures that the requirement
// still holds for the already computed busses.
while (time + offset) % id != 0 {
time += lcm;
}
// Compute new LCM based on the buses that already
// full-fill the offset requirement.
(time, lcm * id)
},
)
.0
}
fn main() {
println!("{}", challenge1());
println!("{}", challenge2());
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn check_challenge1() {
assert_eq!(challenge1(), 370);
}
#[test]
fn check_challenge2() {
assert_eq!(challenge2(), 894954360381385);
}
}
|
#[doc = "Register `DR_01` reader"]
pub type R = crate::R<DR_01_SPEC>;
#[doc = "Field `PE` reader - Parity Error bit"]
pub type PE_R = crate::BitReader;
#[doc = "Field `V` reader - Validity bit"]
pub type V_R = crate::BitReader;
#[doc = "Field `U` reader - User bit"]
pub type U_R = crate::BitReader;
#[doc = "Field `C` reader - Channel Status bit"]
pub type C_R = crate::BitReader;
#[doc = "Field `PT` reader - Preamble Type"]
pub type PT_R = crate::FieldReader;
#[doc = "Field `DR` reader - Data value"]
pub type DR_R = crate::FieldReader<u32>;
impl R {
#[doc = "Bit 0 - Parity Error bit"]
#[inline(always)]
pub fn pe(&self) -> PE_R {
PE_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - Validity bit"]
#[inline(always)]
pub fn v(&self) -> V_R {
V_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - User bit"]
#[inline(always)]
pub fn u(&self) -> U_R {
U_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - Channel Status bit"]
#[inline(always)]
pub fn c(&self) -> C_R {
C_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bits 4:5 - Preamble Type"]
#[inline(always)]
pub fn pt(&self) -> PT_R {
PT_R::new(((self.bits >> 4) & 3) as u8)
}
#[doc = "Bits 8:31 - Data value"]
#[inline(always)]
pub fn dr(&self) -> DR_R {
DR_R::new((self.bits >> 8) & 0x00ff_ffff)
}
}
#[doc = "Data input register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`dr_01::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct DR_01_SPEC;
impl crate::RegisterSpec for DR_01_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`dr_01::R`](R) reader structure"]
impl crate::Readable for DR_01_SPEC {}
#[doc = "`reset()` method sets DR_01 to value 0"]
impl crate::Resettable for DR_01_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
///! Contains a mutation operator based on ruin and recreate principle.
use super::*;
use crate::construction::heuristics::finalize_insertion_ctx;
use std::sync::Arc;
/// A mutation operator based on ruin and recreate principle.
pub struct RuinAndRecreate {
ruin: Arc<dyn Ruin + Send + Sync>,
recreate: Arc<dyn Recreate + Send + Sync>,
}
impl RuinAndRecreate {
/// Creates a new instance of `RuinAndRecreate` using given ruin and recreate methods.
pub fn new(ruin: Arc<dyn Ruin + Send + Sync>, recreate: Arc<dyn Recreate + Send + Sync>) -> Self {
Self { ruin, recreate }
}
}
impl Mutation for RuinAndRecreate {
fn mutate(&self, refinement_ctx: &RefinementContext, insertion_ctx: &InsertionContext) -> InsertionContext {
let mut insertion_ctx =
self.recreate.run(refinement_ctx, self.ruin.run(refinement_ctx, insertion_ctx.deep_copy()));
finalize_insertion_ctx(&mut insertion_ctx);
insertion_ctx
}
}
|
use std::char;
fn main() {
let input = 327901;
println!("{}", part1(input));
println!("{}", part2(&[3, 2, 7, 9, 0, 1]));
}
fn part1(input: usize) -> String {
let recipes = generate_recipes(input + 10);
let last_ten = &recipes[input..input + 10];
last_ten
.iter()
.map(|&x| char::from_digit(x as u32, 10).unwrap())
.collect()
}
fn generate_recipes(num_recipes: usize) -> Vec<usize> {
// allocate enough space for all the recipes up front
println!("started allocating");
let mut recipes = Vec::with_capacity(num_recipes + 20);
println!("finished allocating");
recipes.push(3);
recipes.push(7);
// These two indexes into the recipes vec represent the two elves
let mut first = 0;
let mut second = 1;
while recipes.len() < num_recipes {
let recipe_sum = recipes[first] + recipes[second];
if recipe_sum > 9 {
recipes.push(recipe_sum / 10);
}
recipes.push(recipe_sum % 10);
first = (first + recipes[first] + 1) % recipes.len();
second = (second + recipes[second] + 1) % recipes.len();
}
recipes
}
fn part2(needle: &[usize]) -> usize {
// allocate enough space for all the recipes up front
let mut recipes: Vec<usize> = Vec::new();
recipes.push(3);
recipes.push(7);
// These two indexes into the recipes vec represent the two elves
let mut first = 0;
let mut second = 1;
loop {
let recipe_sum = recipes[first] + recipes[second];
if recipe_sum > 9 {
recipes.push(recipe_sum / 10);
}
recipes.push(recipe_sum % 10);
for offset in 0..=1 {
if recipes.len() > needle.len() + offset {
let num_skip = recipes.len() - needle.len() - offset;
let tail = &recipes[num_skip..num_skip + needle.len()];
if tail == needle {
println!("tail: {:?}", tail);
println!("needle: {:?}", needle);
return num_skip;
}
}
}
if (recipes.len() % 10000000 == 0) {
println!("{}", recipes.len());
}
first = (first + recipes[first] + 1) % recipes.len();
second = (second + recipes[second] + 1) % recipes.len();
}
}
#[test]
fn test1() {
assert_eq!(part1(5), "0124515891");
assert_eq!(part1(18), "9251071085");
assert_eq!(part1(2018), "5941429882");
}
#[test]
fn test2() {
assert_eq!(part2(&[0, 1, 2, 4, 5]), 5);
assert_eq!(part2(&[5, 1, 5, 8, 9]), 9);
assert_eq!(part2(&[9, 2, 5, 1, 0]), 18);
assert_eq!(part2(&[5, 9, 4, 1, 4]), 2018);
}
|
use super::super::drawable::*;
use super::image::{Image, ImageIterator, ImageType};
use crate::coord::{Coord, ToUnsigned};
use crate::pixelcolor::PixelColor;
/// # 16 bits per pixel images
///
/// Every two bytes define the color for each pixel.
///
/// You can convert an image to 16BPP for inclusion with `include_bytes!()` doing the following
///
/// ```bash
/// convert image.png -flip -flop -type truecolor -define bmp:subtype=RGB565 -resize '64x64!' -depth 16 -strip image.bmp
/// ```
/// then
/// ```bash
/// tail -c $bytes image.bmp > image.raw // where $bytes is w * h * 2
/// ```
/// This will remove the BMP header leaving the raw pixel data
/// E.g 64x64 image will have `64 * 64 * 2` bytes of raw data.
pub type Image16BPP<'a, C> = Image<'a, C, ImageType16BPP>;
/// 16 bits per pixel image type
#[derive(Debug, Copy, Clone)]
pub enum ImageType16BPP {}
impl ImageType for ImageType16BPP {}
impl<'a, C> IntoIterator for &'a Image16BPP<'a, C>
where
C: PixelColor + From<u16>,
{
type Item = Pixel<C>;
type IntoIter = ImageIterator<'a, C, ImageType16BPP>;
fn into_iter(self) -> Self::IntoIter {
ImageIterator::new(self)
}
}
impl<'a, C> Iterator for ImageIterator<'a, C, ImageType16BPP>
where
C: PixelColor + From<u16>,
{
type Item = Pixel<C>;
fn next(&mut self) -> Option<Self::Item> {
let current_pixel = loop {
let w = self.im.width;
let h = self.im.height;
let x = self.x;
let y = self.y;
// End iterator if we've run out of stuff
if x >= w || y >= h {
return None;
}
let offset = ((y * w) + x) * 2; // * 2 as two bytes per pixel
// merge two bytes into a u16
let bit_value = (self.im.imagedata[(offset + 1) as usize] as u16) << 8
| self.im.imagedata[offset as usize] as u16;
let current_pixel = self.im.offset + Coord::new(x as i32, y as i32);
// Increment stuff
self.x += 1;
// Step down a row if we've hit the end of this one
if self.x >= w {
self.x = 0;
self.y += 1;
}
if current_pixel[0] >= 0 && current_pixel[1] >= 0 {
break Pixel(current_pixel.to_unsigned(), bit_value.into());
}
};
Some(current_pixel)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::pixelcolor::PixelColorU16;
use crate::transform::Transform;
use crate::unsignedcoord::UnsignedCoord;
#[test]
fn negative_top_left() {
let image: Image16BPP<PixelColorU16> = Image16BPP::new(
&[
0xff, 0x00, 0x00, 0x00, 0xbb, 0x00, //
0x00, 0x00, 0xcc, 0x00, 0x00, 0x00, //
0xee, 0x00, 0x00, 0x00, 0xaa, 0x00,
],
3,
3,
)
.translate(Coord::new(-1, -1));
assert_eq!(image.top_left(), Coord::new(-1, -1));
assert_eq!(image.bottom_right(), Coord::new(2, 2));
assert_eq!(image.size(), UnsignedCoord::new(3, 3));
}
#[test]
fn dimensions() {
let image: Image16BPP<PixelColorU16> = Image16BPP::new(
&[
0xff, 0x00, 0x00, 0x00, 0xbb, 0x00, //
0x00, 0x00, 0xcc, 0x00, 0x00, 0x00, //
0xee, 0x00, 0x00, 0x00, 0xaa, 0x00,
],
3,
3,
)
.translate(Coord::new(100, 200));
assert_eq!(image.top_left(), Coord::new(100, 200));
assert_eq!(image.bottom_right(), Coord::new(103, 203));
assert_eq!(image.size(), UnsignedCoord::new(3, 3));
}
#[test]
fn it_can_have_negative_offsets() {
let image: Image16BPP<PixelColorU16> = Image16BPP::new(
&[
0xff, 0x00, 0x00, 0x00, 0xbb, 0x00, //
0x00, 0x00, 0xcc, 0x00, 0x00, 0x00, //
0xee, 0x00, 0x00, 0x00, 0xaa, 0x00,
],
3,
3,
)
.translate(Coord::new(-1, -1));
let mut it = image.into_iter();
assert_eq!(
it.next(),
Some(Pixel(UnsignedCoord::new(0, 0), 0xcc_u16.into()))
);
assert_eq!(
it.next(),
Some(Pixel(UnsignedCoord::new(1, 0), 0x00_u16.into()))
);
assert_eq!(
it.next(),
Some(Pixel(UnsignedCoord::new(0, 1), 0x00_u16.into()))
);
assert_eq!(
it.next(),
Some(Pixel(UnsignedCoord::new(1, 1), 0xaa_u16.into()))
);
assert_eq!(it.next(), None);
}
}
|
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 vec<T: FromStr>(&mut self, len: usize) -> Vec<T> {
(0..len).map(|_| self.input()).collect()
}
fn mat<T: FromStr>(&mut self, row: usize, col: usize) -> Vec<Vec<T>> {
(0..row).map(|_| self.vec(col)).collect()
}
}
fn main() {
let cin = stdin();
let cin = cin.lock();
let mut sc = Scanner::new(cin);
let n: usize = sc.input();
let m: usize = sc.input();
let q: usize = sc.input();
let arr: Vec<(usize, usize, usize, usize)> = (0..q)
.map(|_| (sc.input(), sc.input(), sc.input(), sc.input()))
.collect();
let mut acc = vec![];
let mut res = vec![vec![]];
dfs(n, m, &mut acc, &mut res);
let mut ans = 0usize;
for xs in res {
let mut sum = 0usize;
for &(a, b, c, d) in &arr {
if xs[b - 1] - xs[a - 1] == c {
sum += d;
}
}
ans = std::cmp::max(ans, sum);
}
println!("{}", ans);
}
fn dfs(n: usize, m: usize, mut acc: &mut Vec<usize>, mut res: &mut Vec<Vec<usize>>) {
if acc.len() == n {
return res.push(acc.clone());
}
let &prev_last = acc.last().unwrap_or(&1);
for v in prev_last..=m {
acc.push(v);
dfs(n, m, &mut acc, &mut res);
acc.pop();
}
}
|
use surf::http::Method;
use crate::framework::endpoint::Endpoint;
/// Delete Key-Value Pairs in Bulk
/// Deletes multiple key-value pairs from Workers KV at once.
/// A 404 is returned if a delete action is for a namespace ID the account doesn't have.
/// https://api.cloudflare.com/#workers-kv-namespace-delete-multiple-key-value-pairs
#[derive(Debug)]
pub struct DeleteBulk<'a> {
pub account_identifier: &'a str,
pub namespace_identifier: &'a str,
pub bulk_keys: Vec<String>,
}
impl<'a> Endpoint<(), (), Vec<String>> for DeleteBulk<'a> {
fn method(&self) -> Method {
Method::Delete
}
fn path(&self) -> String {
format!(
"accounts/{}/storage/kv/namespaces/{}/bulk",
self.account_identifier, self.namespace_identifier
)
}
fn body(&self) -> Option<Vec<String>> {
Some(self.bulk_keys.clone())
}
// default content-type is already application/json
}
|
use crate::{
hitable::HitRecord,
ray::Ray,
utils::{
random_in_unit_sphere,
reflect,
refract,
schlick,
},
};
use vec3D::Vec3D;
pub trait Scatter {
fn scatter(&self, ray_in: &Ray, rec: &HitRecord, attenuation: &mut Vec3D, scattered: &mut Ray) -> bool;
}
#[derive(Clone, Copy)]
pub enum Material {
Lambert(Lambert),
Metal(Metal),
Dielectric(Dielectric),
}
impl Scatter for Material {
fn scatter(&self, ray_in: &Ray, rec: &HitRecord, attenuation: &mut Vec3D, scattered: &mut Ray) -> bool {
match self {
Material::Lambert(material) => material.scatter(ray_in, rec, attenuation, scattered),
Material::Metal(material) => material.scatter(ray_in, rec, attenuation, scattered),
Material::Dielectric(material) => material.scatter(ray_in, rec, attenuation, scattered),
}
}
}
#[derive(Clone, Copy)]
pub struct Lambert {
albedo: Vec3D,
}
impl Lambert {
pub fn new(albedo: Vec3D) -> Lambert {
Lambert {
albedo
}
}
}
impl Scatter for Lambert {
fn scatter(&self, _ray_in: &Ray, rec: &HitRecord, attenuation: &mut Vec3D, scattered: &mut Ray) -> bool {
let target = rec.p + rec.normal + random_in_unit_sphere();
*scattered = Ray::new(rec.p, target - rec.p);
*attenuation = self.albedo;
true
}
}
#[derive(Clone, Copy)]
pub struct Metal {
albedo: Vec3D,
fuzz: f64
}
impl Metal {
pub fn new(albedo: Vec3D, fuzz: f64) -> Metal {
Metal {
albedo,
fuzz: fuzz.min(1.0)
}
}
}
impl Scatter for Metal {
fn scatter(&self, ray_in: &Ray, rec: &HitRecord, attenuation: &mut Vec3D, scattered: &mut Ray) -> bool {
let reflected = reflect(ray_in.direction.unit(), rec.normal);
*scattered = Ray::new(rec.p, reflected + random_in_unit_sphere() * self.fuzz);
*attenuation = self.albedo;
scattered.direction.dot(rec.normal) > 0.0
}
}
#[derive(Clone, Copy)]
pub struct Dielectric {
ref_idx: f64,
}
impl Dielectric {
pub fn new(ref_idx: f64) -> Dielectric {
Dielectric {
ref_idx
}
}
}
impl Scatter for Dielectric {
fn scatter(&self, ray_in: &Ray, rec: &HitRecord, attenuation: &mut Vec3D, scattered: &mut Ray) -> bool {
let outward_normal: Vec3D;
let ni_over_nt: f64;
let mut refracted = Vec3D::new(1.0, 1.0, 1.0);
let reflect_prob: f64;
let cosine: f64;
let reflected = reflect(ray_in.direction, rec.normal);
*attenuation = Vec3D::new(1.0, 1.0, 1.0);
if ray_in.direction.dot(rec.normal) > 0.0 {
outward_normal = rec.normal * -1.0;
ni_over_nt = self.ref_idx;
cosine = self.ref_idx * ray_in.direction.dot(rec.normal) / ray_in.direction.mag();
} else {
outward_normal = rec.normal * 1.0;
ni_over_nt = 1.0 / self.ref_idx;
cosine = (ray_in.direction.dot(rec.normal) * -1.0) / ray_in.direction.mag();
}
if refract(ray_in.direction, outward_normal, ni_over_nt, &mut refracted) {
reflect_prob = schlick(cosine, self.ref_idx);
} else {
reflect_prob = 1.0;
}
if rand::random::<f64>() < reflect_prob {
*scattered = Ray::new(rec.p, reflected);
} else {
*scattered = Ray::new(rec.p, refracted);
}
true
}
}
|
#![allow(dead_code)]
#![feature(libc)]
extern crate libc;
extern crate rsnl;
pub mod socket;
pub mod message;
pub mod controller;
|
use std::collections::VecDeque;
use thiserror::Error;
use super::hir::Expr;
use super::*;
use super::Radix;
/// RecoverableResult is a type that represents a Result that can be recovered from.
///
/// See the [`Recover`] trait for more information.
///
/// [`Recover`]: trait.Recover.html
pub type RecoverableResult<T, E = CompileError> = Result<T, (E, T)>;
pub type CompileResult<T> = Result<T, CompileError>;
pub type CompileError = Locatable<Error>;
pub type CompileWarning = Locatable<Warning>;
/// ErrorHandler is a struct that hold errors generated by the compiler
///
/// An error handler is used because multiple errors may be generated by each
/// part of the compiler, this cannot be represented well with Rust's normal
/// `Result`.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct ErrorHandler<T = Error> {
errors: VecDeque<Locatable<T>>,
pub(crate) warnings: VecDeque<CompileWarning>,
}
// Can't be derived because the derive mistakenly puts a bound of T: Default
impl<T> Default for ErrorHandler<T> {
fn default() -> Self {
Self {
errors: Default::default(),
warnings: Default::default(),
}
}
}
impl<T> ErrorHandler<T> {
/// Construct a new error handler.
pub(crate) fn new() -> ErrorHandler<T> {
Default::default()
}
/// Whether any errors have been seen and not handled
pub(crate) fn is_empty(&self) -> bool {
self.errors.is_empty()
}
/// Add an error to the error handler.
pub(crate) fn push_back<E: Into<Locatable<T>>>(&mut self, error: E) {
self.errors.push_back(error.into());
}
/// Remove the first error from the queue
pub(crate) fn pop_front(&mut self) -> Option<Locatable<T>> {
self.errors.pop_front()
}
/// Shortcut for adding a warning
pub(crate) fn warn<W: Into<Warning>>(&mut self, warning: W, location: Location) {
self.warnings.push_back(location.with(warning.into()));
}
/// Shortcut for adding an error
pub(crate) fn error<E: Into<T>>(&mut self, error: E, location: Location) {
self.errors.push_back(location.with(error.into()));
}
/// Add an iterator of errors to the error queue
pub(crate) fn extend<E: Into<Locatable<T>>>(&mut self, iter: impl Iterator<Item = E>) {
self.errors.extend(iter.map(Into::into));
}
/// Move another `ErrorHandler`'s errors and warnings into this one.
pub(crate) fn append<S>(&mut self, other: &mut ErrorHandler<S>)
where
T: From<S>,
{
self.errors
.extend(&mut other.errors.drain(..).map(|loc| loc.map(Into::into)));
self.warnings.append(&mut other.warnings);
}
}
impl Iterator for ErrorHandler {
type Item = CompileError;
fn next(&mut self) -> Option<CompileError> {
self.pop_front()
}
}
#[derive(Clone, Debug, Error, PartialEq)]
pub enum Error {
#[error("invalid program: {0}")]
Semantic(#[from] SemanticError),
#[error("invalid syntax: {0}")]
Syntax(#[from] SyntaxError),
#[error("invalid macro: {0}")]
PreProcessor(#[from] CppError),
#[error("invalid token: {0}")]
Lex(#[from] LexError),
}
/// Semantic errors are non-exhaustive and may have new variants added at any time
#[derive(Clone, Debug, Error, PartialEq)]
#[non_exhaustive]
pub enum SemanticError {
#[error("{0}")]
Generic(String),
// Declaration specifier errors
#[error("cannot combine '{new}' specifier with previous '{existing}' type specifier")]
InvalidSpecifier {
existing: ast::DeclarationSpecifier,
new: ast::DeclarationSpecifier,
},
#[error("'{0}' is not a qualifier and cannot be used for pointers")]
NotAQualifier(ast::DeclarationSpecifier),
#[error("'{}' is too long for rcc", vec!["long"; *.0].join(" "))]
TooLong(usize),
#[error("conflicting storage classes '{0}' and '{1}'")]
ConflictingStorageClass(StorageClass, StorageClass),
#[error("conflicting types '{0}' and '{1}'")]
ConflictingType(Type, Type),
#[error("'{0}' cannot be signed or unsigned")]
CannotBeSigned(Type),
#[error("types cannot be both signed and unsigned")]
ConflictingSigned,
#[error("only function-scoped variables can have an `auto` storage class")]
AutoAtGlobalScope,
#[error("cannot have empty program")]
EmptyProgram,
// Declarator errors
#[error("expected an integer")]
NonIntegralLength,
#[error("arrays must have a positive length")]
NegativeLength,
#[error("function parameters always have a storage class of `auto`")]
ParameterStorageClass(StorageClass),
#[error("duplicate parameter name '{0}' in function declaration")]
DuplicateParameter(InternedStr),
#[error("functions cannot return '{0}'")]
IllegalReturnType(Type),
// TODO: print params in the error message
#[error("arrays cannot contain functions (got '{0}'). help: try storing array of pointer to function: (*{}[])(...)")]
ArrayStoringFunction(Type),
#[error("void must be the first and only parameter if specified")]
InvalidVoidParameter,
#[error("functions taking `void` must not have variadic arguments")]
VoidVarargs,
#[error("functions taking variadic arguments must have at least one parameter first")]
VarargsWithoutParam,
#[error("overflow in enumeration constant")]
EnumOverflow,
#[error("variable has incomplete type 'void'")]
VoidType,
// expression errors
#[error("use of undeclared identifier '{0}'")]
UndeclaredVar(InternedStr),
#[error("expected expression, got typedef")]
TypedefInExpressionContext,
#[error("type casts cannot have a storage class")]
IllegalStorageClass(StorageClass),
#[error("type casts cannot have a variable name")]
IdInTypeName(InternedStr),
#[error("expected integer, got '{0}'")]
NonIntegralExpr(Type),
#[error("cannot implicitly convert '{0}' to '{1}'{}",
if .1.is_pointer() {
format!(". help: use an explicit cast: ({})", .1)
} else {
String::new()
})
]
InvalidCast(Type, Type),
// String is the reason it couldn't be assigned
#[error("cannot assign to {0}")]
NotAssignable(String),
#[error("invalid operators for '{0}' (expected either arithmetic types or pointer operation, got '{1} {0} {2}'")]
InvalidAdd(hir::BinaryOp, Type, Type),
#[error("cannot perform pointer arithmetic when size of pointed type '{0}' is unknown")]
PointerAddUnknownSize(Type),
#[error("called object of type '{0}' is not a function")]
NotAFunction(Type),
#[error("too {} arguments to function call: expected {0}, have {1}", if .1 > .0 { "many" } else { "few" })]
/// (actual, expected)
WrongArgumentNumber(usize, usize),
#[error("{0} has not yet been defined")]
IncompleteDefinitionUsed(Type),
#[error("no member named '{0}' in '{1}'")]
NotAMember(InternedStr, Type),
#[error("expected struct or union, got type '{0}'")]
NotAStruct(Type),
#[error("cannot use '->' operator on type that is not a pointer")]
NotAStructPointer(Type),
#[error("cannot dereference expression of non-pointer type '{0}'")]
NotAPointer(Type),
#[error("cannot take address of {0}")]
InvalidAddressOf(&'static str),
#[error("cannot increment or decrement value of type '{0}'")]
InvalidIncrement(Type),
#[error("cannot use unary plus on expression of non-arithmetic type '{0}'")]
NotArithmetic(Type),
#[error("incompatible types in ternary expression: '{0}' cannot be converted to '{1}'")]
IncompatibleTypes(Type, Type),
// const fold errors
#[error("{} overflow in expresson", if *(.is_positive) { "positive" } else { "negative" })]
ConstOverflow { is_positive: bool },
#[error("cannot divide by zero")]
DivideByZero,
#[error("cannot shift {} by a negative amount", if *(.is_left) { "left" } else { "right" })]
NegativeShift { is_left: bool },
#[error("cannot shift {} by {maximum} or more bits for type '{ctype}' (got {current})",
if *(.is_left) { "left" } else { "right" })]
TooManyShiftBits {
is_left: bool,
maximum: u64,
ctype: Type,
current: u64,
},
#[error("not a constant expression: {0}")]
NotConstant(Expr),
#[error("cannot dereference NULL pointer")]
NullPointerDereference,
#[error("invalid types for '{0}' (expected arithmetic types or compatible pointers, got {1} {0} {2}")]
InvalidRelationalType(lex::ComparisonToken, Type, Type),
#[error("cannot cast pointer to float or vice versa")]
FloatPointerCast(Type),
// TODO: this shouldn't be an error
#[error("cannot cast to non-scalar type '{0}'")]
NonScalarCast(Type),
#[error("cannot cast void to any type")]
VoidCast,
#[error("cannot cast structs to any type")]
StructCast,
// Control flow errors
#[error("unreachable statement")]
UnreachableStatement,
// TODO: this error should happen way before codegen
#[cfg(feature = "codegen")]
#[error("redeclaration of label {0}")]
LabelRedeclaration(cranelift::prelude::Block),
#[error("use of undeclared label {0}")]
UndeclaredLabel(InternedStr),
#[error("{}case outside of switch statement", if *(.is_default) { "default " } else { "" })]
CaseOutsideSwitch { is_default: bool },
#[error("cannot have multiple {}cases in a switch statement",
if *(.is_default) { "default " } else { "" } )]
DuplicateCase { is_default: bool },
// Initializer errors
#[error("initializers cannot be empty")]
EmptyInitializer,
#[error("scalar initializers for '{0}' may only have one element (initialized with {1})")]
AggregateInitializingScalar(Type, usize),
#[error("too many initializers (declared with {0} elements, found {1})")]
TooManyMembers(usize, usize),
// Function definition errors
#[error("illegal storage class {0} for function (only `static` and `extern` are allowed)")]
InvalidFuncStorageClass(StorageClass),
#[error("missing parameter name in function definition (parameter {0} of type '{1}')")]
MissingParamName(usize, Type),
#[error("forward declaration of {0} is never completed (used in {1})")]
ForwardDeclarationIncomplete(InternedStr, InternedStr),
#[error("illegal signature for main function (expected 'int main(void)' or 'int main(int, char **)'")]
IllegalMainSignature,
// declaration errors
#[error("redefinition of '{0}'")]
Redefinition(InternedStr),
#[error("redeclaration of '{0}' with different type or qualifiers (originally {}, now {})", .1.get(), .2.get())]
IncompatibleRedeclaration(InternedStr, hir::Symbol, hir::Symbol),
#[error("'{0}' can only appear on functions")]
FuncQualifiersNotAllowed(hir::FunctionQualifiers),
// stmt errors
// new with the new parser
#[error("switch expressions must have an integer type (got {0})")]
NonIntegralSwitch(Type),
#[error("function '{0}' does not return a value")]
MissingReturnValue(InternedStr),
#[error("void function '{0}' should not return a value")]
ReturnFromVoid(InternedStr),
}
/// Syntax errors are non-exhaustive and may have new variants added at any time
#[derive(Clone, Debug, Error, PartialEq)]
#[non_exhaustive]
pub enum SyntaxError {
#[error("{0}")]
Generic(String),
#[error("expected {0}, got <end-of-file>")]
EndOfFile(&'static str),
#[error("expected statement, got {0}")]
NotAStatement(super::Keyword),
// expected a primary expression, but got EOF or an invalid token
#[error("expected variable, literal, or '('")]
MissingPrimary,
#[error("expected identifier, got '{}'",
.0.as_ref().map_or("<end-of-file>".into(),
|t| std::borrow::Cow::Owned(t.to_string())))]
ExpectedId(Option<Token>),
#[error("expected declaration specifier, got keyword '{0}'")]
ExpectedDeclSpecifier(Keyword),
#[error("expected declarator in declaration")]
ExpectedDeclarator,
#[error("empty type name")]
ExpectedType,
#[error("expected '(', '*', or variable, got '{0}'")]
ExpectedDeclaratorStart(Token),
#[error("only functions can have a function body (got {0})")]
NotAFunction(ast::InitDeclarator),
#[error("functions cannot be initialized (got {0})")]
FunctionInitializer(ast::Initializer),
#[error("function not allowed in this context (got {})", .0.as_type())]
FunctionNotAllowed(ast::FunctionDefinition),
#[error("function definitions must have a name")]
MissingFunctionName,
#[error("`static` for array sizes is only allowed in function declarations")]
StaticInConcreteArray,
}
/// Preprocessing errors are non-exhaustive and may have new variants added at any time
#[derive(Clone, Debug, Error, PartialEq)]
#[non_exhaustive]
pub enum CppError {
/// A user-defined error (`#error`) was present.
/// The `Vec<Token>` contains the tokens which followed the error.
// TODO: this allocates a string for each token,
// might be worth separating out into a function at some point
#[error("#error {}", (.0).iter().map(|t| t.to_string()).collect::<Vec<_>>().join(" "))]
User(Vec<Token>),
/// An invalid directive was present, such as `#invalid`
#[error("invalid preprocessing directive")]
InvalidDirective,
/// A valid token was present in an invalid position, such as `#if *`
///
/// The `&str` describes the expected token;
/// the `Token` is the actual token found.
#[error("expected {0}, got {1}")]
UnexpectedToken(&'static str, Token),
/// The file ended unexpectedly.
///
/// This error is separate from an unterminated `#if`:
/// it occurs if the file ends in the middle of a directive,
/// such as `#define`.
///
/// The `&str` describes what token was expected.
#[error("expected {0}, got <end-of-file>")]
EndOfFile(&'static str),
#[error("file '{0}' not found")]
FileNotFound(String),
#[error("wrong number of arguments: expected {0}, got {1}")]
TooFewArguments(usize, usize),
#[error("IO error: {0}")]
// TODO: find a way to put io::Error in here (doesn't derive Clone or PartialEq)
IO(String),
/// The file ended before an `#if`, `#ifdef`, or `#ifndef` was closed.
#[error("#if is never terminated")]
UnterminatedIf,
/// An `#if` occurred without an expression following.
#[error("expected expression for #if")]
EmptyExpression,
#[error("macro name missing")]
ExpectedMacroId,
#[error("missing {0} in {1}")]
Expected(&'static str, &'static str),
/// A `#define` occured without an identifier following.
#[error("macro name missing")]
EmptyDefine,
/// An `#include<>` or `#include""` was present.
#[error("empty filename")]
EmptyInclude,
/// A `#endif` was present, but no `#if` was currently open
#[error("#endif without #if")]
UnexpectedEndIf,
/// An `#else` was present, but either
/// a) no `#if` was currently open, or
/// b) an `#else` has already been seen.
#[error("#else after #else or #else without #if")]
UnexpectedElse,
/// An `#elif` was present, but either
/// a) no `#if` was currently open, or
/// b) an `#else` has already been seen.
#[error("{}", if *early { "#elif without #if" } else { "#elif after #else " })]
UnexpectedElif { early: bool },
/// After parsing an `#if` expression, there were tokens left over.
#[error("trailing tokens in `#if` expression")]
TooManyTokens,
}
/// Lex errors are non-exhaustive and may have new variants added at any time
#[derive(Clone, Debug, Error, PartialEq, Eq)]
#[non_exhaustive]
pub enum LexError {
#[error("unterminated /* comment")]
UnterminatedComment,
#[error("no newline at end of file")]
NoNewlineAtEOF,
#[error("unknown token: '{0}'")]
UnknownToken(char),
#[error("missing terminating {} character in {} literal",
if *(.string) { "\"" } else { "'" },
if *(.string) { "string" } else { "character" })]
MissingEndQuote { string: bool },
#[error("illegal newline while parsing string literal")]
NewlineInString,
#[error("{0} character escape out of range")]
CharEscapeOutOfRange(Radix),
#[error("overflow while parsing {}integer literal",
if let Some(signed) = .is_signed {
if *signed { "signed "} else { "unsigned "}
} else { "" })]
IntegerOverflow { is_signed: Option<bool> },
#[error("exponent for floating literal has no digits")]
ExponentMissingDigits,
#[error("missing digits to {0} integer constant")]
MissingDigits(Radix),
#[error("{0}")]
ParseFloat(#[from] std::num::ParseFloatError),
#[error("invalid digit {digit} in {radix} constant")]
InvalidDigit { digit: u32, radix: Radix },
#[error("multi-character character literal")]
MultiCharCharLiteral,
#[error("illegal newline while parsing char literal")]
NewlineInChar,
#[error("empty character constant")]
EmptyChar,
#[error("underflow parsing floating literal")]
FloatUnderflow,
#[error("{0}")]
InvalidHexFloat(#[from] hexponent::ParseError),
}
#[derive(Clone, Debug, Error, PartialEq)]
#[non_exhaustive]
/// errors are non-exhaustive and may have new variants added at any time
pub enum Warning {
// for compatibility
#[error("{0}")]
Generic(String),
/// A #warning directive was present, followed by the tokens in this variant.
// TODO: this allocates a string for each token,
// might be worth separating out into a function at some point
#[error("#warning {}", (.0).iter().map(|t| t.to_string()).collect::<Vec<_>>().join(" "))]
User(Vec<Token>),
#[error("extraneous semicolon in {0}")]
ExtraneousSemicolon(&'static str),
#[error("'{0}' qualifier on return type has no effect")]
FunctionQualifiersIgnored(hir::Qualifiers),
#[error("duplicate '{0}' declaration specifier{}",
if *.1 > 1 { format!(" occurs {} times", .1) } else { String::new() })]
DuplicateSpecifier(ast::UnitSpecifier, usize),
#[error("qualifiers in type casts are ignored")]
IgnoredQualifier(hir::Qualifiers),
#[error("declaration does not declare anything")]
EmptyDeclaration,
#[error("rcc does not support #pragma")]
IgnoredPragma,
#[error("variadic macros are not yet supported")]
IgnoredVariadic,
#[error("implicit int is deprecated and may be removed in a future release")]
ImplicitInt,
#[error("this is a definition, not a declaration, the 'extern' keyword has no effect")]
ExtraneousExtern,
}
impl<T: Into<String>> From<T> for Warning {
fn from(msg: T) -> Warning {
Warning::Generic(msg.into())
}
}
impl CompileError {
pub fn location(&self) -> Location {
self.location
}
pub fn is_lex_err(&self) -> bool {
self.data.is_lex_err()
}
pub fn is_syntax_err(&self) -> bool {
self.data.is_syntax_err()
}
pub fn is_semantic_err(&self) -> bool {
self.data.is_semantic_err()
}
}
impl Error {
pub fn is_lex_err(&self) -> bool {
if let Error::Lex(_) = self {
true
} else {
false
}
}
pub fn is_syntax_err(&self) -> bool {
if let Error::Syntax(_) = self {
true
} else {
false
}
}
pub fn is_semantic_err(&self) -> bool {
if let Error::Semantic(_) = self {
true
} else {
false
}
}
}
impl From<Locatable<String>> for CompileError {
fn from(err: Locatable<String>) -> Self {
err.map(|s| SemanticError::Generic(s).into())
}
}
impl From<Locatable<SemanticError>> for CompileError {
fn from(err: Locatable<SemanticError>) -> Self {
err.map(Error::Semantic)
}
}
impl From<Locatable<SyntaxError>> for CompileError {
fn from(err: Locatable<SyntaxError>) -> Self {
err.map(Error::Syntax)
}
}
impl From<Locatable<CppError>> for CompileError {
fn from(err: Locatable<CppError>) -> Self {
err.map(Error::PreProcessor)
}
}
impl From<Locatable<LexError>> for CompileError {
fn from(err: Locatable<LexError>) -> Self {
err.map(Error::Lex)
}
}
impl From<Locatable<String>> for Locatable<SemanticError> {
fn from(err: Locatable<String>) -> Self {
err.map(SemanticError::Generic)
}
}
impl<S: Into<String>> From<S> for SemanticError {
fn from(err: S) -> Self {
SemanticError::Generic(err.into())
}
}
impl<S: Into<String>> From<S> for SyntaxError {
fn from(err: S) -> Self {
SyntaxError::Generic(err.into())
}
}
pub(crate) trait Recover {
type Ok;
fn recover(self, error_handler: &mut ErrorHandler) -> Self::Ok;
}
impl<T, E: Into<CompileError>> Recover for RecoverableResult<T, E> {
type Ok = T;
fn recover(self, error_handler: &mut ErrorHandler) -> T {
self.unwrap_or_else(|(e, i)| {
error_handler.push_back(e);
i
})
}
}
impl<T, E: Into<CompileError>> Recover for RecoverableResult<T, Vec<E>> {
type Ok = T;
fn recover(self, error_handler: &mut ErrorHandler) -> T {
self.unwrap_or_else(|(es, i)| {
error_handler.extend(es.into_iter());
i
})
}
}
#[cfg(test)]
mod tests {
use super::*;
fn dummy_error() -> CompileError {
Location::default().with(Error::Lex(LexError::UnterminatedComment))
}
fn new_error(error: Error) -> CompileError {
Location::default().with(error)
}
#[test]
fn test_error_handler_into_iterator() {
let mut error_handler = ErrorHandler::new();
error_handler.push_back(dummy_error());
let errors = error_handler.collect::<Vec<_>>();
assert_eq!(errors.len(), 1);
}
#[test]
fn test_compile_error_is_kind() {
let e = Error::Lex(LexError::UnterminatedComment);
assert!(e.is_lex_err());
assert!(!e.is_semantic_err());
assert!(!e.is_syntax_err());
let e = Error::Semantic(SemanticError::Generic("".to_string()));
assert!(!e.is_lex_err());
assert!(e.is_semantic_err());
assert!(!e.is_syntax_err());
let e = Error::Syntax(SyntaxError::Generic("".to_string()));
assert!(!e.is_lex_err());
assert!(!e.is_semantic_err());
assert!(e.is_syntax_err());
}
#[test]
fn test_compile_error_display() {
assert_eq!(
dummy_error().data.to_string(),
"invalid token: unterminated /* comment"
);
assert_eq!(
Error::Semantic(SemanticError::Generic("bad code".to_string())).to_string(),
"invalid program: bad code"
);
}
#[test]
fn test_recover_error() {
let mut error_handler = ErrorHandler::new();
let r: RecoverableResult<i32> = Ok(1);
assert_eq!(r.recover(&mut error_handler), 1);
assert_eq!(error_handler.pop_front(), None);
let mut error_handler = ErrorHandler::new();
let r: RecoverableResult<i32> = Err((dummy_error(), 42));
assert_eq!(r.recover(&mut error_handler), 42);
let errors = error_handler.collect::<Vec<_>>();
assert_eq!(errors, vec![dummy_error()]);
}
#[test]
fn test_recover_multiple_errors() {
let mut error_handler = ErrorHandler::new();
let r: RecoverableResult<i32, Vec<CompileError>> = Ok(1);
assert_eq!(r.recover(&mut error_handler), 1);
assert_eq!(error_handler.pop_front(), None);
let mut error_handler = ErrorHandler::new();
let r: RecoverableResult<i32, Vec<CompileError>> = Err((
vec![
dummy_error(),
new_error(Error::Semantic(SemanticError::Generic("pears".to_string()))),
],
42,
));
assert_eq!(r.recover(&mut error_handler), 42);
let errors = error_handler.collect::<Vec<_>>();
assert_eq!(
errors,
vec![
dummy_error(),
new_error(Error::Semantic(SemanticError::Generic("pears".to_string()))),
]
);
}
}
|
//! Modal and ModalContainer
//!
//! A widget represent modal widget
use druid::{
lens::{self, LensExt},
BoxConstraints, Command, Data, Env, Event, EventCtx, LayoutCtx, LifeCycle, LifeCycleCtx,
PaintCtx, Point, Rect, Size, UpdateCtx, Widget, WidgetPod,
};
pub trait Modal {
fn is_closed(&self) -> Option<Command>;
}
pub struct ModalContainer<T: Data, M: Data + Modal, L: lens::Lens<T, Option<M>>> {
inner: WidgetPod<T, Box<dyn Widget<T>>>,
closure: Box<dyn Fn(&M, &Env) -> Option<Box<dyn Widget<M>>>>,
lens: L,
modal: Option<WidgetPod<M, Box<dyn Widget<M>>>>,
}
impl<T: Data, M: Data + Modal, L: lens::Lens<T, Option<M>>> ModalContainer<T, M, L> {
pub fn new<F>(inner: impl Widget<T> + 'static, closure: F, lens: L) -> Self
where
F: Fn(&M, &Env) -> Option<Box<dyn Widget<M>>> + 'static,
{
ModalContainer {
inner: WidgetPod::new(inner).boxed(),
closure: Box::new(closure),
lens,
modal: None,
}
}
}
impl<T: Data, M: Data + Modal + 'static, L: lens::Lens<T, Option<M>>> Widget<T>
for ModalContainer<T, M, L>
{
fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) {
self.inner.lifecycle(ctx, event, data, env);
if let Some(modal) = &mut self.modal {
self.lens.with(data, |data| {
if let Some(data) = data {
modal.lifecycle(ctx, event, data, env);
}
});
}
}
fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) {
// if we have modal, block all other event
if let Some(modal) = &mut self.modal {
self.lens.with_mut(data, |data| {
if let Some(modal_data) = data {
modal.event(ctx, event, modal_data, env);
if let Some(cmd) = modal_data.is_closed() {
ctx.submit_command(cmd);
*data = None;
}
}
});
return;
}
self.inner.event(ctx, event, data, env);
}
fn update(&mut self, ctx: &mut UpdateCtx, old_data: &T, data: &T, env: &Env) {
self.inner.update(ctx, data, env);
let changed =
self.lens.with(old_data, |old_data| self.lens.with(data, |data| !old_data.same(data)));
if changed {
self.modal = self
.lens
.get(data)
.as_ref()
.and_then(|data| (*self.closure)(data, env))
.map(|w| WidgetPod::new(w).boxed());
ctx.request_paint();
}
if let Some(modal) = &mut self.modal {
self.lens.with(data, |data| {
if let Some(data) = data {
if !modal.is_initialized() {
ctx.children_changed();
} else {
modal.update(ctx, data, env);
}
}
});
}
}
fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env) -> Size {
let size = self.inner.layout(ctx, bc, data, env);
self.inner.set_layout_rect(ctx, data, env, Rect::from_origin_size(Point::ORIGIN, size));
if let Some(modal) = &mut self.modal {
self.lens.with(data, |data| {
if let Some(data) = data {
let size = modal.layout(ctx, bc, data, env);
modal.set_layout_rect(
ctx,
data,
env,
Rect::from_origin_size(Point::ORIGIN, size),
);
}
});
}
size
}
fn paint(&mut self, paint_ctx: &mut PaintCtx, data: &T, env: &Env) {
self.inner.paint(paint_ctx, data, env);
if let Some(modal) = &mut self.modal {
self.lens.with(data, |data| {
if let Some(data) = data {
modal.paint(paint_ctx, data, env);
}
});
}
}
}
|
use log::{info, debug};
use std::sync::{Arc, RwLock};
use failure;
use failure::{Error, Fail};
use failure_derive;
use portaudio;
use hero_studio_core::midi::bus::{BusAddress, MidiBus};
use hero_studio_core::{config::Config, config::Audio as AudioConfig, studio::Studio, time::BarsTime};
mod midi;
use crate::midi::{Midi, MidiDriver, MidiError, PORT_MIDI_ID, CORE_MIDI_ID};
mod audio;
use crate::audio::{audio_close, audio_start};
mod server;
use crate::server::{Server, Message, ALL_PORTS};
// mod reactor;
// mod events;
const APP_NAME: &'static str = "Hero Studio";
const HERO_STUDIO_CONFIG: &'static str = "HERO_STUDIO_CONFIG";
const DEFAULT_HERO_STUDIO_CONFIG: &'static str = "studio.toml";
const HERO_STUDIO_LOG_CONFIG: &'static str = "HERO_STUDIO_LOG_CONFIG";
const DEFAULT_HERO_STUDIO_LOG_CONFIG: &'static str = "log4rs.yaml";
#[derive(Debug, Fail)]
enum MainError {
#[fail(display = "Failed to init logging: {}", cause)]
LoggingInit { cause: String },
#[fail(display = "Unable to lock studio for write")]
StudioWriteLock,
#[fail(display = "Failed to get a MIDI driver: {}", cause)]
GetMidiDriver { cause: MidiError },
}
type Stream = portaudio::stream::Stream<portaudio::stream::NonBlocking, portaudio::stream::Duplex<f32, f32>>;
fn main() -> Result<(), Error> {
init_logging()?;
let config = init_config()?;
let audio_config = config.audio.clone();
let (midi_bus, midi_driver) = init_midi_bus(&config)?;
let studio = init_studio(config, midi_bus)?;
let studio_lock = Arc::new(RwLock::new(studio));
let (pa_ctx, mut stream) = init_audio(audio_config, studio_lock.clone())?;
// TODO get port from config
let server = init_server(3001)?;
debug!("Started");
std::thread::sleep(std::time::Duration::from_secs(1));
debug!("Play");
studio_lock
.write()
.map(|mut studio| studio.play(false))
.map_err(|_err| MainError::StudioWriteLock)?;
// Loop while the non-blocking stream is active.
while let Ok(true) = stream.is_active() {
pa_ctx.sleep(1000);
}
debug!("Closing server ...");
server.close();
debug!("Closing audio ...");
audio_close(&mut stream)?;
Ok(())
}
fn init_logging() -> Result<(), Error> {
let log_config_path =
std::env::var(HERO_STUDIO_LOG_CONFIG)
.unwrap_or_else(|_| DEFAULT_HERO_STUDIO_LOG_CONFIG.to_string());
log4rs::init_file(log_config_path.as_str(), Default::default())
.map_err(|err| MainError::LoggingInit { cause: err.to_string() })?;
Ok(())
}
fn init_config() -> Result<Config, Error> {
let config_path =
std::env::var(HERO_STUDIO_CONFIG).unwrap_or_else(|_| DEFAULT_HERO_STUDIO_CONFIG.to_string());
debug!("Loading studio configuration from {} ...", config_path);
let config = Config::from_file(config_path.as_str())?;
debug!("{:#?}", config);
Ok(config)
}
fn init_midi_bus(_config: &Config) -> Result<(MidiBus, Box<dyn MidiDriver>), Error> {
info!("Initialising MIDI ...");
let midi = Midi::new();
let mut midi_bus = MidiBus::new();
// TODO create a driver from the configuration
// let midi_driver_id = *midi.drivers().first().unwrap();
let midi_driver_id = PORT_MIDI_ID;
// let midi_driver_id = CORE_MIDI_ID;
let midi_driver = midi
.driver(midi_driver_id, APP_NAME)
.map_err(|cause| MainError::GetMidiDriver { cause })?;
debug!("MIDI Driver: {:?}", midi_driver.id());
debug!("Destinations:");
for destination in midi_driver.destinations() {
debug!("=> {:?}", destination.name());
if let Ok(bus_node) = destination.open() {
debug!(" Adding MIDI destination to the bus: {}", destination.name());
midi_bus.add_node(&BusAddress::new(), bus_node);
}
}
Ok((midi_bus, midi_driver))
}
fn init_studio(config: Config, midi_bus: MidiBus) -> Result<Studio, Error> {
info!("Initialising the studio ...");
let config_lock = Arc::new(RwLock::new(config));
let midi_bus = Arc::new(RwLock::new(midi_bus));
let mut studio = Studio::new(config_lock, midi_bus);
studio.song_mut().set_loop_end(BarsTime::new(2, 0, 0, 0));
Ok(studio)
}
fn init_audio(audio_config: AudioConfig, studio_lock: Arc<RwLock<Studio>>) -> Result<(portaudio::PortAudio, Stream), Error> {
info!("Initialising audio ...");
let pa_ctx = portaudio::PortAudio::new()?;
let stream = audio_start(&pa_ctx, audio_config, studio_lock)?;
Ok((pa_ctx, stream))
}
fn init_server(port: u16) -> Result<Server, Error> {
info!("Initialising the websocket server ...");
let server = Server::new(port)?;
let receiver = server.receiver();
let sender = server.sender();
std::thread::spawn(move || {
for msg in receiver.iter() {
debug!("Received {:#?}", msg);
}
});
// std::thread::spawn(move || {
// let mut count = 0;
// loop {
// let data = format!("{:?}", count);
// drop(sender.send(Message::Outgoing { port: ALL_PORTS, data: data.into_bytes() } ));
// std::thread::sleep_ms(1);
// count += 1;
// }
// });
Ok(server)
}
|
#[macro_use]
extern crate bencher;
extern crate directories;
use bencher::Bencher;
use bencher::black_box;
use directories::BaseDirs;
use directories::ProjectDirs;
use directories::UserDirs;
fn base_dirs(b: &mut Bencher) {
b.iter(|| {
let _ = black_box(BaseDirs::new());
});
}
fn user_dirs(b: &mut Bencher) {
b.iter(|| {
let _ = black_box(UserDirs::new());
});
}
fn project_dirs_from_path(b: &mut Bencher) {
b.iter(|| {
let _ = black_box(ProjectDirs::from_path(Default::default()));
});
}
fn project_dirs(b: &mut Bencher) {
b.iter(|| {
let _ = black_box(ProjectDirs::from("org", "foo", "Bar App"));
});
}
benchmark_group!(constructors,
base_dirs,
user_dirs,
project_dirs_from_path,
project_dirs,
);
benchmark_main!(constructors);
|
#![feature(used)]
#![no_std]
extern crate cortex_m_semihosting;
#[cfg(not(feature = "use_semihosting"))]
extern crate panic_abort;
#[cfg(feature = "use_semihosting")]
extern crate panic_semihosting;
extern crate cortex_m;
extern crate cortex_m_rt;
extern crate atsamd21_hal;
extern crate metro_m0;
use metro_m0::clock::GenericClockController;
use metro_m0::delay::Delay;
use metro_m0::{CorePeripherals, Peripherals};
extern crate hd44780_driver;
use hd44780_driver::{HD44780, DisplayMode, Display, Cursor, CursorBlink};
extern crate embedded_hal;
fn busy_loop(){
#[allow(unused_variables)]
let mut i = 0;
for _ in 0..50000 {
i += 1;
}
}
fn main() {
let mut peripherals = Peripherals::take().unwrap();
let core = CorePeripherals::take().unwrap();
let mut clocks = GenericClockController::new(
peripherals.GCLK,
&mut peripherals.PM,
&mut peripherals.SYSCTRL,
&mut peripherals.NVMCTRL,
);
let mut pins = metro_m0::pins(peripherals.PORT);
let delay = Delay::new(core.SYST, &mut clocks);
let mut lcd = HD44780::new_8bit(
pins.d4.into_open_drain_output(&mut pins.port), // Register Select pin
pins.d3.into_open_drain_output(&mut pins.port), // Enable pin
pins.d5.into_open_drain_output(&mut pins.port), // d0
pins.d6.into_open_drain_output(&mut pins.port), // d1
pins.d7.into_open_drain_output(&mut pins.port), // d2
pins.d8.into_open_drain_output(&mut pins.port), // d3
pins.d9.into_open_drain_output(&mut pins.port), // d4
pins.d10.into_open_drain_output(&mut pins.port), // d5
pins.d11.into_open_drain_output(&mut pins.port), // d6
pins.d12.into_open_drain_output(&mut pins.port), // d7
delay,
);
//lcd.set_cursor_mode(CursorMode::Increment);
lcd.set_autoscroll(true);
lcd.set_display_mode(DisplayMode {
cursor_visible : Cursor::Invisible,
cursor_blink : CursorBlink::On,
display_visible : Display::On,
});
let string = "Hello, world! ";
// Display the following string
loop {
for c in string.chars() {
lcd.write_char(c);
busy_loop();
}
}
}
|
use serde::Deserialize;
use super::{Activity, Character, Media, Staff, Studio, User};
use crate::models::AiringSchedule;
pub type AniListID = u64;
#[derive(Clone, Debug, Deserialize)]
pub struct FuzzyDate {
year: u32,
month: u32,
day: u32,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PageInfo {
pub total: usize,
per_page: usize,
current_page: usize,
last_page: usize,
has_next_page: bool,
}
#[derive(Debug, Deserialize)]
pub struct Single<T> {
pub item: Option<T>,
}
#[derive(Debug, Deserialize)]
pub struct MultiItemContainer<T> {
pub items: Vec<T>,
}
#[derive(Debug, Deserialize)]
pub struct Paged<T> {
#[serde(rename = "Page")]
pub page: MultiItemContainer<T>,
}
#[derive(Debug, Deserialize)]
pub struct AniListError {
message: Option<String>,
status: Option<i32>,
}
#[derive(Debug, Deserialize)]
pub struct AniListResponse<T> {
pub data: T,
pub errors: Option<Vec<AniListError>>,
}
make_response!(ActivityResponse, Activity, activity);
make_response!(MediaResponse, Media, media);
make_paged_response!(PagedMediaResponse, Media, media);
make_response!(UserResponse, User, user);
make_paged_response!(PagedUserResponse, User, users);
make_response!(CharacterResponse, Character, character);
make_paged_response!(PagedCharacterResponse, Character, characters);
make_response!(StaffResponse, Staff, staff);
make_paged_response!(PagedStaffResponse, Staff, staff);
make_response!(StudioResponse, Studio, studio);
make_paged_response!(PagedStudioResponse, Studio, studios);
make_response!(AiringScheduleResponse, AiringSchedule, airing_schedule);
make_paged_response!(
PagedAiringScheduleResponse,
AiringSchedule,
airing_schedules
);
|
#[cfg(test)]
#[path = "../../tests/unit/checker/capacity_test.rs"]
mod capacity_test;
use super::*;
use crate::utils::combine_error_results;
use std::iter::once;
use vrp_core::models::common::{Load, MultiDimLoad};
/// Checks that vehicle load is assigned correctly. The following rules are checked:
/// * max vehicle's capacity is not violated
/// * load change is correct
pub fn check_vehicle_load(context: &CheckerContext) -> Result<(), Vec<String>> {
combine_error_results(&[check_vehicle_load_assignment(context)])
}
fn check_vehicle_load_assignment(context: &CheckerContext) -> Result<(), String> {
context.solution.tours.iter().try_for_each(|tour| {
let capacity = MultiDimLoad::new(context.get_vehicle(&tour.vehicle_id)?.capacity.clone());
let legs = (0_usize..)
.zip(tour.stops.windows(2))
.map(|(idx, leg)| {
(
idx,
match leg {
[from, to] => (from, to),
_ => panic!("unexpected leg configuration"),
},
)
})
.collect::<Vec<_>>();
let intervals: Vec<Vec<(usize, (&Stop, &Stop))>> = legs
.iter()
.fold(Vec::<(usize, usize)>::default(), |mut acc, (idx, (_, to))| {
let last_idx = legs.len() - 1;
if is_reload_stop(context, to) || *idx == last_idx {
let start_idx = acc.last().map_or(0_usize, |item| item.1 + 2);
let end_idx = if *idx == last_idx { last_idx } else { *idx - 1 };
acc.push((start_idx, end_idx));
}
acc
})
.into_iter()
.map(|(start_idx, end_idx)| {
legs.iter().cloned().skip(start_idx).take(end_idx - start_idx + 1).collect::<Vec<_>>()
})
.collect::<Vec<_>>();
intervals
.iter()
.try_fold::<_, _, Result<_, String>>(MultiDimLoad::default(), |acc, interval| {
let (start_delivery, end_pickup) = interval
.iter()
.flat_map(|(_, (from, to))| once(from).chain(once(to)))
.zip(0..)
.filter_map(|(stop, idx)| if idx == 0 || idx % 2 == 1 { Some(stop) } else { None })
.flat_map(|stop| {
stop.activities
.iter()
.map(move |activity| (activity.clone(), context.get_activity_type(tour, stop, activity)))
})
.try_fold::<_, _, Result<_, String>>(
(acc, MultiDimLoad::default()),
|acc, (activity, activity_type)| {
let activity_type = activity_type?;
let demand = get_demand(context, &activity, &activity_type)?;
Ok(match demand {
(DemandType::StaticDelivery, demand) => (acc.0 + demand, acc.1),
(DemandType::StaticPickup, demand) => (acc.0, acc.1 + demand),
(DemandType::StaticPickupDelivery, demand) => (acc.0 + demand, acc.1 + demand),
_ => acc,
})
},
)?;
let end_capacity = interval.iter().try_fold(start_delivery, |acc, (idx, (from, to))| {
let from_load = MultiDimLoad::new(from.load.clone());
let to_load = MultiDimLoad::new(to.load.clone());
if !capacity.can_fit(&from_load) || !capacity.can_fit(&to_load) {
return Err(format!("load exceeds capacity in tour '{}'", tour.vehicle_id));
}
let change = to.activities.iter().try_fold::<_, _, Result<_, String>>(
MultiDimLoad::default(),
|acc, activity| {
let activity_type = context.get_activity_type(tour, to, activity)?;
let (demand_type, demand) =
if activity.activity_type == "arrival" || activity.activity_type == "reload" {
(DemandType::StaticDelivery, end_pickup)
} else {
get_demand(context, &activity, &activity_type)?
};
Ok(match demand_type {
DemandType::StaticDelivery | DemandType::DynamicDelivery => acc - demand,
DemandType::StaticPickup | DemandType::DynamicPickup => acc + demand,
DemandType::None | DemandType::StaticPickupDelivery => acc,
})
},
)?;
let is_from_valid = from_load == acc;
let is_to_valid = to_load == from_load + change;
if (is_from_valid && is_to_valid) || (*idx == 0 && has_dispatch(tour)) {
Ok(to_load)
} else {
let message = match (is_from_valid, is_to_valid) {
(true, false) => format!("at stop {}", idx + 1),
(false, true) => format!("at stop {}", idx),
_ => format!("at stops {}, {}", idx, idx + 1),
};
Err(format!("load mismatch {} in tour '{}'", message, tour.vehicle_id))
}
})?;
Ok(end_capacity - end_pickup)
})
.map(|_| ())
})
}
enum DemandType {
None,
StaticPickup,
StaticDelivery,
StaticPickupDelivery,
DynamicPickup,
DynamicDelivery,
}
fn get_demand(
context: &CheckerContext,
activity: &Activity,
activity_type: &ActivityType,
) -> Result<(DemandType, MultiDimLoad), String> {
let (is_dynamic, demand) = context.visit_job(
activity,
&activity_type,
|job, task| {
let is_dynamic = job.pickups.as_ref().map_or(false, |p| !p.is_empty())
&& job.deliveries.as_ref().map_or(false, |p| !p.is_empty());
let demand = task.demand.clone().map_or_else(MultiDimLoad::default, MultiDimLoad::new);
(is_dynamic, demand)
},
|| (false, MultiDimLoad::default()),
)?;
let demand_type = match (is_dynamic, activity.activity_type.as_ref()) {
(_, "replacement") => DemandType::StaticPickupDelivery,
(true, "pickup") => DemandType::DynamicPickup,
(true, "delivery") => DemandType::DynamicDelivery,
(false, "pickup") => DemandType::StaticPickup,
(false, "delivery") => DemandType::StaticDelivery,
_ => DemandType::None,
};
Ok((demand_type, demand))
}
fn is_reload_stop(context: &CheckerContext, stop: &Stop) -> bool {
context.get_stop_activity_types(stop).first().map_or(false, |a| a == "reload")
}
fn has_dispatch(tour: &Tour) -> bool {
tour.stops
.iter()
.flat_map(|stop| stop.activities.iter())
.nth(1)
.map_or(false, |activity| activity.activity_type == "dispatch")
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - ICACHE control register"]
pub cr: CR,
#[doc = "0x04 - ICACHE status register"]
pub sr: SR,
#[doc = "0x08 - ICACHE interrupt enable register"]
pub ier: IER,
#[doc = "0x0c - ICACHE flag clear register"]
pub fcr: FCR,
#[doc = "0x10 - ICACHE hit monitor register"]
pub hmonr: HMONR,
#[doc = "0x14 - ICACHE miss monitor register"]
pub mmonr: MMONR,
_reserved6: [u8; 0x08],
#[doc = "0x20 - ICACHE region 0 configuration register"]
pub crr0: CRR0,
#[doc = "0x24 - ICACHE region 1 configuration register"]
pub crr1: CRR1,
#[doc = "0x28 - ICACHE region 2 configuration register"]
pub crr2: CRR2,
#[doc = "0x2c - ICACHE region 3 configuration register"]
pub crr3: CRR3,
}
#[doc = "CR (rw) register accessor: ICACHE control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cr`]
module"]
pub type CR = crate::Reg<cr::CR_SPEC>;
#[doc = "ICACHE control register"]
pub mod cr;
#[doc = "SR (r) register accessor: ICACHE status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`sr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`sr`]
module"]
pub type SR = crate::Reg<sr::SR_SPEC>;
#[doc = "ICACHE status register"]
pub mod sr;
#[doc = "IER (rw) register accessor: ICACHE interrupt enable register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ier::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 [`ier::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ier`]
module"]
pub type IER = crate::Reg<ier::IER_SPEC>;
#[doc = "ICACHE interrupt enable register"]
pub mod ier;
#[doc = "FCR (w) register accessor: ICACHE flag clear register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`fcr::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`fcr`]
module"]
pub type FCR = crate::Reg<fcr::FCR_SPEC>;
#[doc = "ICACHE flag clear register"]
pub mod fcr;
#[doc = "HMONR (r) register accessor: ICACHE hit monitor register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hmonr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`hmonr`]
module"]
pub type HMONR = crate::Reg<hmonr::HMONR_SPEC>;
#[doc = "ICACHE hit monitor register"]
pub mod hmonr;
#[doc = "MMONR (r) register accessor: ICACHE miss monitor register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`mmonr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`mmonr`]
module"]
pub type MMONR = crate::Reg<mmonr::MMONR_SPEC>;
#[doc = "ICACHE miss monitor register"]
pub mod mmonr;
#[doc = "CRR0 (rw) register accessor: ICACHE region 0 configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`crr0::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 [`crr0::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`crr0`]
module"]
pub type CRR0 = crate::Reg<crr0::CRR0_SPEC>;
#[doc = "ICACHE region 0 configuration register"]
pub mod crr0;
#[doc = "CRR1 (rw) register accessor: ICACHE region 1 configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`crr1::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 [`crr1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`crr1`]
module"]
pub type CRR1 = crate::Reg<crr1::CRR1_SPEC>;
#[doc = "ICACHE region 1 configuration register"]
pub mod crr1;
#[doc = "CRR2 (rw) register accessor: ICACHE region 2 configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`crr2::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 [`crr2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`crr2`]
module"]
pub type CRR2 = crate::Reg<crr2::CRR2_SPEC>;
#[doc = "ICACHE region 2 configuration register"]
pub mod crr2;
#[doc = "CRR3 (rw) register accessor: ICACHE region 3 configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`crr3::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 [`crr3::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`crr3`]
module"]
pub type CRR3 = crate::Reg<crr3::CRR3_SPEC>;
#[doc = "ICACHE region 3 configuration register"]
pub mod crr3;
|
use brawllib_rs::wiird;
use brawllib_rs::wiird::{WiiRDBlock, WiiRDCode};
use getopts::Options;
use std::env;
use std::path::PathBuf;
fn print_usage(program: &str, opts: Options) {
let brief = format!("Usage: {} [options]", program);
print!("{}", opts.usage(&brief));
}
fn main() {
let args: Vec<String> = env::args().collect();
let program = &args[0];
let mut opts = Options::new();
opts.optopt("c", "codeset", "path to a gecko/WiiRD codeset", "CODESET_PATH");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(_) => {
print_usage(program, opts);
return;
}
};
let codeset_path = if let Some(path) = matches.opt_str("c") {
PathBuf::from(path)
} else {
println!("Need to pass a codeset path\n");
print_usage(program, opts);
return;
};
let codeset = match wiird::wiird_load_gct(&codeset_path) {
Ok(codeset) => codeset,
Err(err) => {
println!("Failed to load codeset: {}", err);
return;
}
};
print_block(&codeset, "");
}
fn print_block(block: &WiiRDBlock, indent: &str) {
for block in &block.codes {
match block {
WiiRDCode::IfStatement { then_branch, else_branch, test, .. } => {
println!("{}If {:x?}", indent, test);
print_block(then_branch, &format!("{} ", indent));
if let Some(else_branch) = else_branch {
println!("{}Else", indent);
print_block(else_branch, &format!("{} ", indent));
}
}
_ => {
println!("{}{:x?}", indent, block);
}
}
}
}
|
use itertools::join;
use core::fmt::Debug;
#[derive(Debug, PartialEq, Eq)]
pub struct Entry {
pub num: i32,
pub c: char,
}
pub type Dict = Vec<Entry>;
type BitString = Vec<i32>;
trait Justify {
fn ljust(&self, filler: char, len: usize) -> String;
fn rjust(&self, filler: char, len: usize) -> String;
}
impl Justify for String {
fn ljust(&self, filler: char, len: usize) -> String {
let mut outstr = self.clone();
while outstr.len() < len {
outstr.push(filler);
}
outstr
}
fn rjust(&self, filler: char, len: usize) -> String {
let mut outstr = self.clone();
while outstr.len() < len {
outstr.insert(0, filler);
}
outstr
}
}
pub fn create_dict() -> Dict {
let abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut dict = Dict::new();
for (i, c) in abc.chars().enumerate() {
dict.push(Entry{num: i as i32, c});
}
dict
}
fn pad_left(input_string: &String, filler: char, len: i32) -> String {
input_string.ljust(filler, len as usize)
}
#[allow(dead_code)]
fn pad_right(input_string: &String, filler: char, len: i32) -> String {
input_string.rjust(filler, len as usize)
}
fn to_bit_string(num: i32) -> BitString {
let bitstring: BitString;
if num == 0 {
bitstring = Vec::new();
} else {
bitstring = format!("{:b}", num).chars().map( |x| x.to_digit(10).unwrap() as i32 ).collect();
};
bitstring
}
fn from_bit_string(bit_string: &BitString) -> i32 {
let val: i32;
if bit_string.is_empty() {
val = 0;
} else {
val = i32::from_str_radix(join(bit_string, &"").as_str(), 2).unwrap();
}
val
}
fn to_binary(input_str: &String) -> BitString {
let mut arr = Vec::new();
for c in input_str.chars() {
let mut bits = to_bit_string(c as i32);
while bits.len() < 8 {
bits.insert(0, 0);
}
arr.extend(bits);
}
arr
}
fn chunks_of<T>(num: usize, arr: &Vec<T>) -> Vec<Vec<T>>
where T: Debug + Clone {
let mut chunks : Vec<Vec<T>> = Vec::new();
for a in arr.chunks(num) {
chunks.push(a.to_vec());
}
chunks
}
fn find_char(dictionary: &Dict, bit_string: &BitString) -> char {
let a = from_bit_string(bit_string);
let mut b: char = '\0';
for item in dictionary {
if item.num == a { b = item.c };
}
b
}
fn translate(dictionary: &Dict, string: &String) -> String {
let mut tmp: BitString = to_binary(string);
while tmp.len() % 6 != 0 {
tmp.push(0);
}
let chunks = chunks_of(6, &tmp);
let mut ret_str = String::new();
for item in chunks {
ret_str.push(find_char(dictionary, &item));
}
ret_str
}
pub fn encode(dictionary: &Dict, string: &String) -> String {
let mut translated = translate(&dictionary, &string);
if translated.len() % 4 != 0 {
translated = pad_left(&translated, '=', (translated.len() + 4 - (translated.len() % 4)) as i32);
}
translated
}
fn find_code(dictionary: &Dict, c: char) -> String {
let mut code = String::new();
for item in dictionary {
if item.c == c {
code = format!("{:06b}", item.num);
}
}
code
}
pub fn decode(dictionary: &Dict, string: &String) -> String {
let mut outstr = String::new();
let mut tmp = string.clone();
while tmp.ends_with("=") {
tmp.truncate(tmp.len()-1);
}
let mut binary_text: Vec<i32> = Vec::new();
for c in tmp.chars() {
let t: Vec<i32> = find_code(&dictionary, c).chars().map( |x| x.to_digit(10).unwrap() as i32 ).collect();
binary_text.extend( t );
}
let chunks = chunks_of(8, &binary_text);
for item in chunks {
outstr.push( (from_bit_string(&item) as u8) as char );
}
if outstr.ends_with("\0") {
outstr.truncate(outstr.len() - 1);
}
outstr
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_create_dictionary() {
let dictionary = create_dict();
assert_eq!(Entry{num: 0, c:'A'}, dictionary[0]);
assert_eq!(Entry{num: 1, c:'B'}, dictionary[1]);
assert_eq!(Entry{num:25, c:'Z'}, dictionary[25]);
assert_eq!(Entry{num:26, c:'a'}, dictionary[26]);
assert_eq!(Entry{num:51, c:'z'}, dictionary[51]);
assert_eq!(Entry{num:52, c:'0'}, dictionary[52]);
assert_eq!(Entry{num:62, c:'+'}, dictionary[62]);
assert_eq!(Entry{num:63, c:'/'}, dictionary[63]);
assert_eq!(dictionary.len(), 64);
}
#[test]
fn test_padding() {
assert_eq!("ASD111", pad_left(&"ASD".to_string(), '1', 6));
assert_eq!("111ASD", pad_right(&"ASD".to_string(), '1', 6));
}
#[test]
fn test_to_bit_string() {
assert_eq!(Vec::<i32>::new(), to_bit_string(0));
assert_eq!(vec![1,0,1,0,0], to_bit_string(20));
assert_eq!(vec![1,0,1,1,0], to_bit_string(22));
}
#[test]
fn test_from_bitsring() {
assert_eq!(0, from_bit_string(&vec![]));
assert_eq!(20, from_bit_string(&vec![1, 0, 1, 0, 0]));
assert_eq!(22, from_bit_string(&vec![1, 0, 1, 1, 0]));
}
#[test]
fn test_to_binary() {
assert_eq!(vec![0, 1, 1, 1, 0, 0, 1, 1], to_binary(&String::from("s")));
assert_eq!(vec![0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1], to_binary(&String::from("SOS")));
}
#[test]
fn test_chunks_of() {
assert_eq!(Vec::<Vec<i32>>::new(), chunks_of(8, &Vec::new()));
assert_eq!(vec![vec![1,2,3,4,5,6], vec![7,8,9,10]], chunks_of(6, &(1..11).collect()));
assert_eq!(vec![vec![1,2,3], vec![4,5,6], vec![7,8,9], vec![10, 11, 12], vec![13, 14, 15]], chunks_of(3, &(1..16).collect()));
}
#[test]
fn test_find_char() {
let dictionary = create_dict();
assert_eq!('A', find_char(&dictionary, &Vec::new()));
assert_eq!('E', find_char(&dictionary, &vec![1,0,0]));
assert_eq!('8', find_char(&dictionary, &vec![1,1,1,1,0,0]));
assert_eq!('/', find_char(&dictionary, &vec![1,1,1,1,1,1]));
}
#[test]
fn test_translate() {
let dictionary = create_dict();
assert_eq!("TWFu", translate(&dictionary, &String::from("Man")).as_str());
assert_eq!("cGxlYXN1cmUu", translate(&dictionary, &String::from("pleasure.")).as_str());
assert_eq!("cGxlYXN1cmU", translate(&dictionary, &String::from("pleasure")).as_str());
assert_eq!("cA", translate(&dictionary, &String::from("p")).as_str());
assert_eq!("", translate(&dictionary, &String::new()).as_str());
}
#[test]
fn test_encode() {
let dictionary = create_dict();
assert_eq!("U2F2ZSBvdXIgc291bHMh", encode(&dictionary, &String::from("Save our souls!")).as_str());
assert_eq!("U2F2ZSBvdXIgc291bHM=", encode(&dictionary, &String::from("Save our souls")).as_str());
assert_eq!("U2F2ZSBvdXIgc291bA==", encode(&dictionary, &String::from("Save our soul")).as_str());
assert_eq!("U2F2ZSBvdXIgc291", encode(&dictionary, &String::from("Save our sou")).as_str());
}
#[test]
fn test_find_code() {
let dictionary = create_dict();
assert_eq!("011010", find_code(&dictionary, 'a').as_str());
assert_eq!("011001", find_code(&dictionary, 'Z').as_str());
assert_eq!("111101", find_code(&dictionary, '9').as_str());
}
#[test]
fn test_decode() {
let dictionary = create_dict();
assert_eq!("Save our souls!", decode(&dictionary, &encode(&dictionary, &String::from("Save our souls!"))).as_str());
assert_eq!("Save our souls", decode(&dictionary, &encode(&dictionary, &String::from("Save our souls"))).as_str());
assert_eq!("Save our soul", decode(&dictionary, &encode(&dictionary, &String::from("Save our soul"))).as_str());
}
} |
use std::fmt;
use iced::Color;
use serde::{Deserialize, Serialize};
use crate::gui::styles::custom_themes::{dracula, gruvbox, nord, solarized};
use crate::gui::styles::types::palette::Palette;
/// Custom style with any relevant metadata
pub struct CustomPalette {
/// Color scheme's palette
pub(crate) palette: Palette,
/// Extra colors such as the favorites star
pub(crate) extension: PaletteExtension,
}
/// Extension color for themes.
pub struct PaletteExtension {
/// Color of favorites star
pub starred: Color,
/// Badge/logo alpha
pub chart_badge_alpha: f32,
/// Round borders alpha
pub round_borders_alpha: f32,
/// Round containers alpha
pub round_containers_alpha: f32,
}
/// Built in extra styles
#[derive(Clone, Copy, Serialize, Deserialize, Debug, Hash, PartialEq)]
#[serde(tag = "custom")]
pub enum ExtraStyles {
DraculaDark,
DraculaLight,
GruvboxDark,
GruvboxLight,
NordDark,
NordLight,
SolarizedDark,
SolarizedLight,
}
impl ExtraStyles {
/// [`Palette`] of the [`ExtraStyles`] variant
pub fn to_palette(self) -> Palette {
match self {
ExtraStyles::DraculaLight => dracula::dracula_light().palette,
ExtraStyles::DraculaDark => dracula::dracula_dark().palette,
ExtraStyles::GruvboxDark => gruvbox::gruvbox_dark().palette,
ExtraStyles::GruvboxLight => gruvbox::gruvbox_light().palette,
ExtraStyles::NordLight => nord::nord_light().palette,
ExtraStyles::NordDark => nord::nord_dark().palette,
ExtraStyles::SolarizedDark => solarized::solarized_dark().palette,
ExtraStyles::SolarizedLight => solarized::solarized_light().palette,
}
}
/// Extension colors for the current [`ExtraStyles`] variant
pub fn to_ext(self) -> PaletteExtension {
match self {
ExtraStyles::DraculaLight => dracula::dracula_light().extension,
ExtraStyles::DraculaDark => dracula::dracula_dark().extension,
ExtraStyles::GruvboxDark => gruvbox::gruvbox_dark().extension,
ExtraStyles::GruvboxLight => gruvbox::gruvbox_light().extension,
ExtraStyles::NordLight => nord::nord_light().extension,
ExtraStyles::NordDark => nord::nord_dark().extension,
ExtraStyles::SolarizedDark => solarized::solarized_dark().extension,
ExtraStyles::SolarizedLight => solarized::solarized_light().extension,
}
}
/// Theme is a night/dark style
pub const fn is_nightly(self) -> bool {
match self {
ExtraStyles::DraculaDark
| ExtraStyles::GruvboxDark
| ExtraStyles::NordDark
| ExtraStyles::SolarizedDark => true,
ExtraStyles::DraculaLight
| ExtraStyles::GruvboxLight
| ExtraStyles::NordLight
| ExtraStyles::SolarizedLight => false,
}
}
/// Slice of all implemented custom styles
pub const fn all_styles() -> &'static [Self] {
&[
ExtraStyles::DraculaDark,
ExtraStyles::DraculaLight,
ExtraStyles::GruvboxDark,
ExtraStyles::GruvboxLight,
ExtraStyles::NordDark,
ExtraStyles::NordLight,
ExtraStyles::SolarizedDark,
ExtraStyles::SolarizedLight,
]
}
}
impl fmt::Display for ExtraStyles {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
ExtraStyles::DraculaLight => write!(f, "Dracula (Day)"),
ExtraStyles::DraculaDark => write!(f, "Dracula (Night)"),
ExtraStyles::GruvboxDark => write!(f, "Gruvbox (Night)"),
ExtraStyles::GruvboxLight => write!(f, "Gruvbox (Day)"),
ExtraStyles::NordLight => write!(f, "Nord (Day)"),
ExtraStyles::NordDark => write!(f, "Nord (Night)"),
ExtraStyles::SolarizedLight => write!(f, "Solarized (Day)"),
ExtraStyles::SolarizedDark => write!(f, "Solarized (Night)"),
}
}
}
|
use super::{Blocks, Chunk};
use crate::internal_data_structure::raw_bit_vector::RawBitVector;
impl super::Chunk {
/// Constructor.
pub fn new(value: u64, length: u16, rbv: &RawBitVector, i_chunk: u64) -> Chunk {
let blocks = Blocks::new(rbv, i_chunk, length);
Chunk {
value,
length,
blocks,
}
}
/// Returns the content of the chunk.
pub fn value(&self) -> u64 {
self.value
}
}
|
fn main() {
let v1 = vec![1, 2, 3];
let v1_iter = v1.iter();
let v2: Vec<_> = v1_iter.map(|x| x + 1).collect();
println!("{:?}", v2);
}
|
use crate::error::{NiaServerError, NiaServerResult};
use crate::protocol::{
NiaConvertable, NiaGetDefinedModifiersRequest, NiaModifierDescription,
Serializable,
};
use std::sync::MutexGuard;
use nia_interpreter_core::NiaInterpreterCommand;
use nia_interpreter_core::NiaInterpreterCommandResult;
use nia_interpreter_core::{
EventLoopHandle, NiaGetDefinedModifiersCommandResult,
};
use nia_protocol_rust::{GetDefinedModifiersResponse, ModifierDescription};
#[derive(Debug, Clone)]
pub struct NiaGetDefinedModifiersResponse {
command_result: NiaGetDefinedModifiersCommandResult,
}
impl NiaGetDefinedModifiersResponse {
fn try_from(
nia_define_modifier_request: NiaGetDefinedModifiersRequest,
event_loop_handle: MutexGuard<EventLoopHandle>,
) -> Result<NiaGetDefinedModifiersResponse, NiaServerError> {
let interpreter_command =
NiaInterpreterCommand::make_get_defined_modifiers();
event_loop_handle
.send_command(interpreter_command)
.map_err(|_| {
NiaServerError::interpreter_error(
"Error sending command to the interpreter.",
)
})?;
let execution_result =
event_loop_handle.receive_result().map_err(|_| {
NiaServerError::interpreter_error(
"Error reading command from the interpreter.",
)
})?;
let response = match execution_result {
NiaInterpreterCommandResult::GetDefinedModifiers(
command_result,
) => NiaGetDefinedModifiersResponse { command_result },
_ => {
return NiaServerError::interpreter_error(
"Unexpected command result.",
)
.into();
}
};
Ok(response)
}
pub fn from(
nia_define_modifier_request: NiaGetDefinedModifiersRequest,
event_loop_handle: MutexGuard<EventLoopHandle>,
) -> NiaGetDefinedModifiersResponse {
println!("{:?}", nia_define_modifier_request);
let try_result = NiaGetDefinedModifiersResponse::try_from(
nia_define_modifier_request,
event_loop_handle,
);
match try_result {
Ok(result) => result,
Err(error) => {
let message =
format!("Execution failure: {}", error.get_message());
let command_result =
NiaGetDefinedModifiersCommandResult::Failure(message);
NiaGetDefinedModifiersResponse { command_result }
}
}
}
}
impl
Serializable<
NiaGetDefinedModifiersResponse,
nia_protocol_rust::GetDefinedModifiersResponse,
> for NiaGetDefinedModifiersResponse
{
fn to_pb(&self) -> GetDefinedModifiersResponse {
let command_result = &self.command_result;
let mut get_defined_modifiers_response =
nia_protocol_rust::GetDefinedModifiersResponse::new();
match command_result {
NiaGetDefinedModifiersCommandResult::Success(defined_modifiers) => {
let modifiers = defined_modifiers
.iter()
.map(|interpreter_modifier| {
NiaModifierDescription::from_interpreter_repr(
interpreter_modifier,
)
.map(|modifier| modifier.to_pb())
})
.collect::<NiaServerResult<Vec<ModifierDescription>>>();
match modifiers {
Ok(modifiers) => {
let modifiers =
protobuf::RepeatedField::from(modifiers);
let mut success_result =
nia_protocol_rust::GetDefinedModifiersResponse_SuccessResult::new();
success_result.set_modifier_descriptions(modifiers);
get_defined_modifiers_response
.set_success_result(success_result);
}
Err(error) => {
let message = error.get_message();
let mut error_result =
nia_protocol_rust::GetDefinedModifiersResponse_ErrorResult::new();
error_result.set_message(protobuf::Chars::from(
message.clone(),
));
get_defined_modifiers_response
.set_error_result(error_result);
}
}
}
NiaGetDefinedModifiersCommandResult::Error(error_message) => {
let mut error_result =
nia_protocol_rust::GetDefinedModifiersResponse_ErrorResult::new();
error_result
.set_message(protobuf::Chars::from(error_message.clone()));
get_defined_modifiers_response.set_error_result(error_result);
}
NiaGetDefinedModifiersCommandResult::Failure(failure_message) => {
let mut failure_result =
nia_protocol_rust::GetDefinedModifiersResponse_FailureResult::new();
failure_result.set_message(protobuf::Chars::from(
failure_message.clone(),
));
get_defined_modifiers_response
.set_failure_result(failure_result);
}
}
get_defined_modifiers_response
}
fn from_pb(
object_pb: GetDefinedModifiersResponse,
) -> NiaServerResult<NiaGetDefinedModifiersResponse> {
unreachable!()
}
}
|
/// LeetCode Monthly Challenge problem for April 6th, 2021.
pub struct Solution {}
impl Solution {
/// Given an array length n where arr[i] = 2 * i + 1, returns the minimum
/// operations to make all elements equal.
///
/// At each operation two indices are chosen, x and y. Then 1 is subtracted
/// from arr[x], and 1 is added to arr[y].
///
/// # Examples
/// ```
/// # use crate::minimum_ops_equal_array::Solution;
/// let ex_one = Solution::min_operations(3);
/// let ex_two = Solution::min_operations(6);
///
/// assert_eq!(ex_one, 2);
/// assert_eq!(ex_two, 9);
/// ```
///
/// # Constraints
/// * 1 <= n <= 10^4
///
pub fn min_operations(n: i32) -> i32 {
let mut res = 0;
let (mut i, mut j) = (0, n - 1);
while i < j {
res += ((2 * j + 1) - (2 * i + 1)) / 2;
i += 1;
j -= 1;
}
res
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_min_operations() {
assert_eq!(
Solution::min_operations(3),
2
);
assert_eq!(
Solution::min_operations(6),
9
);
assert_eq!(
Solution::min_operations(51),
650
);
assert_eq!(
Solution::min_operations(273),
18632
);
assert_eq!(
Solution::min_operations(10000),
25000000
);
}
}
|
extern crate peroxide;
use peroxide::*;
use Number::F;
const S: [f64; 7] = [
0.038, 0.194, 0.425, 0.626, 1.253, 2.500, 3.740
];
fn main() {
let y = ml_matrix("0.05; 0.127; 0.094; 0.2122; 0.2729; 0.2665; 0.3317");
let beta_init = vec!(0.9, 0.2);
let mut beta = beta_init.to_matrix();
let mut j = jacobian(f, beta_init);
let mut y_hat = f(NumberVector::from_f64_vec(beta.data.clone()))
.to_f64_vec()
.to_matrix();
for i in 0 .. 10 {
let h: Matrix;
match j.pseudo_inv() {
Some(W) => h = W * (&y - &y_hat),
None => break,
}
beta = &beta + &h;
j = jacobian(f, beta.data.clone());
y_hat = f(NumberVector::from_f64_vec(beta.data.clone())).to_f64_vec().to_matrix();
}
beta.print();
}
fn f(beta: Vec<Number>) -> Vec<Number> {
let s: Vec<Number> = NumberVector::from_f64_vec(S.to_vec());
map(|x| beta[0] * x / (beta[1] + x), &s)
} |
use std::{
collections::{BTreeMap, BTreeSet}, mem,
};
use webidl;
use super::Result;
#[derive(Default)]
pub(crate) struct FirstPassRecord<'a> {
pub(crate) interfaces: BTreeSet<String>,
pub(crate) dictionaries: BTreeSet<String>,
pub(crate) enums: BTreeSet<String>,
pub(crate) mixins: BTreeMap<String, MixinData<'a>>,
}
#[derive(Default)]
pub(crate) struct MixinData<'a> {
pub(crate) non_partial: Option<&'a webidl::ast::NonPartialMixin>,
pub(crate) partials: Vec<&'a webidl::ast::PartialMixin>,
}
pub(crate) trait FirstPass {
fn first_pass<'a>(&'a self, record: &mut FirstPassRecord<'a>) -> Result<()>;
}
impl FirstPass for [webidl::ast::Definition] {
fn first_pass<'a>(&'a self, record: &mut FirstPassRecord<'a>) -> Result<()> {
for def in self {
def.first_pass(record)?;
}
Ok(())
}
}
impl FirstPass for webidl::ast::Definition {
fn first_pass<'a>(&'a self, record: &mut FirstPassRecord<'a>) -> Result<()> {
use webidl::ast::Definition::*;
match self {
Dictionary(dictionary) => dictionary.first_pass(record),
Enum(enum_) => enum_.first_pass(record),
Interface(interface) => interface.first_pass(record),
Mixin(mixin) => mixin.first_pass(record),
_ => {
// Other definitions aren't currently used in the first pass
Ok(())
}
}
}
}
impl FirstPass for webidl::ast::Dictionary {
fn first_pass<'a>(&'a self, record: &mut FirstPassRecord<'a>) -> Result<()> {
use webidl::ast::Dictionary::*;
match self {
NonPartial(dictionary) => dictionary.first_pass(record),
_ => {
// Other dictionaries aren't currently used in the first pass
Ok(())
}
}
}
}
impl FirstPass for webidl::ast::NonPartialDictionary {
fn first_pass<'a>(&'a self, record: &mut FirstPassRecord<'a>) -> Result<()> {
if record.dictionaries.insert(self.name.clone()) {
warn!("Encountered multiple declarations of {}", self.name);
}
Ok(())
}
}
impl FirstPass for webidl::ast::Enum {
fn first_pass<'a>(&'a self, record: &mut FirstPassRecord<'a>) -> Result<()> {
if record.enums.insert(self.name.clone()) {
warn!("Encountered multiple declarations of {}", self.name);
}
Ok(())
}
}
impl FirstPass for webidl::ast::Interface {
fn first_pass<'a>(&'a self, record: &mut FirstPassRecord<'a>) -> Result<()> {
use webidl::ast::Interface::*;
match self {
NonPartial(interface) => interface.first_pass(record),
_ => {
// Other interfaces aren't currently used in the first pass
Ok(())
}
}
}
}
impl FirstPass for webidl::ast::NonPartialInterface {
fn first_pass<'a>(&'a self, record: &mut FirstPassRecord<'a>) -> Result<()> {
if record.interfaces.insert(self.name.clone()) {
warn!("Encountered multiple declarations of {}", self.name);
}
Ok(())
}
}
impl FirstPass for webidl::ast::Mixin {
fn first_pass<'a>(&'a self, record: &mut FirstPassRecord<'a>) -> Result<()> {
use webidl::ast::Mixin::*;
match self {
NonPartial(mixin) => mixin.first_pass(record),
Partial(mixin) => mixin.first_pass(record),
}
}
}
impl FirstPass for webidl::ast::NonPartialMixin {
fn first_pass<'a>(&'a self, record: &mut FirstPassRecord<'a>) -> Result<()> {
let entry = record
.mixins
.entry(self.name.clone())
.or_insert_with(Default::default);
if mem::replace(&mut entry.non_partial, Some(self)).is_some() {
warn!(
"Encounterd multiple declarations of {}, using last encountered",
self.name
);
}
Ok(())
}
}
impl FirstPass for webidl::ast::PartialMixin {
fn first_pass<'a>(&'a self, record: &mut FirstPassRecord<'a>) -> Result<()> {
let entry = record
.mixins
.entry(self.name.clone())
.or_insert_with(Default::default);
entry.partials.push(self);
Ok(())
}
}
|
#[doc = "Register `CFR` writer"]
pub type W = crate::W<CFR_SPEC>;
#[doc = "Field `CEOCF` writer - Clear End of Conversion Flag"]
pub type CEOCF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CHPDF` writer - Clear Header Parsing Done Flag"]
pub type CHPDF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl W {
#[doc = "Bit 5 - Clear End of Conversion Flag"]
#[inline(always)]
#[must_use]
pub fn ceocf(&mut self) -> CEOCF_W<CFR_SPEC, 5> {
CEOCF_W::new(self)
}
#[doc = "Bit 6 - Clear Header Parsing Done Flag"]
#[inline(always)]
#[must_use]
pub fn chpdf(&mut self) -> CHPDF_W<CFR_SPEC, 6> {
CHPDF_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 = "JPEG clear flag register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cfr::W`](W). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct CFR_SPEC;
impl crate::RegisterSpec for CFR_SPEC {
type Ux = u32;
}
#[doc = "`write(|w| ..)` method takes [`cfr::W`](W) writer structure"]
impl crate::Writable for CFR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets CFR to value 0"]
impl crate::Resettable for CFR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
// build.rs
use grpc_build::build;
fn main() {
build("./protos", "src/protogen", true, true, true).unwrap();
}
|
use ad_hoc_sys as sys;
use std::str::from_utf8_unchecked_mut;
use std::slice::from_raw_parts_mut;
use std::mem::transmute;
use std::ptr::copy_nonoverlapping;
use crate::org::company as host;
use host::Client as packs;
#[repr(C)]
pub struct Meta0(pub u16, u32, u32, u32, pub u32, pub Option<unsafe extern "C" fn(pack: *mut sys::Pack, len: usize) -> *mut sys::Pack>, u16, u32, u16, [*const sys::Field; 0]);
unsafe impl std::marker::Sync for Meta0 {}
pub static mut DeviceVersion: Meta0 = Meta0(0, 0, 0, 0, 4, None, 0, 0, 0, []);
unsafe extern "C" fn meta1alloc(pack: *mut sys::Pack, len: usize) -> *mut sys::Pack { transmute(&host::Client::Stop::meta_) }
#[repr(C)]
pub struct Meta1(pub u16, u32, u32, u32, pub u32, pub Option<unsafe extern "C" fn(pack: *mut sys::Pack, len: usize) -> *mut sys::Pack>, u16, u32, u16, [*const sys::Field; 0]);
unsafe impl std::marker::Sync for Meta1 {}
pub static mut Stop: Meta1 = Meta1(1, 0, 0, 0, 0, Some(meta1alloc), 0, 0, 0, []);
unsafe extern "C" fn meta2alloc(pack: *mut sys::Pack, len: usize) -> *mut sys::Pack { transmute(&host::Client::Start::meta_) }
#[repr(C)]
pub struct Meta2(pub u16, u32, u32, u32, pub u32, pub Option<unsafe extern "C" fn(pack: *mut sys::Pack, len: usize) -> *mut sys::Pack>, u16, u32, u16, [*const sys::Field; 0]);
unsafe impl std::marker::Sync for Meta2 {}
pub static mut Start: Meta2 = Meta2(2, 0, 0, 0, 0, Some(meta2alloc), 0, 0, 0, []);
unsafe extern "C" fn meta3alloc(pack: *mut sys::Pack, len: usize) -> *mut sys::Pack { transmute(&host::Client::GetDeviceVersion::meta_) }
#[repr(C)]
pub struct Meta3(pub u16, u32, u32, u32, pub u32, pub Option<unsafe extern "C" fn(pack: *mut sys::Pack, len: usize) -> *mut sys::Pack>, u16, u32, u16, [*const sys::Field; 0]);
unsafe impl std::marker::Sync for Meta3 {}
pub static mut GetDeviceVersion: Meta3 = Meta3(3, 0, 0, 0, 0, Some(meta3alloc), 0, 0, 0, []);
unsafe extern "C" fn meta4alloc(pack: *mut sys::Pack, len: usize) -> *mut sys::Pack { transmute(&host::Client::GetConfiguration::meta_) }
#[repr(C)]
pub struct Meta4(pub u16, u32, u32, u32, pub u32, pub Option<unsafe extern "C" fn(pack: *mut sys::Pack, len: usize) -> *mut sys::Pack>, u16, u32, u16, [*const sys::Field; 0]);
unsafe impl std::marker::Sync for Meta4 {}
pub static mut GetConfiguration: Meta4 = Meta4(4, 0, 0, 0, 0, Some(meta4alloc), 0, 0, 0, []);
unsafe extern "C" fn meta5alloc(pack: *mut sys::Pack, len: usize) -> *mut sys::Pack { transmute(&host::Client::SetConfiguration::meta_) }
#[repr(C)]
pub struct Meta5(pub u16, u32, u32, u32, pub u32, pub Option<unsafe extern "C" fn(pack: *mut sys::Pack, len: usize) -> *mut sys::Pack>, u16, u32, u16, [*const sys::Field; 0]);
unsafe impl std::marker::Sync for Meta5 {}
pub static mut SetConfiguration: Meta5 = Meta5(5, 0, 0, 0, 0, Some(meta5alloc), 0, 0, 0, []);
#[repr(C)]
pub struct Meta6(pub u16, u32, u32, u32, pub u32, pub Option<unsafe extern "C" fn(pack: *mut sys::Pack, len: usize) -> *mut sys::Pack>, u16, u32, u16, [*const sys::Field; 0]);
unsafe impl std::marker::Sync for Meta6 {}
pub static mut BusConfiguration: Meta6 = Meta6(6, 0, 0, 0, 5, None, 0, 0, 0, []);
///[multiplier](Client::BusConfiguration::multiplier).
pub struct Item_V(pub *mut u8);
impl Item_V {
pub fn get(&mut self) -> u8 {
let src = &mut self.0;
let dst = sys::get_bytes(self.0, 0, 1 as usize) as u8;
(dst) as u8
}
pub fn set(&mut self, src: u8) { sys::set_bytes((src) as u64, 1 as usize, self.0, 0); }
}
///[time](Client::BusConfiguration::time).
pub struct Item_f(pub *mut u8);
impl Item_f {
pub fn get(&mut self) -> u16 {
let src = &mut self.0;
let dst = sys::get_bytes(self.0, 1, 2 as usize) as u16;
(dst) as u16
}
pub fn set(&mut self, src: u16) { sys::set_bytes((src) as u64, 2 as usize, self.0, 1); }
}
///[clk_khz](Client::BusConfiguration::clk_khz).
pub struct Item_l(pub *mut u8);
impl Item_l {
pub fn get(&mut self) -> u16 {
let src = &mut self.0;
let dst = sys::get_bytes(self.0, 3, 2 as usize) as u16;
(dst) as u16
}
pub fn set(&mut self, src: u16) { sys::set_bytes((src) as u64, 2 as usize, self.0, 3); }
}
#[repr(C)]
pub struct Meta7(pub u16, u32, u32, u32, pub u32, pub Option<unsafe extern "C" fn(pack: *mut sys::Pack, len: usize) -> *mut sys::Pack>, u16, u32, u16, [*const sys::Field; 0]);
unsafe impl std::marker::Sync for Meta7 {}
pub static mut InstructionsPack: Meta7 = Meta7(7, 0, 0, 0, 257, None, 0, 0, 0, []);
///[Length](Client::InstructionsPack::Length).
pub struct Item_A(pub *mut u8);
impl Item_A {
pub fn get(&mut self) -> u8 {
let src = &mut self.0;
let dst = sys::get_bytes(self.0, 0, 1 as usize) as u8;
(dst) as u8
}
pub fn set(&mut self, src: u8) { sys::set_bytes((src) as u64, 1 as usize, self.0, 0); }
}
///[Instructions](Client::InstructionsPack::Instructions).
pub struct ItemArray_C {
pub bytes: *mut u8,
pub len: usize,
pub offset: usize,
pub index: usize,
}
impl ItemArray_C {
pub fn get(&mut self, index: usize) -> u8 {
let dst = sys::get_bytes(self.bytes, self.offset + index * 1, 1 as usize) as u8;
(dst) as u8
}
pub fn set(&mut self, index: usize, src: u8) { sys::set_bytes((src) as u64, 1 as usize, self.bytes, self.offset + index * 1); }
}
impl Iterator for ItemArray_C {
type Item = u8;
fn next(&mut self) -> Option<<Self as Iterator>::Item> {
self.index = self.index.wrapping_add(1);
if self.index < self.len {
return Some(self.get(self.index));
}
self.index = !0;
None
}
}
#[repr(C)]
pub struct Meta8(pub u16, u32, u32, u32, pub u32, pub Option<unsafe extern "C" fn(pack: *mut sys::Pack, len: usize) -> *mut sys::Pack>, u16, u32, u16, [*const sys::Field; 0]);
unsafe impl std::marker::Sync for Meta8 {}
pub static mut DeviceError: Meta8 = Meta8(8, 0, 0, 0, 3, None, 0, 0, 0, []);
#[repr(C)]
pub struct Meta9(pub u16, u32, u32, u32, pub u32, pub Option<unsafe extern "C" fn(pack: *mut sys::Pack, len: usize) -> *mut sys::Pack>, u16, u32, u16, [*const sys::Field; 0]);
unsafe impl std::marker::Sync for Meta9 {}
pub static mut SensorsData: Meta9 = Meta9(9, 0, 0, 0, 2000, None, 0, 0, 0, []);
///[values](Client::SensorsData::values).
pub struct ItemArray_Z {
pub bytes: *const u8,
pub len: usize,
pub offset: usize,
pub index: usize,
}
impl ItemArray_Z {
pub fn get(&mut self, index: usize) -> u16 {
let dst = sys::get_bytes(self.bytes, self.offset + index * 2, 2 as usize) as u16;
(dst) as u16
}
}
impl Iterator for ItemArray_Z {
type Item = u16;
fn next(&mut self) -> Option<<Self as Iterator>::Item> {
self.index = self.index.wrapping_add(1);
if self.index < self.len {
return Some(self.get(self.index));
}
self.index = !0;
None
}
}
pub const RECEIVE_REQ_MAX_BYTES: u32 = 2000u32;
pub const RECEIVE_FULL_MAX_BYTES: u32 = 2000u32;
pub const SEND_REQ_MAX_BYTES: u32 = 257u32;
pub const SEND_FULL_MAX_BYTES: u32 = 257u32;
|
#[doc = "Reader of register SAI_ACR1"]
pub type R = crate::R<u32, super::SAI_ACR1>;
#[doc = "Writer for register SAI_ACR1"]
pub type W = crate::W<u32, super::SAI_ACR1>;
#[doc = "Register SAI_ACR1 `reset()`'s with value 0x40"]
impl crate::ResetValue for super::SAI_ACR1 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0x40
}
}
#[doc = "Reader of field `MODE`"]
pub type MODE_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `MODE`"]
pub struct MODE_W<'a> {
w: &'a mut W,
}
impl<'a> MODE_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x03) | ((value as u32) & 0x03);
self.w
}
}
#[doc = "Reader of field `PRTCFG`"]
pub type PRTCFG_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `PRTCFG`"]
pub struct PRTCFG_W<'a> {
w: &'a mut W,
}
impl<'a> PRTCFG_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 << 2)) | (((value as u32) & 0x03) << 2);
self.w
}
}
#[doc = "Reader of field `DS`"]
pub type DS_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `DS`"]
pub struct DS_W<'a> {
w: &'a mut W,
}
impl<'a> DS_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 & !(0x07 << 5)) | (((value as u32) & 0x07) << 5);
self.w
}
}
#[doc = "Reader of field `LSBFIRST`"]
pub type LSBFIRST_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LSBFIRST`"]
pub struct LSBFIRST_W<'a> {
w: &'a mut W,
}
impl<'a> LSBFIRST_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8);
self.w
}
}
#[doc = "Reader of field `CKSTR`"]
pub type CKSTR_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `CKSTR`"]
pub struct CKSTR_W<'a> {
w: &'a mut W,
}
impl<'a> CKSTR_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 << 9)) | (((value as u32) & 0x01) << 9);
self.w
}
}
#[doc = "Reader of field `SYNCEN`"]
pub type SYNCEN_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `SYNCEN`"]
pub struct SYNCEN_W<'a> {
w: &'a mut W,
}
impl<'a> SYNCEN_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 10)) | (((value as u32) & 0x03) << 10);
self.w
}
}
#[doc = "Reader of field `MONO`"]
pub type MONO_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `MONO`"]
pub struct MONO_W<'a> {
w: &'a mut W,
}
impl<'a> MONO_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12);
self.w
}
}
#[doc = "Reader of field `OUTDRIV`"]
pub type OUTDRIV_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `OUTDRIV`"]
pub struct OUTDRIV_W<'a> {
w: &'a mut W,
}
impl<'a> OUTDRIV_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 13)) | (((value as u32) & 0x01) << 13);
self.w
}
}
#[doc = "Reader of field `SAIXEN`"]
pub type SAIXEN_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SAIXEN`"]
pub struct SAIXEN_W<'a> {
w: &'a mut W,
}
impl<'a> SAIXEN_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16);
self.w
}
}
#[doc = "Reader of field `DMAEN`"]
pub type DMAEN_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DMAEN`"]
pub struct DMAEN_W<'a> {
w: &'a mut W,
}
impl<'a> DMAEN_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17);
self.w
}
}
#[doc = "Reader of field `NOMCK`"]
pub type NOMCK_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `NOMCK`"]
pub struct NOMCK_W<'a> {
w: &'a mut W,
}
impl<'a> NOMCK_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 19)) | (((value as u32) & 0x01) << 19);
self.w
}
}
#[doc = "Reader of field `MCKDIV`"]
pub type MCKDIV_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `MCKDIV`"]
pub struct MCKDIV_W<'a> {
w: &'a mut W,
}
impl<'a> MCKDIV_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x3f << 20)) | (((value as u32) & 0x3f) << 20);
self.w
}
}
#[doc = "Reader of field `OSR`"]
pub type OSR_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `OSR`"]
pub struct OSR_W<'a> {
w: &'a mut W,
}
impl<'a> OSR_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 26)) | (((value as u32) & 0x01) << 26);
self.w
}
}
#[doc = "Reader of field `MCKEN`"]
pub type MCKEN_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `MCKEN`"]
pub struct MCKEN_W<'a> {
w: &'a mut W,
}
impl<'a> MCKEN_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 << 27)) | (((value as u32) & 0x01) << 27);
self.w
}
}
impl R {
#[doc = "Bits 0:1 - SAIx audio block mode immediately"]
#[inline(always)]
pub fn mode(&self) -> MODE_R {
MODE_R::new((self.bits & 0x03) as u8)
}
#[doc = "Bits 2:3 - Protocol configuration. These bits are set and cleared by software. These bits have to be configured when the audio block is disabled."]
#[inline(always)]
pub fn prtcfg(&self) -> PRTCFG_R {
PRTCFG_R::new(((self.bits >> 2) & 0x03) as u8)
}
#[doc = "Bits 5:7 - Data size. These bits are set and cleared by software. These bits are ignored when the SPDIF protocols are selected (bit PRTCFG\\[1:0\\]), because the frame and the data size are fixed in such case. When the companding mode is selected through COMP\\[1:0\\]
bits, DS\\[1:0\\]
are ignored since the data size is fixed to 8 bits by the algorithm. These bits must be configured when the audio block is disabled."]
#[inline(always)]
pub fn ds(&self) -> DS_R {
DS_R::new(((self.bits >> 5) & 0x07) as u8)
}
#[doc = "Bit 8 - Least significant bit first. This bit is set and cleared by software. It must be configured when the audio block is disabled. This bit has no meaning in AC97 audio protocol since AC97 data are always transferred with the MSB first. This bit has no meaning in SPDIF audio protocol since in SPDIF data are always transferred with LSB first."]
#[inline(always)]
pub fn lsbfirst(&self) -> LSBFIRST_R {
LSBFIRST_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 9 - Clock strobing edge. This bit is set and cleared by software. It must be configured when the audio block is disabled. This bit has no meaning in SPDIF audio protocol."]
#[inline(always)]
pub fn ckstr(&self) -> CKSTR_R {
CKSTR_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bits 10:11 - Synchronization enable. These bits are set and cleared by software. They must be configured when the audio sub-block is disabled. Note: The audio sub-block should be configured as asynchronous when SPDIF mode is enabled."]
#[inline(always)]
pub fn syncen(&self) -> SYNCEN_R {
SYNCEN_R::new(((self.bits >> 10) & 0x03) as u8)
}
#[doc = "Bit 12 - Mono mode. This bit is set and cleared by software. It is meaningful only when the number of slots is equal to 2. When the mono mode is selected, slot 0 data are duplicated on slot 1 when the audio block operates as a transmitter. In reception mode, the slot1 is discarded and only the data received from slot 0 are stored. Refer to Section: Mono/stereo mode for more details."]
#[inline(always)]
pub fn mono(&self) -> MONO_R {
MONO_R::new(((self.bits >> 12) & 0x01) != 0)
}
#[doc = "Bit 13 - Output drive. This bit is set and cleared by software. Note: This bit has to be set before enabling the audio block and after the audio block configuration."]
#[inline(always)]
pub fn outdriv(&self) -> OUTDRIV_R {
OUTDRIV_R::new(((self.bits >> 13) & 0x01) != 0)
}
#[doc = "Bit 16 - Audio block enable where x is A or B. This bit is set by software. To switch off the audio block, the application software must program this bit to 0 and poll the bit till it reads back 0, meaning that the block is completely disabled. Before setting this bit to 1, check that it is set to 0, otherwise the enable command will not be taken into account. This bit allows to control the state of SAIx audio block. If it is disabled when an audio frame transfer is ongoing, the ongoing transfer completes and the cell is fully disabled at the end of this audio frame transfer. Note: When SAIx block is configured in master mode, the clock must be present on the input of SAIx before setting SAIXEN bit."]
#[inline(always)]
pub fn saixen(&self) -> SAIXEN_R {
SAIXEN_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bit 17 - DMA enable. This bit is set and cleared by software. Note: Since the audio block defaults to operate as a transmitter after reset, the MODE\\[1:0\\]
bits must be configured before setting DMAEN to avoid a DMA request in receiver mode."]
#[inline(always)]
pub fn dmaen(&self) -> DMAEN_R {
DMAEN_R::new(((self.bits >> 17) & 0x01) != 0)
}
#[doc = "Bit 19 - No divider"]
#[inline(always)]
pub fn nomck(&self) -> NOMCK_R {
NOMCK_R::new(((self.bits >> 19) & 0x01) != 0)
}
#[doc = "Bits 20:25 - Master clock divider. These bits are set and cleared by software. These bits are meaningless when the audio block operates in slave mode. They have to be configured when the audio block is disabled. Others: the master clock frequency is calculated accordingly to the following formula:"]
#[inline(always)]
pub fn mckdiv(&self) -> MCKDIV_R {
MCKDIV_R::new(((self.bits >> 20) & 0x3f) as u8)
}
#[doc = "Bit 26 - Oversampling ratio for master clock"]
#[inline(always)]
pub fn osr(&self) -> OSR_R {
OSR_R::new(((self.bits >> 26) & 0x01) != 0)
}
#[doc = "Bit 27 - MCKEN"]
#[inline(always)]
pub fn mcken(&self) -> MCKEN_R {
MCKEN_R::new(((self.bits >> 27) & 0x01) != 0)
}
}
impl W {
#[doc = "Bits 0:1 - SAIx audio block mode immediately"]
#[inline(always)]
pub fn mode(&mut self) -> MODE_W {
MODE_W { w: self }
}
#[doc = "Bits 2:3 - Protocol configuration. These bits are set and cleared by software. These bits have to be configured when the audio block is disabled."]
#[inline(always)]
pub fn prtcfg(&mut self) -> PRTCFG_W {
PRTCFG_W { w: self }
}
#[doc = "Bits 5:7 - Data size. These bits are set and cleared by software. These bits are ignored when the SPDIF protocols are selected (bit PRTCFG\\[1:0\\]), because the frame and the data size are fixed in such case. When the companding mode is selected through COMP\\[1:0\\]
bits, DS\\[1:0\\]
are ignored since the data size is fixed to 8 bits by the algorithm. These bits must be configured when the audio block is disabled."]
#[inline(always)]
pub fn ds(&mut self) -> DS_W {
DS_W { w: self }
}
#[doc = "Bit 8 - Least significant bit first. This bit is set and cleared by software. It must be configured when the audio block is disabled. This bit has no meaning in AC97 audio protocol since AC97 data are always transferred with the MSB first. This bit has no meaning in SPDIF audio protocol since in SPDIF data are always transferred with LSB first."]
#[inline(always)]
pub fn lsbfirst(&mut self) -> LSBFIRST_W {
LSBFIRST_W { w: self }
}
#[doc = "Bit 9 - Clock strobing edge. This bit is set and cleared by software. It must be configured when the audio block is disabled. This bit has no meaning in SPDIF audio protocol."]
#[inline(always)]
pub fn ckstr(&mut self) -> CKSTR_W {
CKSTR_W { w: self }
}
#[doc = "Bits 10:11 - Synchronization enable. These bits are set and cleared by software. They must be configured when the audio sub-block is disabled. Note: The audio sub-block should be configured as asynchronous when SPDIF mode is enabled."]
#[inline(always)]
pub fn syncen(&mut self) -> SYNCEN_W {
SYNCEN_W { w: self }
}
#[doc = "Bit 12 - Mono mode. This bit is set and cleared by software. It is meaningful only when the number of slots is equal to 2. When the mono mode is selected, slot 0 data are duplicated on slot 1 when the audio block operates as a transmitter. In reception mode, the slot1 is discarded and only the data received from slot 0 are stored. Refer to Section: Mono/stereo mode for more details."]
#[inline(always)]
pub fn mono(&mut self) -> MONO_W {
MONO_W { w: self }
}
#[doc = "Bit 13 - Output drive. This bit is set and cleared by software. Note: This bit has to be set before enabling the audio block and after the audio block configuration."]
#[inline(always)]
pub fn outdriv(&mut self) -> OUTDRIV_W {
OUTDRIV_W { w: self }
}
#[doc = "Bit 16 - Audio block enable where x is A or B. This bit is set by software. To switch off the audio block, the application software must program this bit to 0 and poll the bit till it reads back 0, meaning that the block is completely disabled. Before setting this bit to 1, check that it is set to 0, otherwise the enable command will not be taken into account. This bit allows to control the state of SAIx audio block. If it is disabled when an audio frame transfer is ongoing, the ongoing transfer completes and the cell is fully disabled at the end of this audio frame transfer. Note: When SAIx block is configured in master mode, the clock must be present on the input of SAIx before setting SAIXEN bit."]
#[inline(always)]
pub fn saixen(&mut self) -> SAIXEN_W {
SAIXEN_W { w: self }
}
#[doc = "Bit 17 - DMA enable. This bit is set and cleared by software. Note: Since the audio block defaults to operate as a transmitter after reset, the MODE\\[1:0\\]
bits must be configured before setting DMAEN to avoid a DMA request in receiver mode."]
#[inline(always)]
pub fn dmaen(&mut self) -> DMAEN_W {
DMAEN_W { w: self }
}
#[doc = "Bit 19 - No divider"]
#[inline(always)]
pub fn nomck(&mut self) -> NOMCK_W {
NOMCK_W { w: self }
}
#[doc = "Bits 20:25 - Master clock divider. These bits are set and cleared by software. These bits are meaningless when the audio block operates in slave mode. They have to be configured when the audio block is disabled. Others: the master clock frequency is calculated accordingly to the following formula:"]
#[inline(always)]
pub fn mckdiv(&mut self) -> MCKDIV_W {
MCKDIV_W { w: self }
}
#[doc = "Bit 26 - Oversampling ratio for master clock"]
#[inline(always)]
pub fn osr(&mut self) -> OSR_W {
OSR_W { w: self }
}
#[doc = "Bit 27 - MCKEN"]
#[inline(always)]
pub fn mcken(&mut self) -> MCKEN_W {
MCKEN_W { w: self }
}
}
|
use std::fmt::Display;
use chrono::{DateTime, Utc};
pub enum DebugMessageType {
Log=0,
Warning=1,
Error=2,
}
pub struct DebugMessage {
pub message: String,
pub time: DateTime<Utc>,
pub msg_type: DebugMessageType
}
impl Display for DebugMessage {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let time = self.time.format("%H:%M:%S");
write!(f, "{}: {}", time, self.message)
}
} |
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use anyhow::{bail, Result};
use scs::SCSCodec;
use starcoin_types::account_address::AccountAddress;
use std::fs::OpenOptions;
use std::path::Path;
use std::{
fs,
fs::File,
io::{Read, Write},
path::PathBuf,
};
use wallet_api::WalletAccount;
use wallet_api::WalletStore;
pub const DEFAULT_ACCOUNT_FILE_NAME: &str = "account";
/// Save wallet to disk file.
/// Use one dir per account.
pub struct FileWalletStore {
root_path: PathBuf,
}
impl FileWalletStore {
pub fn new<P: AsRef<Path>>(path: P) -> Self {
let path = path.as_ref();
if !path.is_dir() {
fs::create_dir(path).expect("Create wallet dir fail.");
}
Self {
root_path: path.to_owned(),
}
}
fn get_path(&self, address: &AccountAddress, key: &str, is_create: bool) -> Result<PathBuf> {
let path_str = address.to_string();
let path = self.root_path.join(path_str);
if !path.is_dir() && is_create {
fs::create_dir(path.as_path())?;
}
let path = path.join(key);
Ok(path)
}
fn account_dirs(&self) -> Vec<PathBuf> {
//get account dir from root path
let root_dir = &self.root_path;
let mut result = vec![];
if let Ok(paths) = fs::read_dir(root_dir) {
for path in paths {
let tmp_path = path.unwrap().path();
let tmp_path = tmp_path.join(DEFAULT_ACCOUNT_FILE_NAME);
result.push(tmp_path);
}
}
result
}
}
impl WalletStore for FileWalletStore {
fn get_account(&self, address: &AccountAddress) -> Result<Option<WalletAccount>> {
let path = self.get_path(address, DEFAULT_ACCOUNT_FILE_NAME, false)?;
if path.exists() {
let file = File::open(&path);
match file {
Ok(mut file) => {
let mut buffer = vec![];
file.read_to_end(&mut buffer)?;
let wallet_account = WalletAccount::decode(buffer.as_slice())?;
Ok(Some(wallet_account))
}
Err(e) => {
bail!("open file err: {}", e);
}
}
} else {
Ok(None)
}
}
fn save_account(&self, account: WalletAccount) -> Result<()> {
let mut file = OpenOptions::new().write(true).create(true).open(
self.get_path(&account.address, DEFAULT_ACCOUNT_FILE_NAME, true)
.unwrap(),
)?;
file.write_all(&scs::to_bytes(&account)?)?;
file.flush()?;
Ok(())
}
fn remove_account(&self, address: &AccountAddress) -> Result<()> {
let path_str = address.to_string();
let path = self.root_path.join(path_str);
if path.is_dir() {
fs::remove_dir_all(path)?;
}
Ok(())
}
fn get_accounts(&self) -> Result<Vec<WalletAccount>> {
// get account dir
let mut result = vec![];
let account_dirs = self.account_dirs();
for dir in account_dirs {
let mut file = File::open(&dir)?;
let mut buffer = vec![];
file.read_to_end(&mut buffer)?;
result.push(WalletAccount::decode(buffer.as_slice()).unwrap());
}
Ok(result)
}
fn save_to_account(&self, address: &AccountAddress, key: String, value: Vec<u8>) -> Result<()> {
let mut file = OpenOptions::new()
.write(true)
.create(true)
.open(self.get_path(address, &key, true).unwrap())?;
file.write_all(value.as_slice())?;
file.flush()?;
Ok(())
}
fn get_from_account(&self, address: &AccountAddress, key: &str) -> Result<Option<Vec<u8>>> {
let path = self.get_path(address, key, false).unwrap();
if !path.as_os_str().is_empty() {
let mut file = File::open(&path)?;
let mut buffer = vec![];
file.read_to_end(&mut buffer)?;
Ok(Option::from(buffer))
} else {
Ok(None)
}
}
}
|
//! TODO:Describe what is different from audio
// TODO: Defines distance from A4. i8 looks like a good option so not sure if a
// custom struct is required.
// TODO: Technically this can be any type capable of adding +1/-1.
type Pitch = i8;
// TODO:
pub struct PitchSystem<T> {
// TODO: concert pitch, pitch standard
pub basic: T
}
// TODO: Standard concert pitch
pub const A440: PitchSystem::<f64> = PitchSystem::<f64> {
basic: 440.0
};
// TODO:
pub trait PitchSynthesis<T> {
fn synthesize(self, _: Pitch) -> T;
}
// TODO:
// impl<T: Div + From<U>, U> PitchSynthesis<T> for PitchSystem<T> {
// fn synthesize(self, pitch: U) -> T {
// // TODO: 2 ** (pitch / 12) * self.basic
// }
// }
// TODO:Technically note can be considered as a basic pitch, accepting octave
// as an argument and modified by accidentals (sharp and flat), e.g. C(4).sharp.sharp.
// May be some unary operators can be used instead if sharp/flat.
// pub enum Note { C, D, E, F, G, A, H }
|
use kvs::Command;
use kvs::Result;
use serde_json;
use std::io::{BufReader, BufWriter, Read, Write};
use std::net::TcpStream;
use std::process::exit;
use structopt::StructOpt;
#[derive(StructOpt, Debug)]
struct ClientOpt {
#[structopt(subcommand)]
cmd: Command,
#[structopt(long, default_value = "127.0.0.1:4000", global = true)]
addr: String,
}
fn main() -> Result<()> {
let opt = ClientOpt::from_args();
let stream = TcpStream::connect(opt.addr)?;
let mut reader = BufReader::new(stream.try_clone()?);
let mut writer = BufWriter::new(stream);
match opt.cmd {
Command::Set { key: _, value: _ } => {
let cmd = serde_json::to_string(&opt.cmd)?;
writer.write(cmd.as_bytes())?;
writer.flush()?;
Ok(())
}
Command::Get { key: _ } => {
let cmd = serde_json::to_string(&opt.cmd)?;
writer.write(cmd.as_bytes())?;
writer.flush()?;
let mut response = String::new();
reader.read_to_string(&mut response)?;
println!("{}", response);
Ok(())
}
Command::Rm { key: _ } => {
let cmd = serde_json::to_string(&opt.cmd)?;
writer.write(cmd.as_bytes())?;
writer.flush()?;
let mut response = String::new();
reader.read_to_string(&mut response)?;
if response.len() > 0 {
eprintln!("{}", response);
exit(1);
}
Ok(())
}
}
}
|
use std::io::{self, Read};
use std::sync::mpsc::{Sender, Receiver, channel};
use std::collections::HashMap;
use std::thread;
use std::time::Duration;
#[derive(Debug, Clone, Copy)]
struct Ridx(char);
#[derive(Debug, Clone, Copy)]
enum Operand {
Register(Ridx),
Constant(i64),
}
#[derive(Debug, Clone, Copy)]
enum Instruction {
Set(Ridx, Operand),
Add(Ridx, Operand),
Mul(Ridx, Operand),
Mod(Ridx, Operand),
Jgz(Operand, Operand),
Snd(Ridx),
Rcv(Ridx),
}
#[derive(Debug)]
struct Machine {
regs: HashMap<char, i64>,
pc: isize,
last_played: i64,
lock_tx: Sender<Report>,
tx: Sender<i64>,
rx: Receiver<i64>,
id: usize,
}
impl Machine {
fn step(&mut self, inst: Instruction) {
self.pc += 1;
use Instruction::*;
match inst {
Set(Ridx(r), operand) => {
let val = self.reg_or_con(operand);
*self.regs.entry(r).or_insert(0) = val;
}
Add(Ridx(r), operand) => {
let val = self.reg_or_con(operand);
*self.regs.entry(r).or_insert(0) += val;
}
Mul(Ridx(r), operand) => {
let val = self.reg_or_con(operand);
*self.regs.entry(r).or_insert(0) *= val;
}
Mod(Ridx(r), operand) => {
let val = self.reg_or_con(operand);
*self.regs.entry(r).or_insert(0) %= val;
}
Jgz(operand1, operand2) => {
let val = self.reg_or_con(operand2);
let con = self.reg_or_con(operand1);
if con > 0 {
self.pc -= 1;
self.pc += val as isize;
}
}
Snd(Ridx(r)) => {
self.tx.send(*self.regs.entry(r).or_insert(0));
match self.id {
1 => {self.lock_tx.send(Report::P1Snd);}
0 => {}
_ => panic!("Unknown Threadid")
};
}
Rcv(Ridx(r)) => {
let val = self.rx.recv().unwrap();
*self.regs.entry(r).or_insert(0) = val;
}
}
}
fn reg_or_con(&mut self, op: Operand) -> i64 {
use Operand::*;
match op {
Register(Ridx(idx)) => {
*self.regs.entry(idx).or_insert(0)
}
Constant(con) => con,
}
}
fn run(&mut self, instr: Vec<Instruction>) {
loop {
if self.pc < 0 || self.pc >= instr.len() as isize { break }
let pc = self.pc;
self.step(instr[pc as usize]);
}
}
}
enum Report {
P1Snd,
}
fn main() {
let mut input = String::new();
io::stdin().read_to_string(&mut input).unwrap();
let inp = parse(&input);
let (lock_tx, lock_rx) = channel();
let (p0_tx, p1_rx) = channel();
let (p1_tx, p0_rx) = channel();
let lock_tx2 = lock_tx.clone();
let inp2 = inp.clone();
//p0
thread::spawn(move || {
let mut machine = Machine {
regs: HashMap::new(),
pc: 0,
last_played: 0,
lock_tx: lock_tx,
tx: p0_tx,
rx: p0_rx,
id: 0,
};
machine.run(inp);
});
//P1
thread::spawn(move || {
let mut machine = Machine {
regs: HashMap::new(),
pc: 0,
last_played: 0,
lock_tx: lock_tx2,
tx: p1_tx,
rx: p1_rx,
id: 1,
};
machine.regs.insert('p', 1);
machine.run(inp2);
});
let mut counter = 0;
loop {
match lock_rx.recv_timeout(Duration::from_millis(500)) {
Err(_) => break,
Ok(_) => {
counter += 1;
}
}
}
println!("{}", counter);
}
fn parse_reg(val: Option<&str>) -> Ridx {
let val = val.unwrap();
Ridx(val.chars().next().unwrap())
}
fn parse_op(val: Option<&str>) -> Operand {
let val = val.unwrap();
match val.chars().next().unwrap().is_alphabetic() {
true => Operand::Register(Ridx(val.chars().next().unwrap())),
false => Operand::Constant(val.parse().unwrap()),
}
}
fn parse(inp: &str) -> Vec<Instruction> {
use Instruction::*;
let lines: Vec<_> = inp.trim().split("\n").collect();
let mut res = vec![];
for line in lines {
let (op, ops) = line.split_at(4);
let mut ops = ops.trim().split_whitespace();
let ins = match op.trim() {
"snd" => Snd(parse_reg(ops.next())),
"add" => Add(parse_reg(ops.next()), parse_op(ops.next())),
"set" => Set(parse_reg(ops.next()), parse_op(ops.next())),
"mul" => Mul(parse_reg(ops.next()), parse_op(ops.next())),
"mod" => Mod(parse_reg(ops.next()), parse_op(ops.next())),
"rcv" => Rcv(parse_reg(ops.next())),
"jgz" => Jgz(parse_op(ops.next()), parse_op(ops.next())),
_ => panic!("Unknown Instruction")
};
res.push(ins);
}
res
} |
fn is_rotation(s1: &str, s2: &str) -> bool {
let mut s1s1 = s1.to_owned().clone();
s1s1.push_str(s1);
s1s1.contains(s2)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_1() {
assert!(is_rotation("totem", "temto"));
}
#[test]
fn test_2() {
assert!(!is_rotation("nexloob", "nealoob"));
}
}
|
fn main() {
use std::mem;
let color = "green";
let print = || println!("`color`: {}", color);
// call the closure using the borrow (&color)
print();
let _reborrow = &color;
print();
let _color_moved = color;
let mut count = 0;
let mut inc = || {
count += 1;
println!("`count`: {}", count);
};
// closure using mutable borrow
inc();
// closure still mutably borrows `count` because it is called later
// an attempt to reborrow will error out
inc();
let _count_reborrorwed = &mut count;
let movable = Box::new(3);
let consume = || {
println!("`moveable`: {:?}", movable);
mem::drop(movable);
};
consume();
let haystack = vec![1, 2, 3];
// Using `move` forces closure to take ownership of
// the captured variables
// Removing `move` causes closure to borrow immutably
// so haystack is still available
// ---
// let contains = move |needle| haystack.contains(needle);
let contains = |needle| haystack.contains(needle);
println!("{}", contains(&1));
println!("{}", contains(&4));
}
|
use chrono::{Local, NaiveDateTime};
use diesel::prelude::*;
use std::collections::HashMap;
use uuid::Uuid;
use crate::core::schema::transaction;
use crate::core::{
generate_uuid, Account, DbConnection, Money, Product, ServiceError, ServiceResult,
};
/// Represent a transaction
#[derive(Debug, Queryable, Insertable, Identifiable, AsChangeset, Serialize, Deserialize, Clone)]
#[table_name = "transaction"]
pub struct Transaction {
pub id: Uuid,
pub account_id: Uuid,
pub cashier_id: Option<Uuid>,
pub total: Money,
pub before_credit: Money,
pub after_credit: Money,
pub date: NaiveDateTime,
}
/// Execute a transaction on the given `account` with the given `total`
///
/// # Internal steps
/// * 1 Start a sql transaction
/// * 2 Requery the account credit
/// * 3 Calculate the new credit
/// * 4 Check if the account minimum_credit allows the new credit
/// * 5 Create and save the transaction (with optional cashier refernece)
/// * 6 Save the new credit to the account
fn execute_at(
conn: &DbConnection,
account: &mut Account,
cashier: Option<&Account>,
total: Money,
date: NaiveDateTime,
) -> ServiceResult<Transaction> {
use crate::core::schema::transaction::dsl;
// TODO: Are empty transaction useful? You can still assign products
/*
if total == 0 {
return Err(ServiceError::BadRequest(
"Empty transaction",
"Cannot perform a transaction with a total of zero".to_owned()
))
}
*/
let before_credit = account.credit;
let mut after_credit = account.credit;
let result = conn.build_transaction().serializable().run(|| {
let mut account = Account::get(conn, &account.id)?;
after_credit = account.credit + total;
if after_credit < account.minimum_credit && after_credit < account.credit {
return Err(ServiceError::InternalServerError(
"Transaction error",
"The transaction can not be performed. Check the account credit and minimum_credit"
.to_owned(),
));
}
let a = Transaction {
id: generate_uuid(),
account_id: account.id,
cashier_id: cashier.map(|c| c.id),
total,
before_credit,
after_credit,
date,
};
account.credit = after_credit;
diesel::insert_into(dsl::transaction)
.values(&a)
.execute(conn)?;
account.update(conn)?;
Ok(a)
});
if result.is_ok() {
account.credit = after_credit;
}
result
}
/// Execute a transaction on the given `account` with the given `total`
///
/// # Internal steps
/// * 1 Start a sql transaction
/// * 2 Requery the account credit
/// * 3 Calculate the new credit
/// * 4 Check if the account minimum_credit allows the new credit
/// * 5 Create and save the transaction (with optional cashier refernece)
/// * 6 Save the new credit to the account
pub fn execute(
conn: &DbConnection,
account: &mut Account,
cashier: Option<&Account>,
total: Money,
) -> ServiceResult<Transaction> {
execute_at(conn, account, cashier, total, Local::now().naive_local())
}
// Pagination reference: https://github.com/diesel-rs/diesel/blob/v1.3.0/examples/postgres/advanced-blog-cli/src/pagination.rs
/// List all transactions of a account between the given datetimes
pub fn get_by_account(
conn: &DbConnection,
account: &Account,
from: &NaiveDateTime,
to: &NaiveDateTime,
) -> ServiceResult<Vec<Transaction>> {
use crate::core::schema::transaction::dsl;
let results = dsl::transaction
.filter(
dsl::account_id
.eq(&account.id)
.and(dsl::date.between(from, to)),
)
.order(dsl::date.desc())
.load::<Transaction>(conn)?;
Ok(results)
}
pub fn get_by_account_and_id(
conn: &DbConnection,
account: &Account,
id: &Uuid,
) -> ServiceResult<Transaction> {
use crate::core::schema::transaction::dsl;
let mut results = dsl::transaction
.filter(dsl::account_id.eq(&account.id).and(dsl::id.eq(id)))
.load::<Transaction>(conn)?;
results.pop().ok_or_else(|| ServiceError::NotFound)
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(tag = "status")]
pub enum ValidationResult {
Ok,
InvalidTransactionBefore {
expected_credit: Money,
transaction_credit: Money,
transaction: Transaction,
},
InvalidTransactionAfter {
expected_credit: Money,
transaction_credit: Money,
transaction: Transaction,
},
InvalidSum {
expected: Money,
actual: Money,
},
NoData,
Error,
}
/// Check if the credit of an account is valid to its transactions
fn validate_account(conn: &DbConnection, account: &Account) -> ServiceResult<ValidationResult> {
use crate::core::schema::transaction::dsl;
conn.build_transaction().serializable().run(|| {
let account = Account::get(conn, &account.id)?;
let results = dsl::transaction
.filter(dsl::account_id.eq(&account.id))
.order(dsl::date.asc())
.load::<Transaction>(conn)?;
let mut last_credit = 0;
for transaction in results {
if last_credit != transaction.before_credit {
return Ok(ValidationResult::InvalidTransactionBefore {
expected_credit: last_credit,
transaction_credit: transaction.before_credit,
transaction,
});
}
if transaction.before_credit + transaction.total != transaction.after_credit {
return Ok(ValidationResult::InvalidTransactionAfter {
expected_credit: last_credit + transaction.total,
transaction_credit: transaction.after_credit,
transaction,
});
}
last_credit += transaction.total;
}
if last_credit != account.credit {
Ok(ValidationResult::InvalidSum {
expected: last_credit,
actual: account.credit,
})
} else {
Ok(ValidationResult::Ok)
}
})
}
/// List all accounts with validation erros of their credit to their transactions
pub fn validate_all(conn: &DbConnection) -> ServiceResult<HashMap<Uuid, ValidationResult>> {
let accounts = Account::all(conn)?;
let map = accounts
.into_iter()
.map(|a| {
let r = validate_account(conn, &a).unwrap_or(ValidationResult::Error);
(a.id, r)
})
.collect::<HashMap<_, _>>();
Ok(map)
}
impl Transaction {
/// Assign products with amounts to this transaction
pub fn add_products(
&self,
conn: &DbConnection,
products: Vec<(Product, i32)>,
) -> ServiceResult<()> {
use crate::core::schema::transaction_product::dsl;
let current_products = self
.get_products(&conn)?
.into_iter()
.collect::<HashMap<Product, i32>>();
for (product, amount) in products {
match current_products.get(&product) {
Some(current_amount) => {
diesel::update(
dsl::transaction_product.filter(
dsl::transaction
.eq(&self.id)
.and(dsl::product_id.eq(&product.id)),
),
)
.set(dsl::amount.eq(current_amount + amount))
.execute(conn)?;
}
None => {
diesel::insert_into(dsl::transaction_product)
.values((
dsl::transaction.eq(&self.id),
dsl::product_id.eq(&product.id),
dsl::amount.eq(amount),
))
.execute(conn)?;
}
}
}
Ok(())
}
/// Remove products with amounts from this transaction
pub fn remove_products(
&self,
conn: &DbConnection,
products: Vec<(Product, i32)>,
) -> ServiceResult<()> {
use crate::core::schema::transaction_product::dsl;
let current_products = self
.get_products(&conn)?
.into_iter()
.collect::<HashMap<Product, i32>>();
for (product, amount) in products {
if let Some(current_amount) = current_products.get(&product) {
if *current_amount <= amount {
diesel::delete(
dsl::transaction_product.filter(
dsl::transaction
.eq(&self.id)
.and(dsl::product_id.eq(&product.id)),
),
)
.execute(conn)?;
} else {
diesel::update(
dsl::transaction_product.filter(
dsl::transaction
.eq(&self.id)
.and(dsl::product_id.eq(&product.id)),
),
)
.set(dsl::amount.eq(current_amount - amount))
.execute(conn)?;
}
}
}
Ok(())
}
/// List assigned products with amounts of this transaction
pub fn get_products(&self, conn: &DbConnection) -> ServiceResult<Vec<(Product, i32)>> {
use crate::core::schema::transaction_product::dsl;
Ok(dsl::transaction_product
.filter(dsl::transaction.eq(&self.id))
.load::<(Uuid, Uuid, i32)>(conn)?
.into_iter()
.filter_map(|(_, p, a)| match Product::get(conn, &p) {
Ok(p) => Some((p, a)),
_ => None,
})
.collect())
}
pub fn all(conn: &DbConnection) -> ServiceResult<Vec<Transaction>> {
use crate::core::schema::transaction::dsl;
let results = dsl::transaction
.order(dsl::date.desc())
.load::<Transaction>(conn)?;
Ok(results)
}
}
pub fn generate_transactions(
conn: &DbConnection,
account: &mut Account,
from: NaiveDateTime,
to: NaiveDateTime,
count_per_day: u32,
avg_down: Money,
avg_up: Money,
) -> ServiceResult<()> {
use chrono::Duration;
use chrono::NaiveTime;
use rand::seq::SliceRandom;
let days = (to - from).num_days();
let start_date = from.date();
let products = Product::all(conn)?;
let mut rng = rand::thread_rng();
for day_offset in 0..days {
let offset = Duration::days(day_offset);
let date = start_date + offset;
for time_offset in 0..count_per_day {
let offset = 9.0 / ((count_per_day - 1) as f32) * time_offset as f32;
let hr = offset as u32;
let mn = ((offset - hr as f32) * 60.0) as u32;
let time = NaiveTime::from_hms(9 + hr, mn, 0);
let date_time = NaiveDateTime::new(date, time);
let mut seconds = 0;
let mut price = 0;
let mut transaction_products: HashMap<Product, i32> = HashMap::new();
while price < avg_down.abs() {
let p = products.choose(&mut rng);
if let Some(p) = p {
let pr = p.current_price;
if let Some(pr) = pr {
price += pr;
}
let amount = transaction_products.get(p).copied().unwrap_or(0) + 1;
transaction_products.insert(p.clone(), amount);
} else {
price = avg_down;
}
}
while account.credit - price < account.minimum_credit {
execute_at(
conn,
account,
None,
avg_up,
date_time + Duration::seconds(seconds),
)?;
seconds += 1;
}
let transaction = execute_at(
conn,
account,
None,
-price,
date_time + Duration::seconds(seconds),
)?;
transaction.add_products(
conn,
transaction_products
.into_iter()
.map(|(k, v)| (k, v))
.collect(),
)?;
}
}
Ok(())
}
|
#[macro_use] extern crate itertools;
fn main() {
let args: Vec<String> = std::env::args().collect();
let filename = &args[1];
println!("{}", filename);
let contents = std::fs::read_to_string(filename).expect("file not found");
// let values = contents.split('\n').filter(|x| !x.is_empty()).map(|x| x.parse::<i32>().unwrap());
let values = contents.split('\n').filter_map(|x| x.parse::<i32>().ok());
let values2 = values.clone();
let values3 = values.clone();
for (x, y, z) in iproduct!(values, values2, values3) {
if x + y + z == 2020
{
println!("{0}, {1}, {2}, {3}", x, y, z, x * y * z);
}
}
}
|
use crate::view_models;
pub struct PostProcessEffectMetaData
{
pub name: view_models::PostProcessEffects,
pub running_time: f32,
pub max_running_time: f32,
} |
// #[macro_use] extern crate quicli;
#[macro_use] extern crate failure;
#[macro_use] extern crate structopt;
mod error;
mod input;
mod output;
use error::{Error, ErrorKind, Result};
// main!(|args: input::RdisOpt, log_level: verbosity| {
// println!("{}", "Hello");
// });
fn main() -> Result<()> {
Ok(())
}
|
use parse::ParseError;
use rand::{Rand, Rng};
use std::fmt;
use std::str::FromStr;
/// A network name to identify nodes.
#[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct Name(pub u64);
impl Rand for Name {
fn rand<R: Rng>(rng: &mut R) -> Self {
Name(rng.gen())
}
}
impl fmt::Debug for Name {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let (b0, b1, b2) = (
(self.0 >> 56) as u8,
(self.0 >> 48) as u8,
(self.0 >> 40) as u8,
);
write!(fmt, "{:02x}{:02x}{:02x}...", b0, b1, b2)
}
}
/// A structure representing a network prefix - a simplified version of the Prefix struct from
/// `routing`
#[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct Prefix {
len: u8,
bits: u64,
}
impl Prefix {
pub const EMPTY: Self = Prefix { bits: 0, len: 0 };
pub fn len(&self) -> u8 {
self.len
}
pub fn extend(self, bit: u8) -> Prefix {
if self.len > 63 {
return self;
}
let bit = (u64::from(bit) & 1) << (63 - self.len);
Prefix {
bits: self.bits | bit,
len: self.len + 1,
}
}
pub fn shorten(self) -> Self {
if self.len < 1 {
return self;
}
let mask = self.len_mask() << 1;
Prefix {
bits: self.bits & mask,
len: self.len - 1,
}
}
pub fn split(self) -> [Prefix; 2] {
[self.extend(0), self.extend(1)]
}
pub fn sibling(self) -> Self {
if self.len > 0 {
self.with_flipped_bit(self.len - 1)
} else {
self
}
}
pub fn with_flipped_bit(self, bit: u8) -> Prefix {
let mask = 1 << (63 - bit);
Prefix {
bits: self.bits ^ mask,
len: self.len,
}
}
pub fn matches(&self, name: Name) -> bool {
(name.0 & self.len_mask()) ^ self.bits == 0
}
pub fn is_ancestor(&self, other: &Prefix) -> bool {
self.len <= other.len && self.matches(Name(other.bits))
}
#[allow(unused)]
pub fn is_descendant(&self, other: &Prefix) -> bool {
other.is_ancestor(self)
}
#[allow(unused)]
pub fn is_compatible_with(&self, other: &Prefix) -> bool {
self.is_ancestor(other) || self.is_descendant(other)
}
#[allow(unused)]
pub fn is_sibling(&self, other: &Prefix) -> bool {
if self.len > 0 {
(*self).with_flipped_bit(self.len - 1) == *other
} else {
false
}
}
#[allow(unused)]
pub fn is_neighbour(&self, other: &Prefix) -> bool {
let diff = self.bits ^ other.bits;
let bit = diff.leading_zeros() as u8;
if bit < self.len && bit < other.len {
let diff = self.with_flipped_bit(bit).bits ^ other.bits;
let bit = diff.leading_zeros() as u8;
bit >= self.len || bit >= other.len
} else {
false
}
}
pub fn substituted_in(&self, mut name: Name) -> Name {
let mask = self.len_mask();
name.0 &= !mask;
name.0 |= self.bits;
name
}
fn len_mask(&self) -> u64 {
if self.len == 0 {
0
} else {
(-1i64 as u64) << (64 - self.len)
}
}
}
impl FromStr for Prefix {
type Err = ParseError;
fn from_str(input: &str) -> Result<Self, Self::Err> {
let mut prefix = Self::EMPTY;
for c in input.chars() {
match c {
'0' => {
prefix = prefix.extend(0);
}
'1' => {
prefix = prefix.extend(1);
}
_ => {
return Err(ParseError);
}
}
}
Ok(prefix)
}
}
impl fmt::Display for Prefix {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
for i in 0..self.len {
let mask = 1 << (63 - i);
if self.bits & mask == 0 {
write!(fmt, "0")?;
} else {
write!(fmt, "1")?;
}
}
Ok(())
}
}
impl fmt::Debug for Prefix {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "Prefix({})", self)
}
}
|
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize};
use near_sdk::collections::LookupMap;
use near_sdk::serde_json::{self, json};
use near_sdk::wee_alloc::WeeAlloc;
use near_sdk::{env, near_bindgen, AccountId};
use near_sdk::{Promise, PromiseOrValue, PromiseResult};
#[global_allocator]
static ALLOC: WeeAlloc = WeeAlloc::INIT;
const SINGLE_CALL_GAS: u64 = 50_000_000_000_000; // 5 x 10^13
const DEFAULT_GAS: u64 = 300_000_000_000_000;
#[near_bindgen]
#[derive(BorshDeserialize, BorshSerialize)]
pub struct Flags {
pub raising_access_controller: AccountId,
pub owner: AccountId,
pending_owner: AccountId,
flags: LookupMap<AccountId, bool>,
pub check_enabled: bool,
access_list: LookupMap<AccountId, bool>,
}
impl Default for Flags {
fn default() -> Self {
panic!("Flags should be initialized before usage")
}
}
#[near_bindgen]
impl Flags {
#[init]
pub fn new(owner_id: AccountId, rac_address: AccountId) -> Self {
assert!(
env::is_valid_account_id(owner_id.as_bytes()),
"Owner's account ID is invalid"
);
assert!(
rac_address == "" || env::is_valid_account_id(rac_address.as_bytes()),
"rac_address account ID is invalid"
);
assert!(!env::state_exists(), "Already initialized");
let mut result = Self {
raising_access_controller: "".to_string(),
owner: owner_id,
pending_owner: "".to_string(),
flags: LookupMap::new(b"flags".to_vec()),
check_enabled: true,
access_list: LookupMap::new(b"access_list".to_vec()),
};
result.set_raising_access_controller(rac_address);
result
}
pub fn get_flag(&self, subject: AccountId) -> bool {
self.check_access();
let flag = self.flags.get(&subject);
if flag.is_none() {
false
} else {
flag.unwrap()
}
}
pub fn get_flags(&self, subjects: Vec<AccountId>) -> Vec<bool> {
self.check_access();
// let subjects_length: usize = subjects.len();
// let mut responses: Vec<bool> = Vec::with_capacity(subjects_length);
// let subjects_length: usize = subjects.len();
let mut responses: Vec<bool> = Vec::new();
for i in 0..subjects.len() {
let flag = self.flags.get(&subjects[i]);
if flag.is_none() {
responses.push(false);
} else {
responses.push(flag.unwrap());
}
}
return responses;
}
pub fn raise_flag(&mut self, subject: AccountId) {
if env::predecessor_account_id() == self.owner {
self.try_to_raise_flag(subject);
} else {
assert!(
env::is_valid_account_id(self.raising_access_controller.as_bytes()),
"Not allowed to raise flags"
);
let has_access_promise = env::promise_create(
self.raising_access_controller.clone(),
b"has_access",
json!({ "_user": env::predecessor_account_id() })
.to_string()
.as_bytes(),
0,
SINGLE_CALL_GAS,
);
let has_access_promise_results = env::promise_then(
has_access_promise,
env::current_account_id(),
b"allowed_to_raise_flag_promise_result",
json!({ "subject": subject }).to_string().as_bytes(),
0,
SINGLE_CALL_GAS,
);
env::promise_return(has_access_promise_results);
}
}
pub fn raise_flags(&mut self, subjects: Vec<AccountId>) {
if env::predecessor_account_id() == self.owner {
for i in 0..subjects.len() {
self.try_to_raise_flag(subjects[i].clone());
}
} else {
assert!(
env::is_valid_account_id(self.raising_access_controller.as_bytes()),
"Not allowed to raise flags"
);
let has_access_promise = env::promise_create(
self.raising_access_controller.clone(),
b"has_access",
json!({ "_user": env::predecessor_account_id() })
.to_string()
.as_bytes(),
0,
SINGLE_CALL_GAS,
);
let has_access_promise_results = env::promise_then(
has_access_promise,
env::current_account_id(),
b"allowed_to_raise_flags_promise_result",
json!({ "subjects": subjects }).to_string().as_bytes(),
0,
SINGLE_CALL_GAS,
);
env::promise_return(has_access_promise_results);
}
}
pub fn allowed_to_raise_flag_promise_result(&mut self, subject: AccountId) {
// assert_eq!(env::current_account_id(), env::predecessor_account_id());
assert_eq!(env::promise_results_count(), 1);
let get_allowed_to_raise_flags_promise_reult: Vec<u8> = match env::promise_result(0) {
PromiseResult::Successful(_x) => _x,
_x => panic!("Promise with index 0 failed"),
};
let allowed: bool =
serde_json::from_slice(&get_allowed_to_raise_flags_promise_reult).unwrap();
if !allowed {
env::panic(b"Not allowed to raise flags");
} else {
self.try_to_raise_flag(subject);
}
}
pub fn allowed_to_raise_flags_promise_result(&mut self, subjects: Vec<AccountId>) {
// assert_eq!(env::current_account_id(), env::predecessor_account_id());
assert_eq!(env::promise_results_count(), 1);
let get_allowed_to_raise_flags_promise_reult: Vec<u8> = match env::promise_result(0) {
PromiseResult::Successful(_x) => _x,
_x => panic!("Promise with index 0 failed"),
};
let allowed: bool =
serde_json::from_slice(&get_allowed_to_raise_flags_promise_reult).unwrap();
if !allowed {
env::panic(b"Not allowed to raise flags");
} else {
for i in 0..subjects.len() {
self.try_to_raise_flag(subjects[i].clone());
}
}
}
pub fn lower_flags(&mut self, subjects: Vec<AccountId>) {
self.only_owner();
for i in 0..subjects.len() {
let subject = self.flags.get(&subjects[i]);
if subject.is_none() {
env::panic(b"The subject doesnt exist");
}
if subject.unwrap() == true {
self.flags.insert(&subjects[i], &false);
env::log(format!("{}", &subjects[i]).as_bytes());
}
}
}
pub fn get_raising_access_controller(&self) -> String {
self.raising_access_controller.clone()
}
pub fn set_raising_access_controller(&mut self, rac_address: AccountId) {
if env::predecessor_account_id() != env::current_account_id() {
self.only_owner();
}
let previous: AccountId = String::from(&self.raising_access_controller) as AccountId;
let init_rac_address: AccountId = rac_address.clone();
if previous != rac_address {
self.raising_access_controller = rac_address;
env::log(format!("{}, {}", previous, init_rac_address).as_bytes());
}
}
pub fn has_access(&self, _user: AccountId) -> bool {
if !self.check_enabled {
!self.check_enabled
} else {
let user_option = self.access_list.get(&_user);
if user_option.is_none() {
return false;
}
let user = user_option.unwrap();
user
}
}
pub fn add_access(&mut self, _user: AccountId) {
self.only_owner();
let user_option = self.access_list.get(&_user);
if user_option.is_none() {
self.access_list.insert(&_user, &true);
}
}
pub fn remove_access(&mut self, _user: AccountId) {
self.only_owner();
let user_option = self.access_list.get(&_user);
if user_option.is_none() {
env::panic(b"Did not find the user to remove.");
}
self.access_list.insert(&_user, &false);
}
pub fn enable_access_check(&mut self) {
self.only_owner();
if !self.check_enabled {
self.check_enabled = true;
}
}
pub fn disable_access_check(&mut self) {
self.only_owner();
if self.check_enabled {
self.check_enabled = false;
}
}
// Commented out to get code working
// fn allowed_to_raise_flags(&self) -> PromiseOrValue<bool> {
// }
fn try_to_raise_flag(&mut self, subject: AccountId) {
let flag = self.flags.get(&subject);
if flag.is_none() {
self.flags.insert(&subject, &true);
env::log(format!("{}", &subject).as_bytes());
} else {
if flag.unwrap() == false {
self.flags.insert(&subject, &true);
env::log(format!("{}", &subject).as_bytes());
}
}
}
fn only_owner(&self) {
assert_eq!(
self.owner,
env::predecessor_account_id(),
"Only callable by owner."
);
}
fn check_access(&self) {
assert!(self.has_access(env::predecessor_account_id()), "No access")
}
pub fn transfer_ownership(&mut self, _to: AccountId) {
self.only_owner();
let init_to: AccountId = _to.clone();
self.pending_owner = _to;
env::log(format!("{}, {}", self.owner, init_to).as_bytes());
}
pub fn accept_ownership(&mut self) {
assert_eq!(
env::predecessor_account_id(),
self.pending_owner,
"Must be proposed owner"
);
let old_owner: AccountId = self.owner.clone();
self.owner = env::predecessor_account_id();
self.pending_owner = "".to_string();
env::log(format!("{}, {}", old_owner, env::predecessor_account_id()).as_bytes());
}
}
|
use crate::MyApp;
use seed::{*, prelude::*};
use crate::traits::component_trait::Component;
use crate::messages::Msg;
//Header
pub struct HeaderComponent;
impl Component<MyApp, Msg> for HeaderComponent {
fn view(_model: &MyApp) -> Node<Msg> {
div![
id!("header"),
"Todo App"
]
}
}
|
use anyhow::Context;
use rusqlite::Transaction;
pub(crate) fn migrate(transaction: &Transaction<'_>) -> anyhow::Result<()> {
// Add new columns to the blocks table
transaction
.execute_batch(
r"ALTER TABLE starknet_blocks ADD COLUMN gas_price BLOB NOT NULL
DEFAULT X'00000000000000000000000000000000';
ALTER TABLE starknet_blocks ADD COLUMN sequencer_address BLOB NOT NULL
DEFAULT X'0000000000000000000000000000000000000000000000000000000000000000';",
)
.context("Add columns gas_price and starknet_address to starknet_blocks table")?;
Ok(())
}
|
use crate::features::syntax::StatementFeature;
use crate::parse::visitor::tests::assert_stmt_feature;
#[test]
fn labelled() {
assert_stmt_feature("label: while(true);", StatementFeature::LabelledStatement);
}
|
fn main() {
let x: i32 = 5;
print_number(x);
let x1: i32 = 10;
let x2: i32 = 11;
print_sum(x1, x2);
print_number(add_one(x1));
}
fn print_number(x: i32){
println!("The number is {}",x)
}
fn print_sum(x: i32, y: i32){
print_number(x+y)
}
fn add_one(x: i32) -> i32 {
x+1 // using a semicolon here returns an error
} |
use k8s_openapi::apiextensions_apiserver::pkg::apis::apiextensions::v1::CustomResourceDefinition;
use kube::{
api::{Api, Patch, PatchParams},
core::crd::merge_crds,
runtime::wait::{await_condition, conditions},
Client, CustomResource, CustomResourceExt, ResourceExt,
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use tracing::*;
mod v1 {
use super::*;
// spec that is forwards compatible with v2 (can upgrade by truncating)
#[derive(CustomResource, Serialize, Deserialize, Default, Debug, Clone, JsonSchema)]
#[kube(group = "kube.rs", version = "v1", kind = "ManyDerive", namespaced)]
pub struct ManyDeriveSpec {
pub name: String,
pub oldprop: u32,
}
}
mod v2 {
// spec that is NOT backwards compatible with v1 (cannot retrieve oldprop if truncated)
use super::*;
#[derive(CustomResource, Serialize, Deserialize, Default, Debug, Clone, JsonSchema)]
#[kube(group = "kube.rs", version = "v2", kind = "ManyDerive", namespaced)]
pub struct ManyDeriveSpec {
pub name: String,
pub extra: Option<String>,
}
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
tracing_subscriber::fmt::init();
let client = Client::try_default().await?;
let ssapply = PatchParams::apply("crd_derive_multi").force();
let crd1 = v1::ManyDerive::crd();
let crd2 = v2::ManyDerive::crd();
let all_crds = vec![crd1.clone(), crd2.clone()];
// apply schema where v1 is the stored version
apply_crd(client.clone(), merge_crds(all_crds.clone(), "v1")?).await?;
// create apis
let v1api: Api<v1::ManyDerive> = Api::default_namespaced(client.clone());
let v2api: Api<v2::ManyDerive> = Api::default_namespaced(client.clone());
// create a v1 version
let v1m = v1::ManyDerive::new("old", v1::ManyDeriveSpec {
name: "i am old".into(),
oldprop: 5,
});
let oldvarv1 = v1api.patch("old", &ssapply, &Patch::Apply(&v1m)).await?;
info!("old instance on v1: {:?}", oldvarv1.spec);
let oldvarv2 = v2api.get("old").await?;
info!("old instance on v2 truncates: {:?}", oldvarv2.spec);
// create a v2 version
let v2m = v2::ManyDerive::new("new", v2::ManyDeriveSpec {
name: "i am new".into(),
extra: Some("hi".into()),
});
let newvarv2 = v2api.patch("new", &ssapply, &Patch::Apply(&v2m)).await?;
info!("new instance on v2 is force downgraded: {:?}", newvarv2.spec); // no extra field
let cannot_fetch_as_old = v1api.get("new").await.unwrap_err();
info!("cannot fetch new on v1: {:?}", cannot_fetch_as_old);
// apply schema upgrade
apply_crd(client.clone(), merge_crds(all_crds, "v2")?).await?;
// nothing changed with existing objects without conversion
//let oldvarv1_upg = v1api.get("old").await?;
//info!("old instance unchanged on v1: {:?}", oldvarv1_upg.spec);
//let oldvarv2_upg = v2api.get("old").await?;
//info!("old instance unchanged on v2: {:?}", oldvarv2_upg.spec);
// re-apply new now that v2 is stored gives us the extra properties
let newvarv2_2 = v2api.patch("new", &ssapply, &Patch::Apply(&v2m)).await?;
info!("new on v2 correct on reapply to v2: {:?}", newvarv2_2.spec);
// note we can apply old versions without them being truncated to the v2 schema
// in our case this means we cannot fetch them with our v1 schema (breaking change to not have oldprop)
let v1m2 = v1::ManyDerive::new("old", v1::ManyDeriveSpec {
name: "i am old2".into(),
oldprop: 5,
});
let v1err = v1api
.patch("old", &ssapply, &Patch::Apply(&v1m2))
.await
.unwrap_err();
info!("cannot get old on v1 anymore: {:?}", v1err); // mandatory field oldprop truncated
// ...but the change is still there:
let old_still_there = v2api.get("old").await?;
assert_eq!(old_still_there.spec.name, "i am old2");
cleanup(client.clone()).await?;
Ok(())
}
async fn apply_crd(client: Client, crd: CustomResourceDefinition) -> anyhow::Result<()> {
let crds: Api<CustomResourceDefinition> = Api::all(client.clone());
info!("Creating crd: {}", serde_yaml::to_string(&crd)?);
let ssapply = PatchParams::apply("crd_derive_multi").force();
crds.patch("manyderives.kube.rs", &ssapply, &Patch::Apply(&crd))
.await?;
let establish = await_condition(
crds.clone(),
"manyderives.kube.rs",
conditions::is_crd_established(),
);
let _ = tokio::time::timeout(std::time::Duration::from_secs(10), establish).await?;
Ok(())
}
async fn cleanup(client: Client) -> anyhow::Result<()> {
let crds: Api<CustomResourceDefinition> = Api::all(client.clone());
let obj = crds.delete("manyderives.kube.rs", &Default::default()).await?;
if let either::Either::Left(o) = obj {
let uid = o.uid().unwrap();
await_condition(crds, "manyderives.kube.rs", conditions::is_deleted(&uid)).await?;
}
Ok(())
}
|
use std::fmt;
use std::marker::PhantomData;
use approx::ApproxEq;
use alga::general::{Real, SubsetOf};
use alga::linear::Rotation;
use core::{Scalar, OwnedSquareMatrix};
use core::dimension::{DimName, DimNameSum, DimNameAdd, U1};
use core::storage::{Storage, OwnedStorage};
use core::allocator::{Allocator, OwnedAllocator};
use geometry::{TranslationBase, PointBase};
/// An isometry that uses a data storage deduced from the allocator `A`.
pub type OwnedIsometryBase<N, D, A, R> =
IsometryBase<N, D, <A as Allocator<N, D, U1>>::Buffer, R>;
/// A direct isometry, i.e., a rotation followed by a translation.
#[repr(C)]
#[derive(Hash, Debug, Clone, Copy)]
#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
pub struct IsometryBase<N: Scalar, D: DimName, S, R> {
/// The pure rotational part of this isometry.
pub rotation: R,
/// The pure translational part of this isometry.
pub translation: TranslationBase<N, D, S>,
// One dummy private field just to prevent explicit construction.
#[cfg_attr(feature = "serde-serialize", serde(skip_serializing, skip_deserializing))]
_noconstruct: PhantomData<N>
}
impl<N, D: DimName, S, R> IsometryBase<N, D, S, R>
where N: Real,
S: OwnedStorage<N, D, U1>,
R: Rotation<PointBase<N, D, S>>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
/// Creates a new isometry from its rotational and translational parts.
#[inline]
pub fn from_parts(translation: TranslationBase<N, D, S>, rotation: R) -> IsometryBase<N, D, S, R> {
IsometryBase {
rotation: rotation,
translation: translation,
_noconstruct: PhantomData
}
}
/// Inverts `self`.
#[inline]
pub fn inverse(&self) -> IsometryBase<N, D, S, R> {
let mut res = self.clone();
res.inverse_mut();
res
}
/// Inverts `self`.
#[inline]
pub fn inverse_mut(&mut self) {
self.rotation.inverse_mut();
self.translation.inverse_mut();
self.translation.vector = self.rotation.transform_vector(&self.translation.vector);
}
/// Appends to `self` the given translation in-place.
#[inline]
pub fn append_translation_mut(&mut self, t: &TranslationBase<N, D, S>) {
self.translation.vector += &t.vector
}
/// Appends to `self` the given rotation in-place.
#[inline]
pub fn append_rotation_mut(&mut self, r: &R) {
self.rotation = self.rotation.append_rotation(&r);
self.translation.vector = r.transform_vector(&self.translation.vector);
}
/// Appends in-place to `self` a rotation centered at the point `p`, i.e., the rotation that
/// lets `p` invariant.
#[inline]
pub fn append_rotation_wrt_point_mut(&mut self, r: &R, p: &PointBase<N, D, S>) {
self.translation.vector -= &p.coords;
self.append_rotation_mut(r);
self.translation.vector += &p.coords;
}
/// Appends in-place to `self` a rotation centered at the point with coordinates
/// `self.translation`.
#[inline]
pub fn append_rotation_wrt_center_mut(&mut self, r: &R) {
let center = PointBase::from_coordinates(self.translation.vector.clone());
self.append_rotation_wrt_point_mut(r, ¢er)
}
}
// NOTE: we don't require `R: Rotation<...>` here because this is not useful for the implementation
// and makes it hard to use it, e.g., for Transform × Isometry implementation.
// This is OK since all constructors of the isometry enforce the Rotation bound already (and
// explicit struct construction is prevented by the dummy ZST field).
impl<N, D: DimName, S, R> IsometryBase<N, D, S, R>
where N: Scalar,
S: Storage<N, D, U1> {
/// Converts this isometry into its equivalent homogeneous transformation matrix.
#[inline]
pub fn to_homogeneous(&self) -> OwnedSquareMatrix<N, DimNameSum<D, U1>, S::Alloc>
where D: DimNameAdd<U1>,
R: SubsetOf<OwnedSquareMatrix<N, DimNameSum<D, U1>, S::Alloc>>,
S::Alloc: Allocator<N, DimNameSum<D, U1>, DimNameSum<D, U1>> {
let mut res: OwnedSquareMatrix<N, _, S::Alloc> = ::convert_ref(&self.rotation);
res.fixed_slice_mut::<D, U1>(0, D::dim()).copy_from(&self.translation.vector);
res
}
}
impl<N, D: DimName, S, R> Eq for IsometryBase<N, D, S, R>
where N: Real,
S: OwnedStorage<N, D, U1>,
R: Rotation<PointBase<N, D, S>> + Eq,
S::Alloc: OwnedAllocator<N, D, U1, S> {
}
impl<N, D: DimName, S, R> PartialEq for IsometryBase<N, D, S, R>
where N: Real,
S: OwnedStorage<N, D, U1>,
R: Rotation<PointBase<N, D, S>> + PartialEq,
S::Alloc: OwnedAllocator<N, D, U1, S> {
#[inline]
fn eq(&self, right: &IsometryBase<N, D, S, R>) -> bool {
self.translation == right.translation &&
self.rotation == right.rotation
}
}
impl<N, D: DimName, S, R> ApproxEq for IsometryBase<N, D, S, R>
where N: Real,
S: OwnedStorage<N, D, U1>,
R: Rotation<PointBase<N, D, S>> + ApproxEq<Epsilon = N::Epsilon>,
S::Alloc: OwnedAllocator<N, D, U1, S>,
N::Epsilon: Copy {
type Epsilon = N::Epsilon;
#[inline]
fn default_epsilon() -> Self::Epsilon {
N::default_epsilon()
}
#[inline]
fn default_max_relative() -> Self::Epsilon {
N::default_max_relative()
}
#[inline]
fn default_max_ulps() -> u32 {
N::default_max_ulps()
}
#[inline]
fn relative_eq(&self, other: &Self, epsilon: Self::Epsilon, max_relative: Self::Epsilon) -> bool {
self.translation.relative_eq(&other.translation, epsilon, max_relative) &&
self.rotation.relative_eq(&other.rotation, epsilon, max_relative)
}
#[inline]
fn ulps_eq(&self, other: &Self, epsilon: Self::Epsilon, max_ulps: u32) -> bool {
self.translation.ulps_eq(&other.translation, epsilon, max_ulps) &&
self.rotation.ulps_eq(&other.rotation, epsilon, max_ulps)
}
}
/*
*
* Display
*
*/
impl<N, D: DimName, S, R> fmt::Display for IsometryBase<N, D, S, R>
where N: Real + fmt::Display,
S: OwnedStorage<N, D, U1>,
R: fmt::Display,
S::Alloc: OwnedAllocator<N, D, U1, S> + Allocator<usize, D, U1> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let precision = f.precision().unwrap_or(3);
try!(writeln!(f, "IsometryBase {{"));
try!(write!(f, "{:.*}", precision, self.translation));
try!(write!(f, "{:.*}", precision, self.rotation));
writeln!(f, "}}")
}
}
// /*
// *
// * Absolute
// *
// */
// impl<N: Absolute> Absolute for $t<N> {
// type AbsoluteValue = $submatrix<N::AbsoluteValue>;
//
// #[inline]
// fn abs(m: &$t<N>) -> $submatrix<N::AbsoluteValue> {
// Absolute::abs(&m.submatrix)
// }
// }
|
use crate::*;
use serenity::{
framework::standard::{
macros::{command, group, help},
Args, CommandGroup, CommandResult, HelpOptions, *,
},
model::channel::Message,
model::id::UserId,
prelude::*,
};
use std::collections::HashSet;
mk_group!(General, ping, say);
cmd_ctx_msg!(ping, ctx, msg, {
println!("user : {}", msg.author);
// msg.reply(&ctx.http, "Pong!").await?;
reply!(msg, ctx, "Pong!");
});
cmd_ctx_msg!(say, ctx, msg, args, {
println!("user : {}", msg.author);
println!("args :{:?}", args);
say!(msg, ctx, "<3");
});
#[help]
async fn help(
context: &Context,
msg: &Message,
args: Args,
help_options: &'static HelpOptions,
groups: &[&'static CommandGroup],
owners: HashSet<UserId>,
) -> CommandResult {
let _ = help_commands::with_embeds(context, msg, args, help_options, groups, owners).await;
Ok(())
}
|
//! An API to easily print a two dimensional array to stdout.
//! # Example
//! ```rust
//! use grid_printer::GridPrinter;
//!
//! let cars = vec![
//! vec!["Make", "Model", "Color", "Year", "Price", ],
//! vec!["Ford", "Pinto", "Green", "1978", "$750.00", ],
//! vec!["Toyota", "Tacoma", "Red", "2006", "$15,475.23", ],
//! vec!["Lamborghini", "Diablo", "Yellow", "2001", "$238,459.99", ],
//! ];
//!
//! let rows = cars.len();
//! let cols = cars[0].len();
//! let printer = GridPrinter::builder(rows, cols)
//! .col_spacing(4)
//! .build();
//! printer.print(&cars);
//! ```
//!
//! # Output:
//! ```bash
//! Make Model Color Year Price
//! Ford Pinto Green 1978 $750.00
//! Toyota Tacoma Red 2006 $15,475.23
//! Lamborghini Diablo Yellow 2001 $238,459.99
//! ```
pub mod style;
use std::io;
use std::fmt;
use std::io::Write;
use std::fmt::Display;
use std::error::Error;
use std::cell::RefCell;
use crate::style::StyleOpt;
use crate::style::stylize;
/// An API to easily print a two dimensional array to stdout.
///
/// # Example
/// ```rust
/// use grid_printer::GridPrinter;
///
/// let cars = vec![
/// vec!["Make", "Model", "Color", "Year", "Price", ],
/// vec!["Ford", "Pinto", "Green", "1978", "$750.00", ],
/// vec!["Toyota", "Tacoma", "Red", "2006", "$15,475.23", ],
/// vec!["Lamborghini", "Diablo", "Yellow", "2001", "$238,459.99", ],
/// ];
///
/// let rows = cars.len();
/// let cols = cars[0].len();
/// let printer = GridPrinter::builder(rows, cols)
/// .col_spacing(4)
/// .build();
/// printer.print(&cars);
/// ```
///
/// Output:
/// ```bash
/// Make Model Color Year Price
/// Ford Pinto Green 1978 $750.00
/// Toyota Tacoma Red 2006 $15,475.23
/// Lamborghini Diablo Yellow 2001 $238,459.99
/// ```
// #[derive(Debug)]
pub struct GridPrinter {
rows: usize,
cols: usize,
max_widths: RefCell<Vec<usize>>,
col_spacing: usize,
col_styles: Option<Vec<Option<StyleOpt>>>,
}
impl GridPrinter {
pub fn new(rows: usize, cols: usize) -> Self {
Self {
rows,
cols,
..GridPrinterBuilder::new(rows, cols).build()
}
}
pub fn builder(rows: usize, cols: usize) -> GridPrinterBuilder {
GridPrinterBuilder::new(rows, cols)
}
fn pad(n: usize) -> String {
vec![' '; n].into_iter().collect()
}
#[allow(clippy::print_with_newline)]
pub fn print_cell(&self, cell: &str, col_idx: usize, style_opt: Option<&StyleOpt>) {
let mut s = cell.to_string();
if let Some(style_opt) = style_opt {
s = stylize(cell, style_opt);
}
let col_width = self.max_widths.borrow()[col_idx];
let pad = GridPrinter::pad(col_width - cell.len() + self.col_spacing);
print!("{}{}", s, pad);
}
#[allow(clippy::print_with_newline)]
pub fn print<F: Display>(&self, source: &[Vec<F>]) {
let mut buff: Vec<String> = Vec::new();
for i in 0..self.rows {
let row = source.get(i);
for j in 0..self.cols {
let cell = match row {
None => "".to_string(),
Some(row) => match row.get(j) {
None => "".to_string(),
Some(el) => format!("{}", el),
}
};
let len = cell.len();
if len > self.max_widths.borrow()[j] {
self.max_widths.borrow_mut()[j] = len;
}
// self.buff.borrow_mut().push(cell);
buff.push(cell);
}
}
for (i, cell) in buff.iter().enumerate() {
let col_idx = i % self.cols;
let _row_idx = i / self.rows;
let style_opt = match self.col_styles.as_ref() {
None => None,
Some(col_styles) => match col_styles.get(col_idx) {
None => None,
Some(style_opt) => style_opt.as_ref(),
}
};
self.print_cell(cell, col_idx, style_opt);
if (i + 1) % self.cols == 0 {
print!("\n");
io::stdout().flush().unwrap();
}
}
}
}
/// A Builder to create/customize a GridPrinter instance
/// ```rust
/// use grid_printer::GridPrinter;
/// use grid_printer::GridPrinterBuilder;
///
/// let rows = 3;
/// let cols = 3;
/// let printer: GridPrinter = GridPrinterBuilder::new(rows, cols)
/// .col_spacing(4)
/// .build();
/// ```
#[derive(Debug)]
pub struct GridPrinterBuilder {
rows: usize,
cols: usize,
col_spacing: usize,
col_styles: Option<Vec<Option<StyleOpt>>>,
}
impl Default for GridPrinterBuilder {
fn default() -> Self {
Self {
rows: 1,
cols: 1,
col_spacing: 2,
col_styles: None,
}
}
}
impl GridPrinterBuilder {
pub fn new(rows: usize, cols: usize) -> Self {
GridPrinterBuilder {
rows,
cols,
..Default::default()
}
}
pub fn col_spacing(mut self, col_spacing: usize) -> Self {
self.col_spacing = col_spacing;
self
}
pub fn col_styles(mut self, col_styles: Vec<Option<StyleOpt>>) -> Result<Self, GridPrinterErr> {
match col_styles.len() == self.cols {
false => Err(GridPrinterErr::DimensionErr),
true => {
self.col_styles = Some(col_styles);
Ok(self)
}
}
}
pub fn col_style(mut self, idx: usize, opt: StyleOpt) -> Result<Self, GridPrinterErr> {
// Note: The size check here is somewhat redundant given the subsequent logic; however,
// performing the check here guarantees we don't mutate the GridPrinterBuilder by adding
// a Vec for an index that is outside the column range.
if idx >= self.cols {
return Err(GridPrinterErr::DimensionErr);
}
let col_styles = self.col_styles.get_or_insert(vec![None; self.cols]);
let col_style = col_styles.get_mut(idx)
.ok_or(GridPrinterErr::DimensionErr)?;
*col_style = Some(opt);
Ok(self)
}
pub fn build(self) -> GridPrinter {
GridPrinter {
rows: self.rows,
cols: self.cols,
max_widths: RefCell::new(vec![0; self.cols]),
col_spacing: self.col_spacing,
col_styles: self.col_styles,
}
}
}
#[derive(Debug)]
pub enum GridPrinterErr {
DimensionErr,
}
impl Display for GridPrinterErr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
GridPrinterErr::DimensionErr => {
write!(f, "DimensionErr. Caused by mismatch in dimension size between method calls.")
},
}
}
}
impl Error for GridPrinterErr {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_2d_arr() {
let v = vec![
vec![1, 20, 3, ],
vec![40, 5, 6, ],
vec![7, 800, 9, ],
];
let rows = v.len();
let cols = v[0].len();
let printer = GridPrinterBuilder::new(rows, cols)
.col_spacing(20)
.build();
printer.print(&v);
}
}
|
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, RwLock};
use std::thread;
use std::thread::spawn;
use std::time::Duration;
pub enum Priority {
Readers,
Writers,
Equal,
}
pub struct ReadersWriters {
readers_count: AtomicUsize,
writers_count: AtomicUsize,
priority: Priority,
read_lock: RwLock<AtomicBool>,
write_lock: RwLock<AtomicBool>,
}
impl ReadersWriters {
fn new(readers_count: usize, writers_count: usize, priority: Priority) -> Arc<ReadersWriters> {
Arc::new(ReadersWriters {
readers_count: AtomicUsize::new(readers_count),
writers_count: AtomicUsize::new(writers_count),
priority,
read_lock: RwLock::new(AtomicBool::new(false)),
write_lock: RwLock::new(AtomicBool::new(false)),
})
}
fn get_readers_count(&self) -> &AtomicUsize {
&self.readers_count
}
fn get_writers_count(&self) -> &AtomicUsize {
&self.writers_count
}
fn read(&self, i: usize) {
if self.write_lock.read().unwrap().load(Ordering::SeqCst) == true {}
self.read_lock.read().unwrap().store(true, Ordering::SeqCst);
println!("{} Started reading.", i);
thread::sleep(Duration::from_millis(1500));
println!("{} Finished reading.", i);
match self.priority {
Priority::Readers => {
self.get_readers_count().fetch_sub(1, Ordering::SeqCst);
if self.get_readers_count().load(Ordering::SeqCst) <= 0 {
self.read_lock
.read()
.unwrap()
.store(false, Ordering::SeqCst);
}
}
Priority::Writers | Priority::Equal => {
self.read_lock
.read()
.unwrap()
.store(false, Ordering::SeqCst);
}
_ => unreachable!(),
}
}
fn write(&self, i: usize) {
match self.priority {
Priority::Readers | Priority::Equal => {
while self.write_lock.write().unwrap().load(Ordering::SeqCst) == true
|| self.read_lock.read().unwrap().load(Ordering::SeqCst) == true
{
}
}
Priority::Writers => {
while self.read_lock.read().unwrap().load(Ordering::SeqCst) == true {}
}
_ => unreachable!(),
}
let mut write = self.write_lock.write().unwrap();
write.store(true, Ordering::SeqCst);
println!("{} Started writing.", i);
thread::sleep(Duration::from_millis(2500));
println!("{} Finished writing.", i);
match self.priority {
Priority::Readers | Priority::Equal => {
write.store(false, Ordering::SeqCst);
}
Priority::Writers => {
if self.get_writers_count().load(Ordering::SeqCst) <= 0 {
write.store(false, Ordering::SeqCst);
}
}
_ => unreachable!(),
}
}
}
pub fn readers_writers_run(readers_count: usize, writers_count: usize, priority: Priority) {
let mut readers_writers = ReadersWriters::new(readers_count, writers_count, priority);
let mut readers = Vec::new();
let mut writers = Vec::new();
let readers_count = readers_writers.get_readers_count().load(Ordering::SeqCst);
let writers_count = readers_writers.get_writers_count().load(Ordering::SeqCst);
for i in 1..=writers_count {
let readers_writers_cloned = readers_writers.clone();
writers.push(spawn(move || {
readers_writers_cloned.write(i as usize);
}));
}
for i in 1..=readers_count {
let readers_writers_cloned = readers_writers.clone();
readers.push(spawn(move || {
readers_writers_cloned.read(i as usize);
}));
}
for r in readers {
r.join().unwrap();
}
for w in writers {
w.join().unwrap();
}
}
|
//rand kütüphanesini ekliyoruz
use rand::Rng;
//std kütüphanesi diğer dillerdekiyle aynı
use std::io::Write;
fn main(){
//rand kütüphanesinin gen fonksiyonuyla 32 tane u8 tipinde değer üretiyoruz
let random_bytes = rand::thread_rng().gen::<[u8; 32]>();
println!("Yazılacak bytelar:");
println!("{:?}", random_bytes);
//dosya açıyoruz.https://stackoverflow.com/questions/53826371/how-to-create-a-binary-file-with-rust/53827079
let mut file = std::fs::File::create("input").expect("create failed");
//byte array'i dosyaya yazıyoruz.
file.write_all(&random_bytes).expect("write failes");
} |
use crate::{
metadata::Metadata,
module::{PubSubImpl, PubSubService},
};
use anyhow::Result;
use jsonrpc_core::{futures as futures01, MetaIoHandler};
use jsonrpc_pubsub::Session;
// use starcoin_crypto::hash::HashValue;
use futures::{compat::Stream01CompatExt, StreamExt};
use starcoin_rpc_api::pubsub::StarcoinPubSub;
use starcoin_txpool_api::TxPoolSyncService;
use starcoin_types::account_address;
use std::sync::Arc;
use txpool::test_helper::start_txpool;
// use txpool::TxPoolRef;
use starcoin_bus::{Bus, BusActor};
use starcoin_chain::test_helper as chain_test_helper;
use starcoin_config::NodeConfig;
use starcoin_consensus::dev::DevConsensus;
use starcoin_crypto::{ed25519::Ed25519PrivateKey, hash::PlainCryptoHash, Genesis, PrivateKey};
use starcoin_logger::prelude::*;
use starcoin_state_api::AccountStateReader;
use starcoin_traits::{ChainReader, ChainWriter, Consensus};
use starcoin_types::{
block::BlockDetail, system_events::NewHeadBlock, transaction::authenticator::AuthenticationKey,
};
use starcoin_wallet_api::WalletAccount;
#[actix_rt::test]
pub async fn test_subscribe_to_events() -> Result<()> {
// prepare
let config = Arc::new(NodeConfig::random_for_test());
let mut block_chain =
chain_test_helper::gen_blockchain_for_test::<DevConsensus>(config.clone())?;
let miner_account = WalletAccount::random();
let pri_key = Ed25519PrivateKey::genesis();
let public_key = pri_key.public_key();
let account_address = account_address::from_public_key(&public_key);
let txn = {
let auth_prefix = AuthenticationKey::ed25519(&public_key).prefix().to_vec();
let txn = starcoin_executor::build_transfer_from_association(
account_address,
auth_prefix,
0,
10000,
);
txn.as_signed_user_txn()?.clone()
};
let (block_template, _) = block_chain.create_block_template(
*miner_account.address(),
Some(miner_account.get_auth_key().prefix().to_vec()),
None,
vec![txn.clone()],
)?;
debug!(
"block_template: gas_used: {}, gas_limit: {}",
block_template.gas_used, block_template.gas_limit
);
let new_block = DevConsensus::create_block(config.clone(), &block_chain, block_template)?;
block_chain.apply(new_block.clone())?;
let reader = AccountStateReader::new(block_chain.chain_state_reader());
let balance = reader.get_balance(&account_address)?;
assert_eq!(balance, Some(10000));
// now block is applied, we can emit events.
let service = PubSubService::new();
let bus = BusActor::launch();
service.start_chain_notify_handler(bus.clone(), block_chain.get_storage());
let pubsub = PubSubImpl::new(service);
let pubsub = pubsub.to_delegate();
let mut io = MetaIoHandler::default();
io.extend_with(pubsub);
let mut metadata = Metadata::default();
let (sender, receiver) = futures01::sync::mpsc::channel(8);
metadata.session = Some(Arc::new(Session::new(sender)));
// Subscribe
let request =
r#"{"jsonrpc": "2.0", "method": "starcoin_subscribe", "params": ["events", {}], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":0,"id":1}"#;
assert_eq!(
io.handle_request_sync(request, metadata.clone()),
Some(response.to_owned())
);
// Subscribe error
let request =
r#"{"jsonrpc": "2.0", "method": "starcoin_subscribe", "params": ["events"], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","error":{"code":-32602,"message":"Couldn't parse parameters: events","data":"\"Expected a filter object.\""},"id":1}"#;
assert_eq!(
io.handle_request_sync(request, metadata.clone()),
Some(response.to_owned())
);
// send block
let block_detail = Arc::new(BlockDetail::new(new_block, 0.into()));
bus.broadcast(NewHeadBlock(block_detail)).await?;
let mut receiver = receiver.compat();
let res = receiver.next().await.transpose().unwrap();
assert!(res.is_some());
let res = res.unwrap();
let notification = serde_json::from_str::<jsonrpc_core::Notification>(res.as_str()).unwrap();
match notification.params {
jsonrpc_core::Params::Map(s) => {
let v = s.get("result").unwrap().get("blockNumber").unwrap();
assert_eq!(v.as_u64(), Some(1));
}
p => {
assert!(false, "subscribe return unexpected result, {:?}", &p);
}
}
Ok(())
}
#[stest::test]
pub async fn test_subscribe_to_pending_transactions() -> Result<()> {
// given
let (txpool, _) = start_txpool();
let txpool_service = txpool.get_service();
let service = PubSubService::new();
let txn_receiver = txpool_service.subscribe_txns();
service.start_transaction_subscription_handler(txn_receiver);
let pubsub = PubSubImpl::new(service);
let pubsub = pubsub.to_delegate();
let mut io = MetaIoHandler::default();
io.extend_with(pubsub);
let mut metadata = Metadata::default();
let (sender, receiver) = futures01::sync::mpsc::channel(8);
metadata.session = Some(Arc::new(Session::new(sender)));
// Fail if params are provided
let request = r#"{"jsonrpc": "2.0", "method": "starcoin_subscribe", "params": ["newPendingTransactions", {}], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","error":{"code":-32602,"message":"Couldn't parse parameters: newPendingTransactions","data":"\"Expected no parameters.\""},"id":1}"#;
assert_eq!(
io.handle_request_sync(request, metadata.clone()),
Some(response.to_owned())
);
// Subscribe
let request = r#"{"jsonrpc": "2.0", "method": "starcoin_subscribe", "params": ["newPendingTransactions"], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":0,"id":1}"#;
assert_eq!(
io.handle_request_sync(request, metadata.clone()),
Some(response.to_owned())
);
// Send new transactions
let txn = {
let pri_key = Ed25519PrivateKey::genesis();
let public_key = pri_key.public_key();
let account_address = account_address::from_public_key(&public_key);
let auth_prefix = AuthenticationKey::ed25519(&public_key).prefix().to_vec();
let txn = starcoin_executor::build_transfer_from_association(
account_address,
auth_prefix,
1,
10000,
);
txn.as_signed_user_txn()?.clone()
};
let txn_id = txn.crypto_hash();
txpool_service.add_txns(vec![txn]).pop().unwrap().unwrap();
let mut receiver = receiver.compat();
let res = receiver.next().await.transpose().unwrap();
let prefix = r#"{"jsonrpc":"2.0","method":"starcoin_subscription","params":{"result":[""#;
let suffix = r#""],"subscription":0}}"#;
let response = format!("{}{}{}", prefix, txn_id.to_hex(), suffix);
assert_eq!(res, Some(response));
// And unsubscribe
let request = r#"{"jsonrpc": "2.0", "method": "starcoin_unsubscribe", "params": [0], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":true,"id":1}"#;
assert_eq!(
io.handle_request_sync(request, metadata),
Some(response.to_owned())
);
let res = receiver.next().await.transpose().unwrap();
assert_eq!(res, None);
Ok(())
}
|
#[doc = "Register `OR` reader"]
pub type R = crate::R<OR_SPEC>;
#[doc = "Register `OR` writer"]
pub type W = crate::W<OR_SPEC>;
#[doc = "Field `IN1` reader - IN1"]
pub type IN1_R = crate::BitReader;
#[doc = "Field `IN1` writer - IN1"]
pub type IN1_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `IN2` reader - IN2"]
pub type IN2_R = crate::BitReader;
#[doc = "Field `IN2` writer - IN2"]
pub type IN2_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `IN1_2_1` reader - IN1_2_1"]
pub type IN1_2_1_R = crate::FieldReader;
#[doc = "Field `IN1_2_1` writer - IN1_2_1"]
pub type IN1_2_1_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `IN2_2_1` reader - IN2_2_1"]
pub type IN2_2_1_R = crate::FieldReader;
#[doc = "Field `IN2_2_1` writer - IN2_2_1"]
pub type IN2_2_1_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
impl R {
#[doc = "Bit 0 - IN1"]
#[inline(always)]
pub fn in1(&self) -> IN1_R {
IN1_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - IN2"]
#[inline(always)]
pub fn in2(&self) -> IN2_R {
IN2_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bits 2:3 - IN1_2_1"]
#[inline(always)]
pub fn in1_2_1(&self) -> IN1_2_1_R {
IN1_2_1_R::new(((self.bits >> 2) & 3) as u8)
}
#[doc = "Bits 4:5 - IN2_2_1"]
#[inline(always)]
pub fn in2_2_1(&self) -> IN2_2_1_R {
IN2_2_1_R::new(((self.bits >> 4) & 3) as u8)
}
}
impl W {
#[doc = "Bit 0 - IN1"]
#[inline(always)]
#[must_use]
pub fn in1(&mut self) -> IN1_W<OR_SPEC, 0> {
IN1_W::new(self)
}
#[doc = "Bit 1 - IN2"]
#[inline(always)]
#[must_use]
pub fn in2(&mut self) -> IN2_W<OR_SPEC, 1> {
IN2_W::new(self)
}
#[doc = "Bits 2:3 - IN1_2_1"]
#[inline(always)]
#[must_use]
pub fn in1_2_1(&mut self) -> IN1_2_1_W<OR_SPEC, 2> {
IN1_2_1_W::new(self)
}
#[doc = "Bits 4:5 - IN2_2_1"]
#[inline(always)]
#[must_use]
pub fn in2_2_1(&mut self) -> IN2_2_1_W<OR_SPEC, 4> {
IN2_2_1_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 = "option register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`or::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 [`or::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct OR_SPEC;
impl crate::RegisterSpec for OR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`or::R`](R) reader structure"]
impl crate::Readable for OR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`or::W`](W) writer structure"]
impl crate::Writable for OR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets OR to value 0"]
impl crate::Resettable for OR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
#[doc = "Register `EXTICR1` reader"]
pub type R = crate::R<EXTICR1_SPEC>;
#[doc = "Register `EXTICR1` writer"]
pub type W = crate::W<EXTICR1_SPEC>;
#[doc = "Field `EXTI0` reader - EXTI 0 configuration bits"]
pub type EXTI0_R = crate::FieldReader<EXTI0_A>;
#[doc = "EXTI 0 configuration bits\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum EXTI0_A {
#[doc = "0: PA0 pin"]
Pa0 = 0,
#[doc = "1: PB0 pin"]
Pb0 = 1,
#[doc = "2: PC0 pin"]
Pc0 = 2,
#[doc = "3: PD0 pin"]
Pd0 = 3,
#[doc = "4: PE0 pin"]
Pe0 = 4,
#[doc = "5: PF0 pin"]
Pf0 = 5,
#[doc = "6: PG0 pin"]
Pg0 = 6,
#[doc = "7: PH0 pin"]
Ph0 = 7,
#[doc = "8: PI0 pin"]
Pi0 = 8,
}
impl From<EXTI0_A> for u8 {
#[inline(always)]
fn from(variant: EXTI0_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for EXTI0_A {
type Ux = u8;
}
impl EXTI0_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<EXTI0_A> {
match self.bits {
0 => Some(EXTI0_A::Pa0),
1 => Some(EXTI0_A::Pb0),
2 => Some(EXTI0_A::Pc0),
3 => Some(EXTI0_A::Pd0),
4 => Some(EXTI0_A::Pe0),
5 => Some(EXTI0_A::Pf0),
6 => Some(EXTI0_A::Pg0),
7 => Some(EXTI0_A::Ph0),
8 => Some(EXTI0_A::Pi0),
_ => None,
}
}
#[doc = "PA0 pin"]
#[inline(always)]
pub fn is_pa0(&self) -> bool {
*self == EXTI0_A::Pa0
}
#[doc = "PB0 pin"]
#[inline(always)]
pub fn is_pb0(&self) -> bool {
*self == EXTI0_A::Pb0
}
#[doc = "PC0 pin"]
#[inline(always)]
pub fn is_pc0(&self) -> bool {
*self == EXTI0_A::Pc0
}
#[doc = "PD0 pin"]
#[inline(always)]
pub fn is_pd0(&self) -> bool {
*self == EXTI0_A::Pd0
}
#[doc = "PE0 pin"]
#[inline(always)]
pub fn is_pe0(&self) -> bool {
*self == EXTI0_A::Pe0
}
#[doc = "PF0 pin"]
#[inline(always)]
pub fn is_pf0(&self) -> bool {
*self == EXTI0_A::Pf0
}
#[doc = "PG0 pin"]
#[inline(always)]
pub fn is_pg0(&self) -> bool {
*self == EXTI0_A::Pg0
}
#[doc = "PH0 pin"]
#[inline(always)]
pub fn is_ph0(&self) -> bool {
*self == EXTI0_A::Ph0
}
#[doc = "PI0 pin"]
#[inline(always)]
pub fn is_pi0(&self) -> bool {
*self == EXTI0_A::Pi0
}
}
#[doc = "Field `EXTI0` writer - EXTI 0 configuration bits"]
pub type EXTI0_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O, EXTI0_A>;
impl<'a, REG, const O: u8> EXTI0_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "PA0 pin"]
#[inline(always)]
pub fn pa0(self) -> &'a mut crate::W<REG> {
self.variant(EXTI0_A::Pa0)
}
#[doc = "PB0 pin"]
#[inline(always)]
pub fn pb0(self) -> &'a mut crate::W<REG> {
self.variant(EXTI0_A::Pb0)
}
#[doc = "PC0 pin"]
#[inline(always)]
pub fn pc0(self) -> &'a mut crate::W<REG> {
self.variant(EXTI0_A::Pc0)
}
#[doc = "PD0 pin"]
#[inline(always)]
pub fn pd0(self) -> &'a mut crate::W<REG> {
self.variant(EXTI0_A::Pd0)
}
#[doc = "PE0 pin"]
#[inline(always)]
pub fn pe0(self) -> &'a mut crate::W<REG> {
self.variant(EXTI0_A::Pe0)
}
#[doc = "PF0 pin"]
#[inline(always)]
pub fn pf0(self) -> &'a mut crate::W<REG> {
self.variant(EXTI0_A::Pf0)
}
#[doc = "PG0 pin"]
#[inline(always)]
pub fn pg0(self) -> &'a mut crate::W<REG> {
self.variant(EXTI0_A::Pg0)
}
#[doc = "PH0 pin"]
#[inline(always)]
pub fn ph0(self) -> &'a mut crate::W<REG> {
self.variant(EXTI0_A::Ph0)
}
#[doc = "PI0 pin"]
#[inline(always)]
pub fn pi0(self) -> &'a mut crate::W<REG> {
self.variant(EXTI0_A::Pi0)
}
}
#[doc = "Field `EXTI1` reader - EXTI 1 configuration bits"]
pub type EXTI1_R = crate::FieldReader<EXTI1_A>;
#[doc = "EXTI 1 configuration bits\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum EXTI1_A {
#[doc = "0: PA1 pin"]
Pa1 = 0,
#[doc = "1: PB1 pin"]
Pb1 = 1,
#[doc = "2: PC1 pin"]
Pc1 = 2,
#[doc = "3: PD1 pin"]
Pd1 = 3,
#[doc = "4: PE1 pin"]
Pe1 = 4,
#[doc = "5: PF1 pin"]
Pf1 = 5,
#[doc = "6: PG1 pin"]
Pg1 = 6,
#[doc = "7: PH1 pin"]
Ph1 = 7,
#[doc = "8: PI1 pin"]
Pi1 = 8,
}
impl From<EXTI1_A> for u8 {
#[inline(always)]
fn from(variant: EXTI1_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for EXTI1_A {
type Ux = u8;
}
impl EXTI1_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<EXTI1_A> {
match self.bits {
0 => Some(EXTI1_A::Pa1),
1 => Some(EXTI1_A::Pb1),
2 => Some(EXTI1_A::Pc1),
3 => Some(EXTI1_A::Pd1),
4 => Some(EXTI1_A::Pe1),
5 => Some(EXTI1_A::Pf1),
6 => Some(EXTI1_A::Pg1),
7 => Some(EXTI1_A::Ph1),
8 => Some(EXTI1_A::Pi1),
_ => None,
}
}
#[doc = "PA1 pin"]
#[inline(always)]
pub fn is_pa1(&self) -> bool {
*self == EXTI1_A::Pa1
}
#[doc = "PB1 pin"]
#[inline(always)]
pub fn is_pb1(&self) -> bool {
*self == EXTI1_A::Pb1
}
#[doc = "PC1 pin"]
#[inline(always)]
pub fn is_pc1(&self) -> bool {
*self == EXTI1_A::Pc1
}
#[doc = "PD1 pin"]
#[inline(always)]
pub fn is_pd1(&self) -> bool {
*self == EXTI1_A::Pd1
}
#[doc = "PE1 pin"]
#[inline(always)]
pub fn is_pe1(&self) -> bool {
*self == EXTI1_A::Pe1
}
#[doc = "PF1 pin"]
#[inline(always)]
pub fn is_pf1(&self) -> bool {
*self == EXTI1_A::Pf1
}
#[doc = "PG1 pin"]
#[inline(always)]
pub fn is_pg1(&self) -> bool {
*self == EXTI1_A::Pg1
}
#[doc = "PH1 pin"]
#[inline(always)]
pub fn is_ph1(&self) -> bool {
*self == EXTI1_A::Ph1
}
#[doc = "PI1 pin"]
#[inline(always)]
pub fn is_pi1(&self) -> bool {
*self == EXTI1_A::Pi1
}
}
#[doc = "Field `EXTI1` writer - EXTI 1 configuration bits"]
pub type EXTI1_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O, EXTI1_A>;
impl<'a, REG, const O: u8> EXTI1_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "PA1 pin"]
#[inline(always)]
pub fn pa1(self) -> &'a mut crate::W<REG> {
self.variant(EXTI1_A::Pa1)
}
#[doc = "PB1 pin"]
#[inline(always)]
pub fn pb1(self) -> &'a mut crate::W<REG> {
self.variant(EXTI1_A::Pb1)
}
#[doc = "PC1 pin"]
#[inline(always)]
pub fn pc1(self) -> &'a mut crate::W<REG> {
self.variant(EXTI1_A::Pc1)
}
#[doc = "PD1 pin"]
#[inline(always)]
pub fn pd1(self) -> &'a mut crate::W<REG> {
self.variant(EXTI1_A::Pd1)
}
#[doc = "PE1 pin"]
#[inline(always)]
pub fn pe1(self) -> &'a mut crate::W<REG> {
self.variant(EXTI1_A::Pe1)
}
#[doc = "PF1 pin"]
#[inline(always)]
pub fn pf1(self) -> &'a mut crate::W<REG> {
self.variant(EXTI1_A::Pf1)
}
#[doc = "PG1 pin"]
#[inline(always)]
pub fn pg1(self) -> &'a mut crate::W<REG> {
self.variant(EXTI1_A::Pg1)
}
#[doc = "PH1 pin"]
#[inline(always)]
pub fn ph1(self) -> &'a mut crate::W<REG> {
self.variant(EXTI1_A::Ph1)
}
#[doc = "PI1 pin"]
#[inline(always)]
pub fn pi1(self) -> &'a mut crate::W<REG> {
self.variant(EXTI1_A::Pi1)
}
}
#[doc = "Field `EXTI2` reader - EXTI 2 configuration bits"]
pub type EXTI2_R = crate::FieldReader<EXTI2_A>;
#[doc = "EXTI 2 configuration bits\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum EXTI2_A {
#[doc = "0: PA2 pin"]
Pa2 = 0,
#[doc = "1: PB2 pin"]
Pb2 = 1,
#[doc = "2: PC2 pin"]
Pc2 = 2,
#[doc = "3: PD2 pin"]
Pd2 = 3,
#[doc = "4: PE2 pin"]
Pe2 = 4,
#[doc = "5: PF2 pin"]
Pf2 = 5,
#[doc = "6: PG2 pin"]
Pg2 = 6,
#[doc = "7: PH2 pin"]
Ph2 = 7,
#[doc = "8: PI2 pin"]
Pi2 = 8,
}
impl From<EXTI2_A> for u8 {
#[inline(always)]
fn from(variant: EXTI2_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for EXTI2_A {
type Ux = u8;
}
impl EXTI2_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<EXTI2_A> {
match self.bits {
0 => Some(EXTI2_A::Pa2),
1 => Some(EXTI2_A::Pb2),
2 => Some(EXTI2_A::Pc2),
3 => Some(EXTI2_A::Pd2),
4 => Some(EXTI2_A::Pe2),
5 => Some(EXTI2_A::Pf2),
6 => Some(EXTI2_A::Pg2),
7 => Some(EXTI2_A::Ph2),
8 => Some(EXTI2_A::Pi2),
_ => None,
}
}
#[doc = "PA2 pin"]
#[inline(always)]
pub fn is_pa2(&self) -> bool {
*self == EXTI2_A::Pa2
}
#[doc = "PB2 pin"]
#[inline(always)]
pub fn is_pb2(&self) -> bool {
*self == EXTI2_A::Pb2
}
#[doc = "PC2 pin"]
#[inline(always)]
pub fn is_pc2(&self) -> bool {
*self == EXTI2_A::Pc2
}
#[doc = "PD2 pin"]
#[inline(always)]
pub fn is_pd2(&self) -> bool {
*self == EXTI2_A::Pd2
}
#[doc = "PE2 pin"]
#[inline(always)]
pub fn is_pe2(&self) -> bool {
*self == EXTI2_A::Pe2
}
#[doc = "PF2 pin"]
#[inline(always)]
pub fn is_pf2(&self) -> bool {
*self == EXTI2_A::Pf2
}
#[doc = "PG2 pin"]
#[inline(always)]
pub fn is_pg2(&self) -> bool {
*self == EXTI2_A::Pg2
}
#[doc = "PH2 pin"]
#[inline(always)]
pub fn is_ph2(&self) -> bool {
*self == EXTI2_A::Ph2
}
#[doc = "PI2 pin"]
#[inline(always)]
pub fn is_pi2(&self) -> bool {
*self == EXTI2_A::Pi2
}
}
#[doc = "Field `EXTI2` writer - EXTI 2 configuration bits"]
pub type EXTI2_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O, EXTI2_A>;
impl<'a, REG, const O: u8> EXTI2_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "PA2 pin"]
#[inline(always)]
pub fn pa2(self) -> &'a mut crate::W<REG> {
self.variant(EXTI2_A::Pa2)
}
#[doc = "PB2 pin"]
#[inline(always)]
pub fn pb2(self) -> &'a mut crate::W<REG> {
self.variant(EXTI2_A::Pb2)
}
#[doc = "PC2 pin"]
#[inline(always)]
pub fn pc2(self) -> &'a mut crate::W<REG> {
self.variant(EXTI2_A::Pc2)
}
#[doc = "PD2 pin"]
#[inline(always)]
pub fn pd2(self) -> &'a mut crate::W<REG> {
self.variant(EXTI2_A::Pd2)
}
#[doc = "PE2 pin"]
#[inline(always)]
pub fn pe2(self) -> &'a mut crate::W<REG> {
self.variant(EXTI2_A::Pe2)
}
#[doc = "PF2 pin"]
#[inline(always)]
pub fn pf2(self) -> &'a mut crate::W<REG> {
self.variant(EXTI2_A::Pf2)
}
#[doc = "PG2 pin"]
#[inline(always)]
pub fn pg2(self) -> &'a mut crate::W<REG> {
self.variant(EXTI2_A::Pg2)
}
#[doc = "PH2 pin"]
#[inline(always)]
pub fn ph2(self) -> &'a mut crate::W<REG> {
self.variant(EXTI2_A::Ph2)
}
#[doc = "PI2 pin"]
#[inline(always)]
pub fn pi2(self) -> &'a mut crate::W<REG> {
self.variant(EXTI2_A::Pi2)
}
}
#[doc = "Field `EXTI3` reader - EXTI 3 configuration bits"]
pub type EXTI3_R = crate::FieldReader<EXTI3_A>;
#[doc = "EXTI 3 configuration bits\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum EXTI3_A {
#[doc = "0: PA3 pin"]
Pa3 = 0,
#[doc = "1: PB3 pin"]
Pb3 = 1,
#[doc = "2: PC3 pin"]
Pc3 = 2,
#[doc = "3: PD3 pin"]
Pd3 = 3,
#[doc = "4: PE3 pin"]
Pe3 = 4,
#[doc = "5: PF3 pin"]
Pf3 = 5,
#[doc = "6: PG3 pin"]
Pg3 = 6,
#[doc = "7: PH3 pin"]
Ph3 = 7,
#[doc = "8: PI3 pin"]
Pi3 = 8,
}
impl From<EXTI3_A> for u8 {
#[inline(always)]
fn from(variant: EXTI3_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for EXTI3_A {
type Ux = u8;
}
impl EXTI3_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<EXTI3_A> {
match self.bits {
0 => Some(EXTI3_A::Pa3),
1 => Some(EXTI3_A::Pb3),
2 => Some(EXTI3_A::Pc3),
3 => Some(EXTI3_A::Pd3),
4 => Some(EXTI3_A::Pe3),
5 => Some(EXTI3_A::Pf3),
6 => Some(EXTI3_A::Pg3),
7 => Some(EXTI3_A::Ph3),
8 => Some(EXTI3_A::Pi3),
_ => None,
}
}
#[doc = "PA3 pin"]
#[inline(always)]
pub fn is_pa3(&self) -> bool {
*self == EXTI3_A::Pa3
}
#[doc = "PB3 pin"]
#[inline(always)]
pub fn is_pb3(&self) -> bool {
*self == EXTI3_A::Pb3
}
#[doc = "PC3 pin"]
#[inline(always)]
pub fn is_pc3(&self) -> bool {
*self == EXTI3_A::Pc3
}
#[doc = "PD3 pin"]
#[inline(always)]
pub fn is_pd3(&self) -> bool {
*self == EXTI3_A::Pd3
}
#[doc = "PE3 pin"]
#[inline(always)]
pub fn is_pe3(&self) -> bool {
*self == EXTI3_A::Pe3
}
#[doc = "PF3 pin"]
#[inline(always)]
pub fn is_pf3(&self) -> bool {
*self == EXTI3_A::Pf3
}
#[doc = "PG3 pin"]
#[inline(always)]
pub fn is_pg3(&self) -> bool {
*self == EXTI3_A::Pg3
}
#[doc = "PH3 pin"]
#[inline(always)]
pub fn is_ph3(&self) -> bool {
*self == EXTI3_A::Ph3
}
#[doc = "PI3 pin"]
#[inline(always)]
pub fn is_pi3(&self) -> bool {
*self == EXTI3_A::Pi3
}
}
#[doc = "Field `EXTI3` writer - EXTI 3 configuration bits"]
pub type EXTI3_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O, EXTI3_A>;
impl<'a, REG, const O: u8> EXTI3_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "PA3 pin"]
#[inline(always)]
pub fn pa3(self) -> &'a mut crate::W<REG> {
self.variant(EXTI3_A::Pa3)
}
#[doc = "PB3 pin"]
#[inline(always)]
pub fn pb3(self) -> &'a mut crate::W<REG> {
self.variant(EXTI3_A::Pb3)
}
#[doc = "PC3 pin"]
#[inline(always)]
pub fn pc3(self) -> &'a mut crate::W<REG> {
self.variant(EXTI3_A::Pc3)
}
#[doc = "PD3 pin"]
#[inline(always)]
pub fn pd3(self) -> &'a mut crate::W<REG> {
self.variant(EXTI3_A::Pd3)
}
#[doc = "PE3 pin"]
#[inline(always)]
pub fn pe3(self) -> &'a mut crate::W<REG> {
self.variant(EXTI3_A::Pe3)
}
#[doc = "PF3 pin"]
#[inline(always)]
pub fn pf3(self) -> &'a mut crate::W<REG> {
self.variant(EXTI3_A::Pf3)
}
#[doc = "PG3 pin"]
#[inline(always)]
pub fn pg3(self) -> &'a mut crate::W<REG> {
self.variant(EXTI3_A::Pg3)
}
#[doc = "PH3 pin"]
#[inline(always)]
pub fn ph3(self) -> &'a mut crate::W<REG> {
self.variant(EXTI3_A::Ph3)
}
#[doc = "PI3 pin"]
#[inline(always)]
pub fn pi3(self) -> &'a mut crate::W<REG> {
self.variant(EXTI3_A::Pi3)
}
}
impl R {
#[doc = "Bits 0:3 - EXTI 0 configuration bits"]
#[inline(always)]
pub fn exti0(&self) -> EXTI0_R {
EXTI0_R::new((self.bits & 0x0f) as u8)
}
#[doc = "Bits 4:7 - EXTI 1 configuration bits"]
#[inline(always)]
pub fn exti1(&self) -> EXTI1_R {
EXTI1_R::new(((self.bits >> 4) & 0x0f) as u8)
}
#[doc = "Bits 8:11 - EXTI 2 configuration bits"]
#[inline(always)]
pub fn exti2(&self) -> EXTI2_R {
EXTI2_R::new(((self.bits >> 8) & 0x0f) as u8)
}
#[doc = "Bits 12:15 - EXTI 3 configuration bits"]
#[inline(always)]
pub fn exti3(&self) -> EXTI3_R {
EXTI3_R::new(((self.bits >> 12) & 0x0f) as u8)
}
}
impl W {
#[doc = "Bits 0:3 - EXTI 0 configuration bits"]
#[inline(always)]
#[must_use]
pub fn exti0(&mut self) -> EXTI0_W<EXTICR1_SPEC, 0> {
EXTI0_W::new(self)
}
#[doc = "Bits 4:7 - EXTI 1 configuration bits"]
#[inline(always)]
#[must_use]
pub fn exti1(&mut self) -> EXTI1_W<EXTICR1_SPEC, 4> {
EXTI1_W::new(self)
}
#[doc = "Bits 8:11 - EXTI 2 configuration bits"]
#[inline(always)]
#[must_use]
pub fn exti2(&mut self) -> EXTI2_W<EXTICR1_SPEC, 8> {
EXTI2_W::new(self)
}
#[doc = "Bits 12:15 - EXTI 3 configuration bits"]
#[inline(always)]
#[must_use]
pub fn exti3(&mut self) -> EXTI3_W<EXTICR1_SPEC, 12> {
EXTI3_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 = "external interrupt configuration register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`exticr1::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 [`exticr1::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct EXTICR1_SPEC;
impl crate::RegisterSpec for EXTICR1_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`exticr1::R`](R) reader structure"]
impl crate::Readable for EXTICR1_SPEC {}
#[doc = "`write(|w| ..)` method takes [`exticr1::W`](W) writer structure"]
impl crate::Writable for EXTICR1_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets EXTICR1 to value 0"]
impl crate::Resettable for EXTICR1_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use matrices::Matrix4;
use tuples::Tuple;
pub struct Ray {
pub origin: Tuple,
pub direction: Tuple,
}
impl Ray {
pub fn new(origin: Tuple, direction: Tuple) -> Self {
Ray { origin, direction }
}
pub fn position(&self, t: f32) -> Tuple {
self.origin + self.direction * t
}
pub fn transform(&self, m: Matrix4) -> Ray {
Ray::new(m * self.origin, m * self.direction)
}
}
#[test]
fn test_creating_and_querying_a_ray() {
let origin = Tuple::point(1.0, 2.0, 3.0);
let direction = Tuple::vector(4.0, 5.0, 6.0);
let r = Ray::new(origin, direction);
assert_eq!(r.origin, origin);
assert_eq!(r.direction, direction);
}
#[test]
fn test_computing_a_point_from_a_distance() {
let r = Ray::new(Tuple::point(2.0, 3.0, 4.0), Tuple::vector(1.0, 0.0, 0.0));
assert_eq!(r.position(0.0), Tuple::point(2.0, 3.0, 4.0));
assert_eq!(r.position(1.0), Tuple::point(3.0, 3.0, 4.0));
assert_eq!(r.position(-1.0), Tuple::point(1.0, 3.0, 4.0));
assert_eq!(r.position(2.5), Tuple::point(4.5, 3.0, 4.0));
}
#[test]
fn test_translating_a_ray() {
let r = Ray::new(Tuple::point(1.0, 2.0, 3.0), Tuple::vector(0.0, 1.0, 0.0));
let m = Matrix4::translation(3.0, 4.0, 5.0);
let r2 = r.transform(m);
assert_eq!(r2.origin, Tuple::point(4.0, 6.0, 8.0));
assert_eq!(r2.direction, Tuple::vector(0.0, 1.0, 0.0));
}
#[test]
fn test_scaling_a_ray() {
let r = Ray::new(Tuple::point(1.0, 2.0, 3.0), Tuple::vector(0.0, 1.0, 0.0));
let m = Matrix4::scaling(2.0, 3.0, 4.0);
let r2 = r.transform(m);
assert_eq!(r2.origin, Tuple::point(2.0, 6.0, 12.0));
assert_eq!(r2.direction, Tuple::vector(0.0, 3.0, 0.0));
}
|
use std::fs;
fn find_sum_of_two(numbers: &[i32], sum: i32) -> Option<(i32, i32)> {
if numbers.len() <= 1 { return None; }
let n1 = numbers[0];
for n2 in &numbers[1..] {
if n1 + n2 == sum { return Some((n1, *n2)) };
}
find_sum_of_two(&numbers[1..], sum)
}
fn find_sum_of_three(numbers: &[i32], sum: i32) -> Option<(i32, i32, i32)> {
if numbers.len() <= 2 { return None; }
let n1 = numbers[0];
match find_sum_of_two(&numbers[1..], sum - n1) {
Some((n2, n3)) => Some((n1, n2, n3)),
None => find_sum_of_three(&numbers[1..], sum)
}
}
fn main() {
let mut numbers: Vec<i32> = Vec::new();
let input = fs::read_to_string("input").unwrap();
for entry in input.lines() {
numbers.push(entry.parse::<i32>().unwrap());
}
// Part 1
if let Some((n1, n2)) = find_sum_of_two(numbers.as_slice(), 2020) {
println!("{} * {} = {}", n1, n2, n1 * n2);
}
// Part 2
if let Some((n1, n2, n3)) = find_sum_of_three(numbers.as_slice(), 2020) {
println!("{} * {} * {} = {}", n1, n2, n3, n1 * n2 * n3);
}
}
#[test]
fn test_sum_two() {
let numbers = [1721, 979, 366, 299, 675, 1456];
let (n1, n2) = find_sum_of_two(&numbers, 2020).unwrap();
assert_eq!(n1 * n2, 514579);
}
#[test]
fn test_sum_three() {
let numbers = [1721, 979, 366, 299, 675, 1456];
let (n1, n2, n3) = find_sum_of_three(&numbers, 2020).unwrap();
assert_eq!(n1 * n2 * n3, 241861950);
}
|
pub mod manage_packets;
pub mod types;
|
#![feature(
associated_type_defaults,
const_fn,
macro_at_most_once_rep,
nll,
rust_2018_preview,
slice_patterns,
specialization,
try_from,
underscore_imports,
use_extern_macros,
)]
#![warn(rust_2018_idioms)]
#![cfg_attr(feature = "cargo-clippy", warn(clippy))]
pub mod aggregate;
pub mod bxdf;
pub mod camera;
pub mod film;
pub mod filter;
pub mod interaction;
pub mod integrator;
pub mod light;
pub mod material;
pub mod math;
pub mod primitive;
pub mod sampler;
pub mod sampling;
pub mod scene;
pub mod shape;
pub mod spectrum;
pub mod texture;
pub mod prelude {
use cgmath;
pub use pbrt_proc::*;
pub use num::Float as NumFloatTrait;
pub use crate::math::*;
use super::spectrum;
pub use crate::spectrum::Spectrum as PbrtSpectrumTrait;
pub type Spectrum = spectrum::RgbSpectrum;
pub type Bounds2f = Bounds2<Float>;
pub type Bounds2i = Bounds2<i32>;
pub type Bounds3f = Bounds3<Float>;
pub type Bounds3i = Bounds3<i32>;
pub type Vector2f = cgmath::Vector2<Float>;
pub type Vector2i = cgmath::Vector2<i32>;
pub type Vector3f = cgmath::Vector3<Float>;
pub type Vector3i = cgmath::Vector3<i32>;
pub type Point2f = cgmath::Point2<Float>;
pub type Point2i = cgmath::Point2<i32>;
pub type Point3f = cgmath::Point3<Float>;
pub type Point3i = cgmath::Point3<i32>;
}
|
use std::ops::{Index, IndexMut, Deref};
use num_traits::{Float, Zero};
use totsu_core::solver::SliceLike;
use totsu_core::{LinAlgEx, MatType, MatOp};
//
/// Matrix builder
///
/// <script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
/// <script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js"></script>
///
/// Matrix struct which owns a `Vec` of data array and is able to be converted as [`totsu_core::MatOp`].
/// This struct relies on dynamic heap allocation.
#[derive(Clone)]
pub struct MatBuild<L: LinAlgEx>
{
typ: MatType,
array: Vec<L::F>,
}
impl<L: LinAlgEx> MatBuild<L>
{
/// Creates an instance.
///
/// Returns the [`MatBuild`] instance with zero data.
/// * `typ` is Matrix type and size.
pub fn new(typ: MatType) -> Self
{
MatBuild {
typ,
array: vec![L::F::zero(); typ.len()],
}
}
/// Size of the matrix.
///
/// Returns a tuple of a number of rows and columns.
pub fn size(&self) -> (usize, usize)
{
self.typ.size()
}
/// Converted as [`totsu_core::MatOp`].
///
/// Returns the [`totsu_core::MatOp`] borrowing the internal data array.
pub fn as_op(&self) -> MatOp<'_, L>
{
MatOp::new(self.typ, &self.array)
}
/// Checks if symmetric packed.
///
/// Returns `true` if [`MatType::SymPack`], `false` otherwise.
pub fn is_sympack(&self) -> bool
{
if let MatType::SymPack(_) = self.typ {
true
}
else {
false
}
}
/// Data by a function.
///
/// * `func` takes a row and a column of the matrix and returns data of each element.
pub fn set_by_fn<M>(&mut self, mut func: M)
where M: FnMut(usize, usize) -> L::F
{
match self.typ {
MatType::General(nr, nc) => {
for c in 0.. nc {
for r in 0.. nr {
self[(r, c)] = func(r, c);
}
}
},
MatType::SymPack(n) => {
for c in 0.. n {
for r in 0..= c {
self[(r, c)] = func(r, c);
}
}
},
};
}
/// Builder pattern of [`MatBuild::set_by_fn`].
pub fn by_fn<M>(mut self, func: M) -> Self
where M: FnMut(usize, usize) -> L::F
{
self.set_by_fn(func);
self
}
/// Data by an iterator in column-major.
///
/// * `iter` iterates matrix data in column-major.
pub fn set_iter_colmaj<T, I>(&mut self, iter: T)
where T: IntoIterator<Item=I>, I: Deref<Target=L::F>
{
let mut i = iter.into_iter();
let (nr, nc) = self.typ.size();
for c in 0.. nc {
for r in 0.. nr {
if let Some(v) = i.next() {
self[(r, c)] = *v;
}
else {
break;
}
}
}
}
/// Builder pattern of [`MatBuild::set_iter_colmaj`].
pub fn iter_colmaj<T, I>(mut self, iter: T) -> Self
where T: IntoIterator<Item=I>, I: Deref<Target=L::F>
{
self.set_iter_colmaj(iter);
self
}
/// Data by an iterator in row-major.
///
/// * `iter` iterates matrix data in row-major.
pub fn set_iter_rowmaj<T, I>(&mut self, iter: T)
where T: IntoIterator<Item=I>, I: Deref<Target=L::F>
{
let mut i = iter.into_iter();
let (nr, nc) = self.typ.size();
for r in 0.. nr {
for c in 0.. nc {
if let Some(v) = i.next() {
self[(r, c)] = *v;
}
else {
break;
}
}
}
}
/// Builder pattern of [`MatBuild::set_iter_rowmaj`].
pub fn iter_rowmaj<T, I>(mut self, iter: T) -> Self
where T: IntoIterator<Item=I>, I: Deref<Target=L::F>
{
self.set_iter_rowmaj(iter);
self
}
/// Scales by \\(\alpha\\).
///
/// * `alpha` is a scalar \\(\alpha\\).
pub fn set_scale(&mut self, alpha: L::F)
{
L::scale(alpha, &mut L::Sl::new_mut(&mut self.array));
}
/// Builder pattern of [`MatBuild::set_scale`].
pub fn scale(mut self, alpha: L::F) -> Self
{
self.set_scale(alpha);
self
}
/// Scales by \\(\alpha\\) except diagonal elements.
///
/// * `alpha` is a scalar \\(\alpha\\).
pub fn set_scale_nondiag(&mut self, alpha: L::F)
{
match self.typ {
MatType::General(nr, nc) => {
let n = nr.min(nc);
for c in 0.. n - 1 {
let i = self.index((c, c));
let (_, spl) = self.array.split_at_mut(i + 1);
let (spl, _) = spl.split_at_mut(nc);
L::scale(alpha, &mut L::Sl::new_mut(spl));
}
let i = self.index((n, n));
let (_, spl) = self.array.split_at_mut(i + 1);
L::scale(alpha, &mut L::Sl::new_mut(spl));
},
MatType::SymPack(n) => {
for c in 0.. n - 1 {
let i = self.index((c, c));
let ii = self.index((c + 1, c + 1));
let (_, spl) = self.array.split_at_mut(i + 1);
let (spl, _) = spl.split_at_mut(ii - i - 1);
L::scale(alpha, &mut L::Sl::new_mut(spl));
}
},
}
}
/// Builder pattern of [`MatBuild::set_scale_nondiag`].
pub fn scale_nondiag(mut self, alpha: L::F) -> Self
{
self.set_scale_nondiag(alpha);
self
}
/// Reshapes the internal data array as it is into a one-column matrix.
pub fn set_reshape_colvec(&mut self)
{
let sz = self.array.len();
self.typ = MatType::General(sz, 1);
}
/// Builder pattern of [`MatBuild::set_reshape_colvec`].
pub fn reshape_colvec(mut self) -> Self
{
self.set_reshape_colvec();
self
}
/// Calculates and converts the matrix \\(A\\) to \\(A^{\frac12}\\).
///
/// The matrix shall belong to [`MatType::SymPack`].
/// * `eps_zero` should be the same value as [`totsu_core::solver::SolverParam::eps_zero`].
pub fn set_sqrt(&mut self, eps_zero: L::F)
{
match self.typ {
MatType::General(_, _) => {
unimplemented!()
},
MatType::SymPack(n) => {
let mut work_vec = vec![L::F::zero(); L::map_eig_worklen(n)];
let mut work = L::Sl::new_mut(&mut work_vec);
let f0 = L::F::zero();
L::map_eig(&mut L::Sl::new_mut(&mut self.array), None, eps_zero, &mut work, |e| {
if e > f0 {
Some(e.sqrt())
}
else {
None
}
});
}
}
}
/// Builder pattern of [`MatBuild::set_sqrt`].
pub fn sqrt(mut self, eps_zero: L::F) -> Self
{
self.set_sqrt(eps_zero);
self
}
fn index(&self, (r, c): (usize, usize)) -> usize
{
let i = match self.typ {
MatType::General(nr, nc) => {
assert!(r < nr);
assert!(c < nc);
c * nr + r
},
MatType::SymPack(n) => {
assert!(r < n);
assert!(c < n);
let (r, c) = if r <= c {
(r, c)
}
else {
(c, r)
};
c * (c + 1) / 2 + r
},
};
assert!(i < self.array.len());
i
}
}
//
impl<L: LinAlgEx> Index<(usize, usize)> for MatBuild<L>
{
type Output = L::F;
fn index(&self, index: (usize, usize)) -> &Self::Output
{
let i = self.index(index);
&self.array[i]
}
}
impl<L: LinAlgEx> IndexMut<(usize, usize)> for MatBuild<L>
{
fn index_mut(&mut self, index: (usize, usize)) -> &mut Self::Output
{
let i = self.index(index);
&mut self.array[i]
}
}
//
mod ex;
//
#[test]
fn test_matbuild1()
{
use float_eq::assert_float_eq;
use totsu_core::FloatGeneric;
type L= FloatGeneric<f64>;
let ref_array = &[ // column-major, upper-triangle (seen as if transposed)
1.,
2.*1.4, 3.,
4.*1.4, 5.*1.4, 6.,
7.*1.4, 8.*1.4, 9.*1.4, 10.,
11.*1.4, 12.*1.4, 13.*1.4, 14.*1.4, 15.,
];
let array = &[ // column-major, upper-triangle (seen as if transposed)
1., 0., 0., 0., 0.,
2., 3., 0., 0., 0.,
4., 5., 6., 0., 0.,
7., 8., 9., 10., 0.,
11., 12., 13., 14., 15.,
];
let m = MatBuild::<L>::new(MatType::SymPack(5))
.iter_colmaj(array)
.scale_nondiag(1.4);
let m_array: &[f64] = m.array.as_ref();
assert_float_eq!(m_array, ref_array.as_ref(), abs_all <= 1e-3);
}
|
use std::io;
use std::sync::mpsc;
use std::thread;
use termion::event::Key;
use termion::input::TermRead;
pub enum Event<I> {
Input(I),
}
pub struct Events {
rx: mpsc::Receiver<Event<Key>>,
}
impl Events {
pub fn new() -> Events {
let (tx, rx) = mpsc::channel();
let _input_handle = {
let tx = tx.clone();
info!("Spawning input thread");
thread::spawn(move || {
info!("Input thread spawned");
let stdin = io::stdin();
for evt in stdin.keys() {
info!("Event: {:?}", evt);
match evt {
Ok(key) => {
if let Err(e) = tx.send(Event::Input(key)) {
error!("Failed to send input event: {:?}", e);
return;
}
}
Err(e) => {
error!("Failed to read stdin keys, error: {:?}", e);
}
}
}
error!("Input thread aborted");
})
};
Events { rx }
}
pub fn next(&self) -> Result<Event<Key>, mpsc::RecvError> {
self.rx.recv()
}
}
|
// SPDX-License-Identifier: Apache-2.0
pub enum BlockCipherAlgorithm {
Aes128Cbc,
}
impl BlockCipherAlgorithm {
pub fn name(&self) -> &str {
match self {
BlockCipherAlgorithm::Aes128Cbc => "aes-128-cbc",
}
}
pub fn key_len(&self) -> usize {
match self {
BlockCipherAlgorithm::Aes128Cbc => 16,
}
}
pub fn nonce_len(&self) -> usize {
match self {
BlockCipherAlgorithm::Aes128Cbc => 16,
}
}
}
pub trait BlockCipher {
fn encrypt(&mut self, ptext: &[u8], ctext: &mut [u8]);
fn decrypt(&mut self, ctext: &[u8], ptext: &mut [u8]);
}
pub trait BlockCipherBuilder {
fn nonce(&mut self, nonce: &[u8]) -> &mut Self;
fn for_encryption(&mut self, key: &[u8]) -> Box<dyn BlockCipher>;
fn for_decryption(&mut self, key: &[u8]) -> Box<dyn BlockCipher>;
}
pub fn bench_block<B, M>(
group: &mut criterion::BenchmarkGroup<M>,
algorithm: BlockCipherAlgorithm,
mut builder: B,
count: usize,
) where
B: BlockCipherBuilder,
M: criterion::measurement::Measurement,
{
let len = crate::STEP * count;
group.bench_with_input(
criterion::BenchmarkId::new(algorithm.name(), count),
&len,
|b, param| {
use criterion::black_box;
use rand::prelude::*;
let mut rng = rand::thread_rng();
let mut key_bytes = vec![0u8; algorithm.key_len()];
rng.fill(key_bytes.as_mut_slice());
let mut nonce_bytes = vec![0u8; algorithm.nonce_len()];
rng.fill(nonce_bytes.as_mut_slice());
let mut ctx = builder.nonce(&nonce_bytes).for_encryption(&key_bytes);
let pbuf = vec![0u8; *param];
let mut cbuf = vec![0u8; *param];
b.iter(|| {
ctx.encrypt(black_box(&pbuf), black_box(&mut cbuf));
});
},
);
}
|
table! {
languages (id) {
id -> Integer,
language -> Text,
}
}
table! {
words (id) {
id -> Integer,
word -> Text,
word_pattern -> Text,
language_id -> Integer,
}
}
joinable!(words -> languages (language_id));
allow_tables_to_appear_in_same_query!(
languages,
words,
);
|
use mpi::topology::Rank;
use super::session::SessionState;
pub unsafe trait RankSelect {
fn get_rank(state: &SessionState) -> Rank;
}
pub struct ZeroRank;
unsafe impl RankSelect for ZeroRank {
fn get_rank(_: &SessionState) -> Rank {
0
}
}
unsafe impl<K: 'static> RankSelect for crate::key::RankKey<K> {
fn get_rank(state: &SessionState) -> Rank {
*state.get_value::<Self>()
}
}
|
println!("the sum is {}", 80.3 + 34.8);
println!("the sum is {}", 80.3 + 34.9);
println!("{}", (23. - 6.) % 5. + 20. * 30. / (3. + 4.));
// println!("{}", 2.7 + 1);
println!("{}", 2.7 + 1.);
println!("{} {}", -12 % 10, -1.2 % 1.);
|
use std::fmt::{Show, Formatter, Result};
use token::*;
pub type Ident = String;
#[deriving(PartialEq)]
pub struct Expr {
pub node : Expr_
}
impl Show for Expr {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "{}", self.node)
}
}
#[deriving(PartialEq)]
pub struct Stmt {
pub node : Stmt_
}
impl Show for Stmt {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "{}", self.node)
}
}
#[deriving(Show, PartialEq)]
pub enum Expr_ {
//1.prop_path, 2.params
FuncCall(Vec<Ident>, Vec<Box<Expr>>),
//1.start, 2.end
InclusiveRange(Box<Expr>, Box<Expr>),
//1.start, 2.end
ExclusiveRange(Box<Expr>, Box<Expr>),
//1.value
Int(int),
//1.value
IdentExpr(Ident),
//1.lhs, 2.op, 3.rhs
BinaryExpr(Box<Expr>, String, Box<Expr>),
//1.op, 2.expr
PrefixUnaryExpr(Ident, Box<Expr>)
}
pub mod FuncCall {
use self::super::{Expr, Ident, FuncCall};
pub fn new(prop_path : Vec<Ident>, params : Vec<Box<Expr>>) -> Box<Expr> {
box Expr {
node : FuncCall(prop_path, params)
}
}
}
pub mod InclusiveRange {
use self::super::{Expr, InclusiveRange};
pub fn new(start : Box<Expr>, end : Box<Expr>) -> Box<Expr> {
box Expr {
node : InclusiveRange(start, end)
}
}
}
pub mod ExclusiveRange {
use self::super::{Expr, ExclusiveRange};
pub fn new(start : Box<Expr>, end : Box<Expr>) -> Box<Expr> {
box Expr {
node : ExclusiveRange(start, end)
}
}
}
pub mod Int {
use self::super::{Expr, Int};
pub fn new(value : int) -> Box<Expr> {
box Expr {
node : Int(value)
}
}
}
pub mod IdentExpr {
use self::super::{Expr, Ident, IdentExpr};
pub fn new(value : Ident) -> Box<Expr> {
box Expr {
node : IdentExpr(value)
}
}
}
pub mod BinaryExpr {
use self::super::{Expr, BinaryExpr};
pub fn new(lhs : Box<Expr>, op : String, rhs : Box<Expr>) -> Box<Expr> {
box Expr {
node : BinaryExpr(lhs, op, rhs)
}
}
}
pub mod PrefixUnaryExpr {
use self::super::{Expr, Ident, PrefixUnaryExpr};
pub fn new(op : Ident, expr : Box<Expr>) -> Box<Expr> {
box Expr {
node : PrefixUnaryExpr(op, expr)
}
}
}
#[deriving(Show, PartialEq)]
pub enum Stmt_ {
//1.expr
ExprStmt(Box<Expr>),
//1.vars
VarDecl(Vec<Ident>),
//1.vars, 2.vals
VarAssign(Vec<Ident>, Vec<Box<Expr>>),
//1.lhs, 2.rhs
AssignStmt(Vec<Vec<Ident>>, Vec<Box<Expr>>),
//1.typ
LoopControlStmt(TokenType),
//1.branches
IfElseStmt(Vec<Box<IfElseBranch>>),
//1.vars, 2.gen, 3.stmts
ForInLoop(Vec<Ident>, Box<Expr>, Vec<Box<Stmt>>),
//1.cond, 2.stmts
WhileLoop(Box<Expr>, Vec<Box<Stmt>>),
//1.name, 2.params, 3.stmts
FunctionDef(Ident, Vec<Ident>, Vec<Box<Stmt>>),
//1.ret_expr
ReturnStmt(Box<Expr>),
//1.name, 2.params, 3.stmts
GeneratorDef(Ident, Vec<Ident>, Vec<Box<Stmt>>),
//1.values
YieldStmt(Vec<Box<Expr>>)
}
pub mod ExprStmt {
use self::super::{Expr, Stmt, ExprStmt};
pub fn new(expr : Box<Expr>) -> Box<Stmt> {
box Stmt {
node : ExprStmt(expr)
}
}
}
pub mod VarDecl {
use self::super::{Stmt, Ident, VarDecl};
pub fn new(vars : Vec<Ident>) -> Box<Stmt> {
box Stmt {
node : VarDecl(vars)
}
}
}
pub mod VarAssign {
use self::super::{Expr, Stmt, Ident, VarAssign};
pub fn new(vars : Vec<Ident>, vals : Vec<Box<Expr>>) -> Box<Stmt> {
box Stmt {
node : VarAssign(vars, vals)
}
}
}
pub mod AssignStmt {
use self::super::{Expr, Stmt, Ident, AssignStmt};
pub fn new(lhs : Vec<Vec<Ident>>, rhs : Vec<Box<Expr>>) -> Box<Stmt> {
box Stmt {
node : AssignStmt(lhs, rhs)
}
}
}
pub mod LoopControlStmt {
use self::super::{Stmt, LoopControlStmt};
use token::TokenType;
pub fn new(typ : TokenType) -> Box<Stmt> {
box Stmt {
node : LoopControlStmt(typ)
}
}
}
#[deriving(PartialEq)]
pub struct IfElseBranch {
pub cond : Option<Box<Expr>>,
pub stmts : Vec<Box<Stmt>>
}
impl IfElseBranch {
pub fn new(cond : Option<Box<Expr>>, stmts : Vec<Box<Stmt>>) -> Box<IfElseBranch> {
box IfElseBranch {
cond : cond,
stmts : stmts
}
}
}
impl Show for IfElseBranch {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "If/Else {}{{ {} }}", self.cond, self.stmts)
}
}
pub mod IfElseStmt {
use self::super::{Stmt, IfElseBranch, IfElseStmt};
pub fn new(branches : Vec<Box<IfElseBranch>>) -> Box<Stmt> {
box Stmt {
node : IfElseStmt(branches)
}
}
}
pub mod ForInLoop {
use self::super::{Expr, Stmt, Ident, ForInLoop};
pub fn new(vars : Vec<Ident>, gen : Box<Expr>, stmts : Vec<Box<Stmt>>) -> Box<Stmt> {
box Stmt {
node : ForInLoop(vars, gen, stmts)
}
}
}
pub mod WhileLoop {
use self::super::{Expr, Stmt, WhileLoop};
pub fn new(cond : Box<Expr>, stmts : Vec<Box<Stmt>>) -> Box<Stmt> {
box Stmt {
node : WhileLoop(cond, stmts)
}
}
}
pub mod FunctionDef {
use self::super::{Stmt, Ident, FunctionDef};
pub fn new(name : Ident, params : Vec<Ident>, stmts : Vec<Box<Stmt>>) -> Box<Stmt> {
box Stmt {
node : FunctionDef(name, params, stmts)
}
}
}
pub mod ReturnStmt {
use self::super::{Expr, Stmt, ReturnStmt};
pub fn new(ret_expr : Box<Expr>) -> Box<Stmt> {
box Stmt {
node : ReturnStmt(ret_expr)
}
}
}
pub mod GeneratorDef {
use self::super::{Stmt, Ident, GeneratorDef};
pub fn new(name : Ident, params : Vec<Ident>, stmts : Vec<Box<Stmt>>) -> Box<Stmt> {
box Stmt {
node : GeneratorDef(name, params, stmts)
}
}
}
pub mod YieldStmt {
use self::super::{Expr, Stmt, YieldStmt};
pub fn new(values : Vec<Box<Expr>>) -> Box<Stmt> {
box Stmt {
node : YieldStmt(values)
}
}
}
|
use std::io::stdin;
use diesel::prelude::*;
use sl_lib::models::*;
use sl_lib::*;
use console::Style;
pub fn publish_or_unpublish() {
let green = Style::new().green();
let yellow = Style::new().yellow();
let cyan = Style::new().cyan();
let bold = Style::new().bold();
use schema::posts::dsl::*;
println!(
"{}",
bold.apply_to("Type [p] to publish and [u] to unpublish.")
);
let mut post_decision = String::new();
stdin().read_line(&mut post_decision).unwrap();
println!("{}", cyan.apply_to("Type post_id for that."));
let mut post_id = String::new();
stdin().read_line(&mut post_id).unwrap();
let post_id = post_id[..(post_id.len() - 1)]
.parse::<i32>()
.expect("Invalid ID"); // Drop the newline character
let connection = init_pool().get().unwrap();
let result_string = post_decision
.chars()
.next() // equals to .nth(0)
.expect("string is empty");
match result_string {
'p' => {
let post = diesel::update(posts.find(post_id))
.set(published.eq(true))
.get_result::<Post>(&*connection)
.expect(&format!("Unable to find post with id {}", post_id));
let publish_message = format!("Published post with title {}", post.title);
println!("{}", green.apply_to(publish_message));
}
'u' => {
let post = diesel::update(posts.find(post_id))
.set(published.eq(true))
.get_result::<Post>(&*connection)
.expect(&format!("Unable to find post with id {}", post_id));
println!(
"{}",
yellow.apply_to(format!("Unpublished post with title {}", post.title))
);
}
_ => println!("Invalid input, You should type either p or u to command line."),
}
}
|
pub enum OsuKeyboardError {
InitializationFailed,
}
pub fn report(error: OsuKeyboardError) -> ! {
let error_handle = match error {
_ => || {},
};
loop {
(error_handle)();
arduino_uno::delay_ms(1000_u16)
}
}
// fn stutter_blink(led: &mut PB5<Output>, times: usize) {
// (0..times).map(|i| i * 10).for_each(|i| {
// led.toggle().void_unwrap();
// arduino_uno::delay_ms(i as u16);
// });
// }
|
use {neon::prelude::*, solana_program::pubkey::Pubkey, std::str::FromStr};
fn to_vec(cx: &mut FunctionContext, list: &Handle<JsValue>) -> NeonResult<Vec<String>> {
if list.is_a::<JsArray, _>(cx) {
let list = list.downcast::<JsArray, _>(cx).unwrap();
let len = list.len(cx) as usize;
let mut result: Vec<String> = Vec::with_capacity(len);
for index in 0..len {
let item = list.get(cx, index as u32)?;
let item = item.to_string(cx)?;
let item = item.value(cx);
result.insert(index, item);
}
return Ok(result);
} else if list.is_a::<JsString, _>(cx) {
let item = list.downcast::<JsString, _>(cx).unwrap().value(cx);
let result = vec![item];
return Ok(result);
} else {
return Ok(vec![]);
}
}
trait AddressJob {
fn try_manipulate_with_address(
&self,
program_id: &Pubkey,
a1: &String,
a2: &String,
a3: &String,
a4: &String,
) -> Option<Pubkey>;
}
struct FinderPubKey;
impl AddressJob for FinderPubKey {
fn try_manipulate_with_address(
&self,
program_id: &Pubkey,
a1: &String,
a2: &String,
a3: &String,
a4: &String,
) -> Option<Pubkey> {
let s2 = Pubkey::from_str(&a2[..]).ok()?;
let s3 = Pubkey::from_str(&a3[..]).ok()?;
let s4 = Pubkey::from_str(&a4[..]).ok()?;
let seeds = [a1.as_bytes(), s2.as_ref(), s3.as_ref(), s4.as_ref()];
let (key, _) = Pubkey::try_find_program_address(&seeds, &program_id)?;
Some(key)
}
}
struct FinderLastBuf;
impl AddressJob for FinderLastBuf {
fn try_manipulate_with_address(
&self,
program_id: &Pubkey,
a1: &String,
a2: &String,
a3: &String,
a4: &String,
) -> Option<Pubkey> {
let s2 = Pubkey::from_str(&a2[..]).ok()?;
let s3 = Pubkey::from_str(&a3[..]).ok()?;
let seeds = [a1.as_bytes(), s2.as_ref(), s3.as_ref(), a4.as_bytes()];
let (key, _) = Pubkey::try_find_program_address(&seeds, &program_id)?;
Some(key)
}
}
struct CreateAddress3Pubkey;
impl AddressJob for CreateAddress3Pubkey {
fn try_manipulate_with_address(
&self,
program_id: &Pubkey,
a1: &String,
a2: &String,
a3: &String,
a4: &String,
) -> Option<Pubkey> {
let s2 = Pubkey::from_str(&a2[..]).ok()?;
let s3 = Pubkey::from_str(&a3[..]).ok()?;
let s4 = a4.parse::<u8>().ok()?;
let s4 = [s4];
let seeds = [a1.as_bytes(), s2.as_ref(), s3.as_ref(), &s4];
let key = Pubkey::create_program_address(&seeds, &program_id).ok()?;
Some(key)
}
}
fn get_finder(mode: &str) -> Option<Box<dyn AddressJob>> {
match mode {
"FinderPubKey" => Some(Box::new(FinderPubKey {})),
"FinderLastBuf" => Some(Box::new(FinderLastBuf {})),
"CreateAddress3Pubkey" => Some(Box::new(CreateAddress3Pubkey {})),
_ => None,
}
}
fn program_address(mut cx: FunctionContext) -> JsResult<JsUndefined> {
let mode = cx.argument::<JsString>(0)?.value(&mut cx);
let program_key = cx.argument::<JsString>(1)?.value(&mut cx);
let block1 = cx.argument::<JsString>(2)?.value(&mut cx);
let block2 = cx.argument::<JsString>(3)?.value(&mut cx);
let blocks3 = cx.argument::<JsValue>(4)?;
let blocks4 = cx.argument::<JsValue>(5)?;
let program_id = Pubkey::from_str(&program_key[..]).unwrap();
let cb_root = cx.argument::<JsFunction>(6)?.root(&mut cx);
let channel = cx.channel();
let blocks3 = to_vec(&mut cx, &blocks3)?;
let blocks4 = to_vec(&mut cx, &blocks4)?;
std::thread::spawn(move || {
channel.send(move |mut cx| {
let finder = get_finder(&mode[..]).unwrap();
let callback = cb_root.into_inner(&mut cx);
let null = cx.null();
let block1_n = cx.string(&block1);
let block2_n = cx.string(&block2);
for block3 in &blocks3 {
for block4 in &blocks4 {
let address = finder.try_manipulate_with_address(
&program_id,
&block1,
&block2,
block3,
block4,
);
if let Some(key) = address {
let key = key.to_string();
let key = cx.string(key);
let val3 = cx.string(block3);
let val4 = cx.string(block4);
callback.call(&mut cx, null, vec![key, block1_n, block2_n, val3, val4])?;
}
}
}
callback.call(&mut cx, null, vec![null])?;
Ok({})
});
});
Ok(cx.undefined())
}
#[neon::main]
fn main(mut cx: ModuleContext) -> NeonResult<()> {
cx.export_function("programAddressList", program_address)?;
Ok(())
}
|
//
// Rust windows (イテレーションの方)
// https://qiita.com/hystcs/items/d33e77084277cdba8052
//
// Rust By Example の タプル
// https://doc.rust-jp.rs/rust-by-example-ja/primitives/tuples.html
//
fn naruhodo(chars: &[char]) -> char {
(chars
.windows(2)
.map(|w| (w[0] as u8, w[1] as u8))
.find(|&w| w.0 + 1 != w.1)
.unwrap()
.0
+ 1) as char
}
fn find_missing_letter(chars: &[char]) -> char {
for i in 0..chars.len() {
let expected = chars[i] as u8 + 1;
let next = chars[i + 1] as u8;
if expected != next {
return char::from(expected);
}
}
panic!();
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn example_tests() {
assert_eq!(find_missing_letter(&['a', 'b', 'c', 'd', 'f']), 'e');
assert_eq!(find_missing_letter(&['O', 'Q', 'R', 'S']), 'P');
}
#[test]
fn example_tests2() {
assert_eq!(naruhodo(&['a', 'b', 'c', 'd', 'f']), 'e');
assert_eq!(naruhodo(&['O', 'Q', 'R', 'S']), 'P');
}
}
|
use crate::error::{Error, Result, TypeError};
use crate::parsing::{parse, Sexpr as PS, SpannedSexpr};
use crate::scm::Scm;
use crate::source::{Source, SourceLocation};
use crate::symbol::Symbol;
use crate::syntactic_closure::SyntacticClosure;
use std::fmt::Debug;
use std::rc::Rc;
#[derive(Debug, Clone)]
pub struct TrackedSexpr {
pub sexpr: Sexpr,
pub src: SourceLocation,
}
// TODO: Should we intern symbols and string?
#[derive(Debug, Clone, PartialEq)]
pub enum Sexpr {
Undefined,
Uninitialized,
Nil,
True,
False,
Symbol(Symbol),
String(Rc<str>),
Int(i64),
Float(f64),
Pair(Box<(TrackedSexpr, TrackedSexpr)>),
Vector(Vec<TrackedSexpr>),
SyntacticClosure(Rc<SyntacticClosure>),
}
impl std::fmt::Display for TrackedSexpr {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::Display::fmt(&self.sexpr, f)
}
}
impl std::fmt::Display for Sexpr {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Sexpr::Undefined => write!(f, "*undefined*"),
Sexpr::Uninitialized => write!(f, "*uninitialized*"),
Sexpr::Nil => write!(f, "'()"),
Sexpr::True => write!(f, "#t"),
Sexpr::False => write!(f, "#f"),
Sexpr::Symbol(s) => write!(f, "{}", s),
Sexpr::String(s) => write!(f, "\"{}\"", s),
Sexpr::Int(i) => write!(f, "{}", i),
Sexpr::Float(i) => write!(f, "{}", i),
Sexpr::Pair(p) => {
write!(f, "(")?;
write!(f, "{}", p.0)?;
let mut p = &p.1;
while let Some((car, cdr)) = p.as_pair() {
write!(f, " {}", car)?;
p = cdr;
}
if !p.is_null() {
write!(f, " . {}", p)?;
}
write!(f, ")")
}
Sexpr::Vector(items) => {
write!(f, "#(")?;
write!(f, "{}", items[0])?;
for i in &items[1..] {
write!(f, " {}", i)?;
}
write!(f, ")")
}
Sexpr::SyntacticClosure(sc) => write!(f, "<{}>", sc.sexpr()),
}
}
}
impl TrackedSexpr {
pub fn from_source(source: &Source) -> Result<Vec<Self>> {
parse(&source.content)
.map(|sexprs| {
sexprs
.into_iter()
.map(|sexpr| Self::from_spanned(sexpr, source.clone()))
.collect()
})
.map_err(|e| Error::from_parse_error_and_source(e, source.clone()))
}
pub fn from_spanned(se: SpannedSexpr, source: Source) -> Self {
match se.expr {
PS::Nil => TrackedSexpr::new(Sexpr::Nil, SourceLocation::from_spanned(se.span, source)),
PS::True => {
TrackedSexpr::new(Sexpr::True, SourceLocation::from_spanned(se.span, source))
}
PS::False => {
TrackedSexpr::new(Sexpr::False, SourceLocation::from_spanned(se.span, source))
}
PS::Symbol(s) => TrackedSexpr::new(
Sexpr::Symbol(s.into()),
SourceLocation::from_spanned(se.span, source),
),
PS::String(s) => TrackedSexpr::new(
Sexpr::String(s.into()),
SourceLocation::from_spanned(se.span, source),
),
PS::Integer(i) => {
TrackedSexpr::new(Sexpr::Int(i), SourceLocation::from_spanned(se.span, source))
}
PS::Float(f) => TrackedSexpr::new(
Sexpr::Float(f),
SourceLocation::from_spanned(se.span, source),
),
PS::List(l) if l.is_empty() => {
TrackedSexpr::new(Sexpr::Nil, SourceLocation::from_spanned(se.span, source))
}
PS::List(l) => {
let mut out_list = TrackedSexpr::nil(
SourceLocation::from_spanned(se.span, source.clone()).last_char(),
);
for x in l.into_iter().rev() {
if let PS::Dot = x.expr {
out_list = out_list.decons().unwrap().0;
} else {
let src = out_list
.src
.start_at(&SourceLocation::from_spanned(x.span, source.clone()));
out_list = TrackedSexpr::cons(
Self::from_spanned(x, source.clone()),
out_list,
src,
);
}
}
out_list
}
PS::Vector(l) => {
let items: Vec<_> = l
.into_iter()
.map(|i| Self::from_spanned(i, source.clone()))
.collect();
TrackedSexpr::new(
Sexpr::Vector(items.into()),
SourceLocation::from_spanned(se.span, source),
)
}
x => unimplemented!("SpannedSexpr::{:?} --> TrackesSexpr", x),
}
}
pub fn with_src(mut self, src: SourceLocation) -> Self {
self.src = src;
self
}
pub fn new(sexpr: Sexpr, src: SourceLocation) -> Self {
TrackedSexpr { sexpr, src }
}
pub fn into_sexpr(self) -> Sexpr {
self.sexpr
}
pub fn source(&self) -> &SourceLocation {
&self.src
}
pub fn undefined() -> Self {
TrackedSexpr {
sexpr: Sexpr::Undefined,
src: SourceLocation::NoSource,
}
}
pub fn nil(src: SourceLocation) -> Self {
TrackedSexpr {
sexpr: Sexpr::Nil,
src,
}
}
pub fn symbol(s: impl Into<Symbol>, src: SourceLocation) -> Self {
TrackedSexpr {
sexpr: Sexpr::Symbol(s.into()),
src,
}
}
pub fn list(data: Vec<TrackedSexpr>, src: SourceLocation) -> Self {
let mut l = TrackedSexpr::nil(src.last_char());
for x in data.into_iter().rev() {
let src = l.src.start_at(&x.src);
l = TrackedSexpr::cons(x, l, src);
}
l
}
pub fn cons(car: Self, cdr: Self, src: SourceLocation) -> Self {
TrackedSexpr {
sexpr: Sexpr::Pair(Box::new((car, cdr))),
src,
}
}
pub fn car(&self) -> Result<&Self> {
match &self.sexpr {
Sexpr::Pair(p) => Ok(&p.0),
_ => Err(Error::at_expr(
TypeError::NoPair(Scm::string(format!("{}", self))),
self,
)),
}
}
pub fn cdr(&self) -> Result<&Self> {
match &self.sexpr {
Sexpr::Pair(p) => Ok(&p.1),
_ => Err(Error::at_expr(
TypeError::NoPair(Scm::string(format!("{}", self))),
self,
)),
}
}
pub fn decons(self) -> std::result::Result<(Self, Self), Self> {
match self.sexpr {
Sexpr::Pair(p) => Ok((p.0, p.1)),
_ => Err(self),
}
}
pub fn at(&self, idx: usize) -> Result<&Self> {
if idx == 0 {
self.car()
} else {
self.cdr().and_then(|cdr| cdr.at(idx - 1))
}
}
pub fn is_null(&self) -> bool {
match self.sexpr {
Sexpr::Nil => true,
_ => false,
}
}
pub fn is_atom(&self) -> bool {
match &self.sexpr {
Sexpr::Pair(_) => false,
_ => true,
}
}
pub fn is_identifier(&self) -> bool {
self.is_symbol() || self.is_alias()
}
pub fn identifier_name(&self) -> Option<Symbol> {
match &self.sexpr {
Sexpr::Symbol(s) => Some(*s),
Sexpr::SyntacticClosure(sc) => sc.alias_name(),
_ => None,
}
}
pub fn is_alias(&self) -> bool {
self.as_alias().is_some()
}
pub fn as_alias(&self) -> Option<&Rc<SyntacticClosure>> {
match &self.sexpr {
Sexpr::SyntacticClosure(sc) if sc.is_alias() => Some(sc),
_ => None,
}
}
pub fn is_symbol(&self) -> bool {
self.as_symbol().is_ok()
}
pub fn as_symbol(&self) -> Result<&Symbol> {
match &self.sexpr {
Sexpr::Symbol(s) => Ok(s),
Sexpr::SyntacticClosure(sc) => sc.sexpr().as_symbol(),
_ => Err(Error::at_expr(TypeError::NoSymbol, self)),
}
}
pub fn is_pair(&self) -> bool {
self.as_pair().is_some()
}
pub fn as_pair(&self) -> Option<(&Self, &Self)> {
match &self.sexpr {
Sexpr::Pair(p) => Some((&p.0, &p.1)),
_ => None,
}
}
pub fn scan<E>(
&self,
mut f: impl FnMut(&Self) -> std::result::Result<(), E>,
) -> std::result::Result<&Self, E> {
let mut x = self;
while x.is_pair() {
f(x.car().unwrap())?;
x = x.cdr().unwrap();
}
Ok(x)
}
pub fn scan_improper<E>(
&self,
mut f: impl FnMut(&Self, bool) -> std::result::Result<(), E>,
) -> std::result::Result<&Self, E> {
let mut x = self;
while x.is_pair() {
f(x.car().unwrap(), false)?;
x = x.cdr().unwrap();
}
f(x, true)?;
Ok(x)
}
pub fn contains(&self, x: &Sexpr) -> bool {
match &self.sexpr {
Sexpr::Vector(v) => v.iter().find(|item| &item.sexpr == x).is_some(),
Sexpr::Pair(p) if &p.0.sexpr == x => true,
Sexpr::Pair(p) => p.1.contains(x),
_ => false,
}
}
pub fn list_len(&self) -> usize {
match &self.sexpr {
Sexpr::Pair(p) => 1 + p.1.list_len(),
_ => 0,
}
}
}
impl From<lexpr::Value> for Sexpr {
fn from(x: lexpr::Value) -> Self {
use lexpr::Value::*;
match x {
Null => Sexpr::Nil,
Number(ref n) if n.is_i64() => Sexpr::Int(n.as_i64().unwrap()),
Symbol(s) => Sexpr::Symbol(s.into()),
Cons(p) => {
let (car, cdr) = p.into_pair();
Sexpr::Pair(Box::new((car.into(), cdr.into())))
}
_ => unimplemented!("{:?}", x),
}
}
}
impl From<lexpr::Value> for TrackedSexpr {
fn from(x: lexpr::Value) -> Self {
TrackedSexpr {
sexpr: x.into(),
src: SourceLocation::NoSource,
}
}
}
impl From<Sexpr> for TrackedSexpr {
fn from(sexpr: Sexpr) -> Self {
TrackedSexpr {
sexpr,
src: SourceLocation::NoSource,
}
}
}
impl PartialEq<str> for TrackedSexpr {
fn eq(&self, other: &str) -> bool {
match &self.sexpr {
Sexpr::Symbol(s) => s == other,
Sexpr::String(s) if other.starts_with('"') && other.ends_with('"') => {
**s == other[1..other.len() - 1]
}
Sexpr::SyntacticClosure(sc) => sc.sexpr() == other,
_ => false,
}
}
}
impl PartialEq for TrackedSexpr {
fn eq(&self, other: &Self) -> bool {
self.sexpr == other.sexpr
}
}
|
use std::convert::AsRef;
use xml::Element;
use ::{ElementUtils, NS, ViaXml};
/// [The Atom Syndication Format § The "atom:generator" Element]
/// (https://tools.ietf.org/html/rfc4287#section-4.2.4)
#[derive(Default)]
pub struct Generator {
pub name: String,
pub uri: Option<String>,
pub version: Option<String>,
}
impl ViaXml for Generator {
fn to_xml(&self) -> Element {
let mut link = Element::new("generator".to_string(), Some(NS.to_string()), vec![]);
link.text(self.name.clone());
link.attribute_with_optional_text("uri", &self.uri);
link.attribute_with_optional_text("version", &self.version);
link
}
fn from_xml(elem: Element) -> Result<Self, &'static str> {
let name = match elem.content_str().as_ref() {
"" => return Err(r#"<generator> is missing required name"#),
n => n.to_string(),
};
let uri = elem.get_attribute("uri", None).map(String::from);
let version = elem.get_attribute("version", None).map(String::from);
Ok(Generator {
name: name,
uri: uri,
version: version,
})
}
}
|
//! ECS input bundle
use std::hash::Hash;
use std::path::Path;
use serde::Serialize;
use serde::de::DeserializeOwned;
use winit::Event;
use app::ApplicationBuilder;
use config::Config;
use ecs::ECSBundle;
use ecs::input::{Bindings, InputEvent, InputHandler, InputSystem};
use error::Result;
use shrev::EventHandler;
/// Bundle for adding the `InputHandler`.
///
/// This also adds the Winit EventHandler and the InputEvent<AC> EventHandler
/// where AC is the type for Actions you have assigned here.
///
/// ## Type parameters
///
/// AX: The type used to identify input axes.
/// AC: The type used to identify input actions.
///
/// String is appropriate for either of these if you don't know what to use.
///
/// ## Errors
///
/// No errors returned from this bundle.
///
pub struct InputBundle<AX, AC>
where
AX: Hash + Eq,
AC: Hash + Eq,
{
bindings: Option<Bindings<AX, AC>>,
}
impl<AX, AC> InputBundle<AX, AC>
where
AX: Hash + Eq + DeserializeOwned + Serialize + Default,
AC: Hash + Eq + DeserializeOwned + Serialize + Default,
{
/// Create a new input bundle with no bindings
pub fn new() -> Self {
Self { bindings: None }
}
/// Use the provided bindings with the `InputHandler`
pub fn with_bindings(mut self, bindings: Bindings<AX, AC>) -> Self {
self.bindings = Some(bindings);
self
}
/// Load bindings from file
pub fn with_bindings_from_file<P: AsRef<Path>>(self, file: P) -> Self {
self.with_bindings(Bindings::load(file))
}
}
impl<'a, 'b, T, AX, AC> ECSBundle<'a, 'b, T> for InputBundle<AX, AC>
where
AX: Hash + Eq + Clone + Send + Sync + 'static,
AC: Hash + Eq + Clone + Send + Sync + 'static,
{
fn build(
&self,
builder: ApplicationBuilder<'a, 'b, T>,
) -> Result<ApplicationBuilder<'a, 'b, T>> {
let mut input = InputHandler::new();
if let Some(ref bindings) = self.bindings {
input.bindings = bindings.clone();
}
let winit_handler = EventHandler::<Event>::new();
let reader_id = winit_handler.register_reader();
Ok(
builder
.with_resource(input)
.with_resource(winit_handler)
.with_resource(EventHandler::<InputEvent<AC>>::new())
.with(InputSystem::<AX, AC>::new(reader_id), "input_system", &[]),
)
}
}
|
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ListNode {
pub val: i32,
pub next: Option<Box<ListNode>>,
}
impl ListNode {
#[inline]
pub fn new(val: i32) -> Self {
ListNode { next: None, val }
}
pub fn from_array(array: &[i32]) -> Self {
ListNode::from(array)
}
pub fn in_option_box_from_array(array: &[i32]) -> Option<Box<ListNode>> {
if array.is_empty() {
None
} else {
ListNode::from_array(array).to_option_box()
}
}
pub fn to_option_box(self) -> Option<Box<ListNode>> {
Some(Box::new(self))
}
pub fn to_vec(&self) -> Vec<i32> {
let mut vec = Vec::new();
self._to_vec(&mut vec);
vec
}
fn _to_vec(&self, vec: &mut Vec<i32>) {
vec.push(self.val);
match &self.next {
None => {}
Some(b) => (*b)._to_vec(vec),
}
}
}
impl From<&[i32]> for ListNode {
fn from(array: &[i32]) -> Self {
let mut current = None;
for &num in array.iter().rev() {
let mut node = ListNode::new(num);
node.next = current;
current = Some(Box::new(node));
}
*current.unwrap()
}
}
#[cfg(test)]
mod tests {
use super::*;
use rstest::rstest;
#[test]
fn from_array() {
let expected = ListNode::new(10);
assert_eq!(ListNode::from_array(&[10]), expected);
let expected = ListNode {
val: 10,
next: Some(Box::new(ListNode {
val: 20,
next: Some(Box::new(ListNode {
val: 30,
next: None,
})),
})),
};
assert_eq!(ListNode::from_array(&[10, 20, 30]), expected)
}
#[test]
#[ignore]
#[should_panic]
fn from_array_panic() {
ListNode::from(&[] as &[i32]);
}
#[test]
fn to_option_box() {
assert_eq!(
ListNode::new(10).to_option_box(),
Some(Box::new(ListNode::new(10)))
);
}
#[rstest(array,
case(&[10]),
case(&[10, 20, 30]),
// ::trace
)]
fn to_vec(array: &[i32]) {
assert_eq!(ListNode::from_array(array).to_vec(), array.to_vec())
}
}
|
mod ast;
mod parsing;
mod tags;
mod tokens;
use ast::{
Expression,
visitor::{ExpressionVisitor, JsonExpressionVisitor}};
use parsing::parse;
use tokens::process_str;
use std::collections::VecDeque;
fn main() {
let mut tokens = process_str("{\"foo\": \"bar\", \"baz\": -123, \"bing\": 5}");
let mut result = parse(tokens);
match result {
Ok(mut expr) => {
let v = &mut JsonExpressionVisitor::new();
expr.accept(v);
println!("{}", v.get_json());
},
Err(e) => panic!("Error trying to parse tokens. {}", e)
}
}
|
#[doc = "Register `NSOBKCFGR` reader"]
pub type R = crate::R<NSOBKCFGR_SPEC>;
#[doc = "Register `NSOBKCFGR` writer"]
pub type W = crate::W<NSOBKCFGR_SPEC>;
#[doc = "Field `LOCK` reader - OBKCFGR lock option configuration bit This bit locks the FLASH_NSOBKCFGR register. The correct write sequence to FLASH_NSOBKKEYR register unlocks this bit. If a wrong sequence is executed, or if the unlock sequence to FLASH_NSOBKKEYR is performed twice, this bit remains locked until the next system reset. LOCK can be set by programming it to 1. When set to 1, a new unlock sequence is mandatory to unlock it. When LOCK changes from 0 to 1, the other bits of FLASH_NSCR register do not change."]
pub type LOCK_R = crate::BitReader;
#[doc = "Field `LOCK` writer - OBKCFGR lock option configuration bit This bit locks the FLASH_NSOBKCFGR register. The correct write sequence to FLASH_NSOBKKEYR register unlocks this bit. If a wrong sequence is executed, or if the unlock sequence to FLASH_NSOBKKEYR is performed twice, this bit remains locked until the next system reset. LOCK can be set by programming it to 1. When set to 1, a new unlock sequence is mandatory to unlock it. When LOCK changes from 0 to 1, the other bits of FLASH_NSCR register do not change."]
pub type LOCK_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SWAP_SECT_REQ` reader - OBK swap sector request bit When set, all the OBKs which have not been updated in the alternate sector is copied from current sector to alternate one. The SWAP_OFFSET value must be a certain minimum value in order for the swap to be launched in OBK-HDPL ≠ 0. Minimum value is 16 for OBK-HDPL = 1, 144 for OBK-HDPL = 2 and 192 for OBK-HDPL = 3."]
pub type SWAP_SECT_REQ_R = crate::BitReader;
#[doc = "Field `SWAP_SECT_REQ` writer - OBK swap sector request bit When set, all the OBKs which have not been updated in the alternate sector is copied from current sector to alternate one. The SWAP_OFFSET value must be a certain minimum value in order for the swap to be launched in OBK-HDPL ≠ 0. Minimum value is 16 for OBK-HDPL = 1, 144 for OBK-HDPL = 2 and 192 for OBK-HDPL = 3."]
pub type SWAP_SECT_REQ_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `ALT_SECT` reader - alternate sector bit This bit must not change while filling the write buffer, otherwise an error (OBKERR) is generated"]
pub type ALT_SECT_R = crate::BitReader;
#[doc = "Field `ALT_SECT` writer - alternate sector bit This bit must not change while filling the write buffer, otherwise an error (OBKERR) is generated"]
pub type ALT_SECT_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `ALT_SECT_ERASE` reader - alternate sector erase bit When ALT_SECT bit is set, use this bit to generate an erase command for the OBK alternate sector. It is set only by Software and cleared when the OBK swap operation is completed or an error occurs (PGSERR). It is reseted at the same time as BUSY bit."]
pub type ALT_SECT_ERASE_R = crate::BitReader;
#[doc = "Field `ALT_SECT_ERASE` writer - alternate sector erase bit When ALT_SECT bit is set, use this bit to generate an erase command for the OBK alternate sector. It is set only by Software and cleared when the OBK swap operation is completed or an error occurs (PGSERR). It is reseted at the same time as BUSY bit."]
pub type ALT_SECT_ERASE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SWAP_OFFSET` reader - Key index (offset /16 bits) pointing for next swap. 0x01 means that only the first OBK data (128 bits) is copied from current to alternate OBK sector 0x02 means that the two first OBK data is copied … …"]
pub type SWAP_OFFSET_R = crate::FieldReader<u16>;
#[doc = "Field `SWAP_OFFSET` writer - Key index (offset /16 bits) pointing for next swap. 0x01 means that only the first OBK data (128 bits) is copied from current to alternate OBK sector 0x02 means that the two first OBK data is copied … …"]
pub type SWAP_OFFSET_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 9, O, u16>;
impl R {
#[doc = "Bit 0 - OBKCFGR lock option configuration bit This bit locks the FLASH_NSOBKCFGR register. The correct write sequence to FLASH_NSOBKKEYR register unlocks this bit. If a wrong sequence is executed, or if the unlock sequence to FLASH_NSOBKKEYR is performed twice, this bit remains locked until the next system reset. LOCK can be set by programming it to 1. When set to 1, a new unlock sequence is mandatory to unlock it. When LOCK changes from 0 to 1, the other bits of FLASH_NSCR register do not change."]
#[inline(always)]
pub fn lock(&self) -> LOCK_R {
LOCK_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - OBK swap sector request bit When set, all the OBKs which have not been updated in the alternate sector is copied from current sector to alternate one. The SWAP_OFFSET value must be a certain minimum value in order for the swap to be launched in OBK-HDPL ≠ 0. Minimum value is 16 for OBK-HDPL = 1, 144 for OBK-HDPL = 2 and 192 for OBK-HDPL = 3."]
#[inline(always)]
pub fn swap_sect_req(&self) -> SWAP_SECT_REQ_R {
SWAP_SECT_REQ_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - alternate sector bit This bit must not change while filling the write buffer, otherwise an error (OBKERR) is generated"]
#[inline(always)]
pub fn alt_sect(&self) -> ALT_SECT_R {
ALT_SECT_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - alternate sector erase bit When ALT_SECT bit is set, use this bit to generate an erase command for the OBK alternate sector. It is set only by Software and cleared when the OBK swap operation is completed or an error occurs (PGSERR). It is reseted at the same time as BUSY bit."]
#[inline(always)]
pub fn alt_sect_erase(&self) -> ALT_SECT_ERASE_R {
ALT_SECT_ERASE_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bits 16:24 - Key index (offset /16 bits) pointing for next swap. 0x01 means that only the first OBK data (128 bits) is copied from current to alternate OBK sector 0x02 means that the two first OBK data is copied … …"]
#[inline(always)]
pub fn swap_offset(&self) -> SWAP_OFFSET_R {
SWAP_OFFSET_R::new(((self.bits >> 16) & 0x01ff) as u16)
}
}
impl W {
#[doc = "Bit 0 - OBKCFGR lock option configuration bit This bit locks the FLASH_NSOBKCFGR register. The correct write sequence to FLASH_NSOBKKEYR register unlocks this bit. If a wrong sequence is executed, or if the unlock sequence to FLASH_NSOBKKEYR is performed twice, this bit remains locked until the next system reset. LOCK can be set by programming it to 1. When set to 1, a new unlock sequence is mandatory to unlock it. When LOCK changes from 0 to 1, the other bits of FLASH_NSCR register do not change."]
#[inline(always)]
#[must_use]
pub fn lock(&mut self) -> LOCK_W<NSOBKCFGR_SPEC, 0> {
LOCK_W::new(self)
}
#[doc = "Bit 1 - OBK swap sector request bit When set, all the OBKs which have not been updated in the alternate sector is copied from current sector to alternate one. The SWAP_OFFSET value must be a certain minimum value in order for the swap to be launched in OBK-HDPL ≠ 0. Minimum value is 16 for OBK-HDPL = 1, 144 for OBK-HDPL = 2 and 192 for OBK-HDPL = 3."]
#[inline(always)]
#[must_use]
pub fn swap_sect_req(&mut self) -> SWAP_SECT_REQ_W<NSOBKCFGR_SPEC, 1> {
SWAP_SECT_REQ_W::new(self)
}
#[doc = "Bit 2 - alternate sector bit This bit must not change while filling the write buffer, otherwise an error (OBKERR) is generated"]
#[inline(always)]
#[must_use]
pub fn alt_sect(&mut self) -> ALT_SECT_W<NSOBKCFGR_SPEC, 2> {
ALT_SECT_W::new(self)
}
#[doc = "Bit 3 - alternate sector erase bit When ALT_SECT bit is set, use this bit to generate an erase command for the OBK alternate sector. It is set only by Software and cleared when the OBK swap operation is completed or an error occurs (PGSERR). It is reseted at the same time as BUSY bit."]
#[inline(always)]
#[must_use]
pub fn alt_sect_erase(&mut self) -> ALT_SECT_ERASE_W<NSOBKCFGR_SPEC, 3> {
ALT_SECT_ERASE_W::new(self)
}
#[doc = "Bits 16:24 - Key index (offset /16 bits) pointing for next swap. 0x01 means that only the first OBK data (128 bits) is copied from current to alternate OBK sector 0x02 means that the two first OBK data is copied … …"]
#[inline(always)]
#[must_use]
pub fn swap_offset(&mut self) -> SWAP_OFFSET_W<NSOBKCFGR_SPEC, 16> {
SWAP_OFFSET_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 non-secure OBK configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`nsobkcfgr::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 [`nsobkcfgr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct NSOBKCFGR_SPEC;
impl crate::RegisterSpec for NSOBKCFGR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`nsobkcfgr::R`](R) reader structure"]
impl crate::Readable for NSOBKCFGR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`nsobkcfgr::W`](W) writer structure"]
impl crate::Writable for NSOBKCFGR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets NSOBKCFGR to value 0x01ff_0000"]
impl crate::Resettable for NSOBKCFGR_SPEC {
const RESET_VALUE: Self::Ux = 0x01ff_0000;
}
|
use hdk::{
self,
error::ZomeApiResult,
entry_definition::ValidatingEntryType,
holochain_core_types::{
dna::entry_types::Sharing,
entry::Entry,
},
holochain_json_api::{
json::JsonString,
error::JsonError,
},
holochain_persistence_api::cas::content::Address,
};
#[derive(Serialize, Deserialize, Debug, DefaultJson, Clone)]
pub struct Calendar {
pub title: String,
}
// Definition
pub fn calendar_definition() -> ValidatingEntryType {
entry!(
name: "calendar",
description: "this is a calendar entry defintion",
sharing: Sharing::Public,
validation_package: || {
hdk::ValidationPackageDefinition::Entry
},
validation: | _validation_data: hdk::EntryValidationData<Calendar>| {
Ok(())
}
)
}
// Store
pub fn create_calendar(title: String) -> ZomeApiResult<Address> {
let calendar = Calendar{
title: title,
};
let calendar_entry = Entry::App(
"calendar".into(),
calendar.into(),
);
let calendar_address = hdk::commit_entry(&calendar_entry)?;
Ok(calendar_address)
}
// Get
pub fn get_calendar(calendar_address: Address) -> ZomeApiResult<Calendar> {
hdk::utils::get_as_type(calendar_address)
}
// Link
// pub fn add_event(event_address: Address)
// Link definition ( calendar -> event )
// get calendar function
// add event
// subscribe to calendar (create link)
|
// Copyright 2018 Jeffery Xiao, 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! An implmentation of a Counted Skiplist, optimized for solving Traveling Salesman Problems.
//!
//! This is the Skiplist equivalent of a [Counted B-Tree](http://msinfo.info/msi/cdsisis/basico/countedb-trees.htm)
//!
//! The code is based on the [extended-collections-rs](https://github.com/jeffrey-xiao/extended-collections-rs) skiplist implementation
//!
//! Like a Skiplist, it provides O(1) previous/next lookup, and O(Log N) average case insertion,
//! deletion, lookup by index, splitting and joining. On top of these basic operations, the *counted*
//! skiplist also has a value associated with every element, and provides O(Log N) functions for
//! calculating the sum of those values between any two endpoints.
//!
//! This implementation actually allows the value associated with each element to depend on the
//! element to its right (this comes from the TSP use case, where the element is a city, and the
//! derived value is the distance to the next city.) This implementation is designed to work
//! even with noncommutative "sums" (i.e. it will work with any [Group](https://en.wikipedia.org/wiki/Group_(mathematics))
//!
//! This implementation also supports custom allocators.
#![warn(missing_docs)]
#![feature(allocator_api, alloc_layout_extra, fn_traits, unboxed_closures)]
extern crate alga;
#[macro_use]
extern crate alga_derive;
extern crate num_traits;
pub mod group_util;
use alga::general::{AdditiveGroup};
use rand::Rng;
use rand::XorShiftRng;
use std::alloc::{Alloc, Global, Layout};
use std::fmt::Debug;
use std::fmt::Error;
use std::fmt::Formatter;
use std::mem;
use std::ops::{Add, Index, IndexMut};
use std::ptr;
type DefaultGroup = i32;
#[repr(C)]
#[derive(Copy, Clone)]
struct Layer<T, S: AdditiveGroup + Copy = DefaultGroup> {
sum: S,
next: *mut Node<T, S>,
next_distance: usize,
prev: *mut Node<T, S>,
}
#[repr(C)]
struct Node<T, S: AdditiveGroup + Copy = DefaultGroup> {
links_len: usize,
value: T,
links: [Layer<T, S>; 0],
}
/// A Pointer to an element of a CountedSkipList,
/// invalidated iff that element is removed.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Finger<T, S: AdditiveGroup + Copy = DefaultGroup>(*mut Node<T, S>);
const MAX_HEIGHT: usize = 32;
impl<T, S: AdditiveGroup + Copy> Node<T, S> {
pub fn new(value: T, links_len: usize, alloc: &mut Alloc) -> *mut Self {
let ptr = unsafe { Self::allocate(links_len, alloc) };
unsafe {
ptr::write(&mut (*ptr).value, value);
}
ptr
}
pub fn get_pointer(&self, height: usize) -> &Layer<T, S> {
unsafe { self.links.get_unchecked(height) }
}
pub fn get_pointer_mut(&mut self, height: usize) -> &mut Layer<T, S> {
unsafe { self.links.get_unchecked_mut(height) }
}
fn layout(links_len: usize) -> Layout {
Layout::new::<Self>()
.extend(Layout::array::<Layer<T, S>>(2 * links_len).unwrap())
.unwrap()
.0
}
unsafe fn allocate(links_len: usize, alloc: &mut Alloc) -> *mut Self {
let ptr: *mut Node<T, S> = alloc
.alloc_zeroed(Self::layout(links_len))
.unwrap()
.cast()
.as_ptr();
ptr::write(&mut (*ptr).links_len, links_len);
// We populate the sum with 0 by default.
for height in 0..links_len {
ptr::write(&mut (*ptr).get_pointer_mut(height).sum, S::identity());
}
ptr
}
unsafe fn deallocate(ptr: *mut Self, alloc: &mut Alloc) {
alloc.dealloc(
std::ptr::NonNull::new_unchecked(ptr).cast(),
Self::layout((*ptr).links_len),
);
}
unsafe fn free(ptr: *mut Self, alloc: &mut Alloc) {
for i in 0..(*ptr).links_len {
ptr::drop_in_place(&mut (*ptr).get_pointer_mut(i).sum);
}
ptr::drop_in_place(&mut (*ptr).value);
Self::deallocate(ptr, alloc);
}
unsafe fn extract_value(ptr: *mut Self, alloc: &mut Alloc) -> T {
for i in 0..(*ptr).links_len {
ptr::drop_in_place(&mut (*ptr).get_pointer_mut(i).sum);
}
let value = mem::replace(&mut (*ptr).value, std::mem::uninitialized());
Self::deallocate(ptr, alloc);
value
}
}
unsafe fn link<T, S: AdditiveGroup + Copy>(
first: *mut Node<T, S>,
second: *mut Node<T, S>,
height: usize,
distance: usize,
) {
let mut first_link = (*first).get_pointer_mut(height);
first_link.next = second;
first_link.next_distance = distance;
if !second.is_null() {
let mut second_link = (*second).get_pointer_mut(height);
second_link.prev = first;
}
}
unsafe fn swap_link<T, S: AdditiveGroup + Copy>(
first: *mut Node<T, S>,
second: *mut Node<T, S>,
height: usize,
) {
let first_link = (*first).get_pointer_mut(height);
let second_link = (*second).get_pointer_mut(height);
let first_next = first_link.next;
let first_distance = first_link.next_distance;
let second_next = second_link.next;
let second_distance = second_link.next_distance;
link(first, second_next, height, second_distance);
link(second, first_next, height, first_distance);
}
/// A Counted SkipList
///
/// A skiplist is a probabilistic data structure that allows for binary search tree operations by
/// maintaining a linked hierarchy of subsequences. The first subsequence is essentially a sorted
/// linked list of all the elements that it contains. Each successive subsequence contains
/// approximately half the elements of the previous subsequence. Using the sparser subsequences,
/// elements can be skipped and searching, insertion, and deletion of keys can be done in
/// approximately logarithm time.
///
/// Each link in this skiplist store the width of the link. The width is defined as the number of
/// bottom layer links being traversed by each of the higher layer links. This augmentation allows
/// the list to get, remove, and insert at an arbitrary index in `O(log N)` time.
///
/// Additionally the *counted* skip list has a value associated with every element, and provides
/// `O(Log N)` time lookup of the sums of those values across any given range. This implementation
/// supports associated values which can be derived from an element and it's right-neighbor,
/// and supports summing any values with a `Group` structure (i.e. they have a 0 element, can be
/// added together (not neccessarily commutatively), and have an inverse).
///
///
/// # Examples
///
/// ```
/// use counted_skiplist::CountedSkipList;
///
/// let mut list = CountedSkipList::new();
/// list.insert(0, 1);
/// list.push_back(2);
/// list.push_front(3);
///
/// assert_eq!(list.get(0), Some(&3));
/// assert_eq!(list.get(3), None);
/// assert_eq!(list.len(), 3);
///
/// *list.get_mut(0).unwrap() += 1;
/// assert_eq!(list.pop_front(), 4);
/// assert_eq!(list.pop_back(), 2);
/// ```
pub struct CountedSkipList<
T,
S: AdditiveGroup + Copy = DefaultGroup,
F: Fn(&T, &T) -> S + Copy = group_util::DefaultExtractor<S>,
A: Alloc = Global,
> {
head: *mut Node<T, S>,
len: usize,
rng: XorShiftRng,
key_func: F,
alloc: A,
}
impl<T> CountedSkipList<T, DefaultGroup, group_util::DefaultExtractor<DefaultGroup>, Global> {
/// Constructs a new, empty `CountedSkipList<T,S>` in the default allocator.
///
/// # Examples
///
/// ```
/// use counted_skiplist::CountedSkipList;
///
/// let list: CountedSkipList<u32, i32, _> = CountedSkipList::new_with_group(|&x, &_y| x as i32);
/// ```
pub fn new() -> Self {
Self::new_with_group(group_util::DefaultExtractor::<DefaultGroup>::new())
}
}
impl<T, S: AdditiveGroup + Copy, F: Fn(&T, &T) -> S + Copy> CountedSkipList<T, S, F, Global> {
/// Constructs a new, empty `CountedSkipList<T,S>` in the default allocator.
///
///
/// # Examples
///
/// ```
/// use counted_skiplist::CountedSkipList;
///
/// let list: CountedSkipList<u32> = CountedSkipList::new();
/// ```
pub fn new_with_group(key_func: F) -> Self {
Self::new_with_group_in(key_func, Global {})
}
}
impl<T, S: AdditiveGroup + Copy, F: Fn(&T, &T) -> S + Copy, A: Alloc> CountedSkipList<T, S, F, A> {
/// Constructs a new, empty `CountedSkipList<T,S>` in a given allocator.
///
/// # Examples
///
/// ```
/// use counted_skiplist::CountedSkipList;
///
/// let alloc = std::alloc::System {};
/// let mut list = CountedSkipList::new_with_group_in(|&a, &b| 0, alloc);
/// list.push_back(5);
/// ```
pub fn new_with_group_in(key_func: F, mut alloc: A) -> Self {
CountedSkipList {
head: unsafe { Node::allocate(MAX_HEIGHT + 1, &mut alloc) },
len: 0,
rng: XorShiftRng::new_unseeded(),
key_func,
alloc,
}
}
fn gen_random_height(&mut self) -> usize {
self.rng.next_u32().leading_zeros() as usize
}
fn build_prev_nodes_cache(
&self,
mut index: usize,
) -> [(*mut Node<T, S>, usize, S); MAX_HEIGHT + 1] {
assert!(index <= self.len);
let mut curr_node = self.head;
let mut last_nodes = [(self.head, 0, S::identity()); MAX_HEIGHT + 1];
unsafe {
for height in (0..=MAX_HEIGHT).rev() {
let mut next_link = (*curr_node).get_pointer_mut(height);
while !next_link.next.is_null() && next_link.next_distance < index {
last_nodes[height].1 += next_link.next_distance;
last_nodes[height].2 += next_link.sum;
index -= next_link.next_distance;
curr_node = next_link.next;
next_link = (*curr_node).get_pointer_mut(height);
}
last_nodes[height].0 = curr_node;
}
}
last_nodes
}
/// Inserts a value into the list at a particular index, shifting elements one position to the
/// right if needed.
///
/// # Examples
///
/// ```
/// use counted_skiplist::CountedSkipList;
///
/// let mut list = CountedSkipList::new();
/// list.insert(0, 1);
/// list.insert(0, 2);
/// assert_eq!(list.get(0), Some(&2));
/// assert_eq!(list.get(1), Some(&1));
/// ```
pub fn insert(&mut self, index: usize, value: T) -> Finger<T, S> {
assert!(index <= self.len);
self.len += 1;
let new_height = self.gen_random_height();
let new_node = Node::new(value, new_height + 1, &mut self.alloc);
let mut last_nodes = self.build_prev_nodes_cache(index);
unsafe {
for height in 0..=new_height {
let last_node = last_nodes[height].0;
let last_node_link = (*last_node).get_pointer_mut(height);
link(
&mut *new_node,
&mut *last_node_link.next,
height,
1, // Good default since it will work for layer 0.
);
link(
&mut *last_node,
&mut *new_node,
height,
last_node_link.next_distance,
);
}
// Since key_fun looks at two nodes, when we insert a node, we need to
// recalculate its value for both the inserted node, and the node previous to it.
// In this section we calculate those values, and set the sums correctly for the layer 0
// of the list. We also update the last_nodes datastructures to include the updated
// values of the previous-to-inserted node.
let new_node_count = {
let base_layer = (*new_node).get_pointer_mut(0);
// TODO: This hack says if you insert at the last position, just treat it as if
// you had a second copy of the same value for computing the key_func.
let next_val = base_layer
.next
.as_ref()
.map_or(&(*new_node).value, |n| &n.value);
let new_node_count = (self.key_func)(&(*new_node).value, next_val);
base_layer.sum = new_node_count;
// If we are inserting at the first position, we can skip this.
if base_layer.prev != self.head {
let prev_base_layer = (*base_layer.prev).get_pointer_mut(0);
let prev_node_count =
(self.key_func)(&(*base_layer.prev).value, &(*new_node).value);
base_layer.sum = new_node_count;
prev_base_layer.sum = prev_node_count;
last_nodes[0].1 += 1;
last_nodes[0].2 += prev_node_count;
}
new_node_count
};
for i in 1..=MAX_HEIGHT {
last_nodes[i].1 += last_nodes[i - 1].1;
last_nodes[i].2 += last_nodes[i - 1].2;
let right_distance =
1 + (*last_nodes[i].0).get_pointer(i).next_distance - last_nodes[i - 1].1;
// Note that order matters here, since the group is not necessarily commutative.
let right_nodes = new_node_count
+ (last_nodes[i - 1].2).inverse()
+ (*last_nodes[i].0).get_pointer(i).sum;
let last_node_link = (*last_nodes[i].0).get_pointer_mut(i);
if i <= new_height {
let new_node_link = (*new_node).get_pointer_mut(i);
last_node_link.next_distance = last_nodes[i - 1].1;
last_node_link.sum = last_nodes[i - 1].2;
new_node_link.next_distance = right_distance;
new_node_link.sum = right_nodes;
} else {
last_node_link.next_distance += 1;
last_node_link.sum = last_nodes[i - 1].2 + right_nodes;
}
}
Finger(new_node)
}
}
/// Removes a value at a particular index from the list. Returns the value at the index.
///
/// # Examples
///
/// ```
/// use counted_skiplist::CountedSkipList;
///
/// let mut list = CountedSkipList::new();
/// list.insert(0, 1);
/// assert_eq!(list.remove(0), 1);
/// ```
pub fn remove(&mut self, index: usize) -> T {
assert!(index < self.len);
let mut last_nodes = self.build_prev_nodes_cache(index);
unsafe {
let node_to_remove = (*last_nodes[0].0).get_pointer_mut(0).next;
let following_node = (*node_to_remove).get_pointer(0).next;
let value_removed = (*node_to_remove).get_pointer(0).sum;
let left_value_removed = (*last_nodes[0].0).get_pointer_mut(0).sum;
// Since the key_func looks at two nodes, we have to recompute the
// value for the previous node.
let left_value_added = if last_nodes[0].0 != self.head {
let next_val = following_node
.as_ref()
.map_or(&(*last_nodes[0].0).value, |n| &n.value);
(self.key_func)(&(*last_nodes[0].0).value, next_val)
} else {
S::identity()
};
let next_distance = if last_nodes[0].0 != self.head { 1 } else { 0 };
link(last_nodes[0].0, following_node, 0, next_distance);
for i in 1..=MAX_HEIGHT {
last_nodes[i].1 += last_nodes[i - 1].1;
last_nodes[i].2 += last_nodes[i - 1].2;
let last_node_link = (*last_nodes[i].0).get_pointer_mut(i);
let removed_node_link = (*node_to_remove).get_pointer_mut(i);
if i < (*node_to_remove).links_len {
let distance = last_nodes[i - 1].1
+ next_distance
+ (*node_to_remove).get_pointer(i).next_distance
- 1;
last_node_link.sum = last_nodes[i - 1].2
+ left_value_added
+ value_removed.inverse()
+ (*node_to_remove).get_pointer(i).sum;
link(last_nodes[i].0, removed_node_link.next, i, distance);
} else {
last_node_link.next_distance -= 1;
// Note that order matters here, since the group is not necessarily commutative.
last_node_link.sum = last_nodes[i - 1].2
+ left_value_added
+ (last_nodes[i - 1].2 + left_value_removed + value_removed).inverse()
+ last_node_link.sum;
}
}
self.len -= 1;
// Frees the node
Node::extract_value(node_to_remove, &mut self.alloc)
}
}
/// Splits a list at a given node with the default allocator
pub unsafe fn split_at_finger(&mut self, finger: Finger<T, S>) -> CountedSkipList<T, S, F> {
self.split_at_finger_in(finger, Global {})
}
/// Splits a list at a given Node with a given allocator
///
/// The node must be an element of this skiplist.
pub unsafe fn split_at_finger_in<B: Alloc>(
&mut self,
finger: Finger<T, S>,
alloc: B,
) -> CountedSkipList<T, S, F, B> {
let mut curr_node = finger.0;
let mut newlist = CountedSkipList::<T, S, F, B>::new_with_group_in(self.key_func, alloc);
let mut distance_from_end = 1;
let mut sum_from_end = (self.key_func)(&(*curr_node).value, &(*curr_node).value);
for height in 0..=MAX_HEIGHT {
let (parent, distance, sum) = self.parent_at_height(curr_node, height);
curr_node = parent;
distance_from_end += distance;
sum_from_end = sum + sum_from_end;
// Split current level, order of link() calls and .sum assignments important here.
let curr_link = (*curr_node).get_pointer_mut(height);
link(
newlist.head,
curr_link.next,
height,
curr_link.next_distance - distance_from_end,
);
(*newlist.head).get_pointer_mut(height).sum = sum_from_end.inverse() + curr_link.sum;
link(curr_node, std::ptr::null_mut(), height, distance_from_end);
(*curr_node).get_pointer_mut(height).sum = sum_from_end;
}
while curr_node != self.head {
curr_node = (*curr_node).get_pointer_mut(MAX_HEIGHT).prev;
distance_from_end += (*curr_node).get_pointer_mut(MAX_HEIGHT).next_distance;
}
newlist.len = self.len - distance_from_end;
self.len = distance_from_end;
newlist
}
/// Inserts a value at the front of the list.
///
/// # Examples
///
/// ```
/// use counted_skiplist::CountedSkipList;
///
/// let mut list = CountedSkipList::new();
/// list.push_front(1);
/// list.push_front(2);
/// assert_eq!(list.get(0), Some(&2));
/// ```
pub fn push_front(&mut self, value: T) -> Finger<T,S> {
self.insert(0, value)
}
/// Inserts a value at the back of the list.
///
/// # Examples
///
/// ```
/// use counted_skiplist::CountedSkipList;
///
/// let mut list = CountedSkipList::new();
/// list.push_back(1);
/// list.push_back(2);
/// assert_eq!(list.get(0), Some(&1));
/// ```
pub fn push_back(&mut self, value: T) -> Finger<T,S> {
let index = self.len();
self.insert(index, value)
}
/// Removes a value at the front of the list.
///
/// # Panics
///
/// Panics if list is empty.
///
/// # Examples
///
/// ```
/// use counted_skiplist::CountedSkipList;
///
/// let mut list = CountedSkipList::new();
/// list.push_back(1);
/// list.push_back(2);
/// assert_eq!(list.pop_front(), 1);
/// ```
pub fn pop_front(&mut self) -> T {
self.remove(0)
}
/// Removes a value at the back of the list.
///
/// # Panics
///
/// Panics if list is empty.
///
/// # Examples
///
/// ```
/// use counted_skiplist::CountedSkipList;
///
/// let mut list = CountedSkipList::new();
/// list.push_back(1);
/// list.push_back(2);
/// assert_eq!(list.pop_back(), 2);
/// ```
pub fn pop_back(&mut self) -> T {
let index = self.len() - 1;
self.remove(index)
}
/// Returns a mutable reference to the value at a particular index. Returns `None` if the
/// index is out of bounds.
///
/// # Examples
///
/// ```
/// use counted_skiplist::CountedSkipList;
///
/// let mut list = CountedSkipList::new();
/// list.insert(0, 1);
/// *list.get_mut(0).unwrap() = 2;
/// assert_eq!(list.get(0), Some(&2));
/// ```
pub fn get(&self, index: usize) -> Option<&T> {
unsafe { self.get_finger(index).map(|n| &(*n.0).value) }
}
/// Returns a mutable reference to the value at a particular index. Returns `None` if the
/// index is out of bounds.
///
/// # Examples
///
/// ```
/// use counted_skiplist::CountedSkipList;
///
/// let mut list = CountedSkipList::new();
/// list.insert(0, 1);
/// *list.get_mut(0).unwrap() = 2;
/// assert_eq!(list.get(0), Some(&2));
/// ```
pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
unsafe { self.get_finger(index).map(|n| &mut (*n.0).value) }
}
/// Returns a finger reference to the node at a particular index. Returns `None` if the
/// index is out of bounds.
///
/// # Examples
///
/// ```
/// use counted_skiplist::CountedSkipList;
///
/// let mut list = CountedSkipList::new();
/// let finger = list.insert(0, 1);
/// assert_eq!(list.get_finger(0), Some(finger));
/// ```
pub fn get_finger(&self, mut index: usize) -> Option<Finger<T, S>> {
let mut curr_height = MAX_HEIGHT;
let mut curr_node = self.head;
unsafe {
loop {
let mut next_link = (*curr_node).get_pointer(curr_height);
while !next_link.next.is_null() && next_link.next_distance <= index {
index -= next_link.next_distance;
let next_next_link = (*next_link.next).get_pointer(curr_height);
curr_node = mem::replace(&mut next_link, next_next_link).next;
if index == 0 {
return Some(Finger(curr_node));
}
}
if curr_height == 0 {
return None;
}
curr_height -= 1;
}
}
}
/// Finds the first node to the left of a given node that
/// has a height greater than or equal to the given height,
/// summing up the total distance and sum traversed.
///
/// If the node is already at the given height, it will just
/// return the given node.
unsafe fn parent_at_height(
&self,
node: *mut Node<T, S>,
height: usize,
) -> (*mut Node<T, S>, usize, S) {
assert!(height <= MAX_HEIGHT);
let mut curr_node = node;
let mut distance_traversed = 0;
let mut sum_traversed = S::identity();
if node.is_null() {
return (node, distance_traversed, sum_traversed);
}
while (*curr_node).links_len <= height {
curr_node = (*curr_node).get_pointer(height - 1).prev;
let curr_link = (*curr_node).get_pointer(height - 1);
distance_traversed += curr_link.next_distance;
sum_traversed = curr_link.sum + sum_traversed;
}
(curr_node, distance_traversed, sum_traversed)
}
/// Finds the first node to the right of a given node that
/// has a height greater than or equal to the given height,
/// summing up the total distance and sum traversed.
///
/// If the node is already at the given height, it will just
/// return the given node.
#[allow(dead_code)]
unsafe fn right_parent_at_height(
&self,
node: *mut Node<T, S>,
height: usize,
) -> (*mut Node<T, S>, usize, S) {
assert!(height <= MAX_HEIGHT);
let mut curr_node = node;
let mut distance_traversed = 0;
let mut sum_traversed = S::identity();
while !curr_node.is_null() && (*curr_node).links_len <= height {
let curr_link = (*curr_node).get_pointer(height - 1);
curr_node = curr_link.prev;
distance_traversed += curr_link.next_distance;
sum_traversed = curr_link.sum + sum_traversed;
}
(curr_node, distance_traversed, sum_traversed)
}
/// Finds the first node to the left of a given node that
/// has a greater height, summing up the total distance and
/// sum traversed.
#[allow(dead_code)]
unsafe fn parent(&self, node: *mut Node<T, S>) -> (*mut Node<T, S>, usize, S) {
self.parent_at_height(node, (*node).links_len)
}
/// Finds the first node to the left of a given node that
/// has a greater height, summing up the total distance and
/// sum traversed.
#[allow(dead_code)]
unsafe fn right_parent(&self, node: *mut Node<T, S>) -> (*mut Node<T, S>, usize, S) {
self.parent_at_height(node, (*node).links_len)
}
/// Returns the distance and sum between two fingers.
///
/// i.e. the sum on the half open interval [a,b).
/// It will return a negative sum if b is before a
/// in the list.
///
/// Undefined behavior if a or b is not a part of
/// this list.
pub unsafe fn finger_difference(&self, a: Finger<T, S>, b: Finger<T, S>) -> (i64, S) {
// The algorithm we use is we walk left from a and b until we reach
// a node at the next height, repeating up to MAX_HEIGHT, or the nodes
// coincide. If the nodes coincide, then we can tell whether a is
// before or after b based on the number of steps taken at the previous
// level. If we reach MAX_HEIGHT without meeting, we just do a linear
// search at the MAX_HEIGHt level.
let mut curr_a = a.0;
let mut curr_b = b.0;
let mut a_distance: i64 = 0;
let mut b_distance: i64 = 0;
let mut a_sum = S::identity();
let mut b_sum = S::identity();
if curr_a == curr_b {
return (0, S::identity());
}
for height in 1..=MAX_HEIGHT {
let (new_a, a_distance_step, a_sum_step) = self.parent_at_height(curr_a, height);
let (new_b, b_distance_step, b_sum_step) = self.parent_at_height(curr_b, height);
curr_a = new_a;
curr_b = new_b;
a_distance += a_distance_step as i64;
b_distance += b_distance_step as i64;
a_sum = a_sum_step + a_sum;
b_sum = b_sum_step + b_sum;
if curr_a == curr_b {
return (b_distance - a_distance, a_sum.inverse() + b_sum);
}
}
// If we reach here, we have got to the top level, without finding a
// common parent. We will search to the right starting at node a
// and if that fails, we will search to the right starting at node b.
// We store the state once we reached the top, in case our search from
// node a fails.
let (top_a, top_a_distance, top_a_sum) = (curr_a, a_distance, a_sum);
loop {
if curr_a.is_null() {
break;
} else if curr_a == curr_b {
return (b_distance - a_distance, a_sum.inverse() + b_sum);
}
let link = (*curr_a).get_pointer(MAX_HEIGHT);
curr_a = link.next;
a_distance -= link.next_distance as i64;
a_sum = link.sum.inverse() + a_sum;
}
// If we reach here, then that means a is to the right of b, so
// we now search right from b.
loop {
if curr_b.is_null() {
break;
} else if top_a == curr_b {
return (b_distance - top_a_distance, top_a_sum.inverse() + b_sum);
}
let link = (*curr_b).get_pointer(MAX_HEIGHT);
curr_b = link.next;
b_distance -= link.next_distance as i64;
b_sum = link.sum.inverse() + b_sum;
}
panic!("Cannot take difference between a and b which are not from the same list.")
}
/// Returns the number of elements in the list.
///
/// # Examples
///
/// ```
/// use counted_skiplist::CountedSkipList;
///
/// let mut list = CountedSkipList::new();
/// list.insert(0, 1);
/// assert_eq!(list.len(), 1);
/// ```
pub fn len(&self) -> usize {
self.len
}
/// Returns `true` if the list is empty.
///
/// # Examples
///
/// ```
/// use counted_skiplist::CountedSkipList;
///
/// let list: CountedSkipList<u32> = CountedSkipList::new();
/// assert!(list.is_empty());
/// ```
pub fn is_empty(&self) -> bool {
self.len == 0
}
/// Clears the list, removing all values.
///
/// # Examples
///
/// ```
/// use counted_skiplist::CountedSkipList;
///
/// let mut list = CountedSkipList::new();
/// list.insert(0, 1);
/// list.insert(1, 2);
/// list.clear();
/// assert_eq!(list.is_empty(), true);
/// ```
pub fn clear(&mut self) {
self.len = 0;
unsafe {
let mut curr_node = (*self.head).get_pointer(0).next;
while !curr_node.is_null() {
let next_node = (*curr_node).get_pointer(0).next;
Node::free(mem::replace(&mut curr_node, next_node), &mut self.alloc);
}
for height in 0..=MAX_HEIGHT {
*(*self.head).links.get_unchecked_mut(height) = Layer {
sum: S::identity(),
next: std::ptr::null_mut(),
next_distance: 0,
prev: std::ptr::null_mut(),
}
}
}
}
/// Returns an iterator over the list.
///
/// # Examples
///
/// ```
/// use counted_skiplist::CountedSkipList;
///
/// let mut list = CountedSkipList::new();
/// list.insert(0, 1);
/// list.insert(1, 2);
///
/// let mut iterator = list.iter();
/// assert_eq!(iterator.next(), Some(&1));
/// assert_eq!(iterator.next(), Some(&2));
/// assert_eq!(iterator.next(), None);
/// ```
pub fn iter(&self) -> CountedSkipListIter<'_, T, S> {
unsafe {
CountedSkipListIter {
current: &(*self.head).get_pointer(0).next,
}
}
}
/// Returns a mutable iterator over the list.
///
/// # Examples
///
/// ```
/// use counted_skiplist::CountedSkipList;
///
/// let mut list = CountedSkipList::new();
/// list.insert(0, 1);
/// list.insert(1, 2);
///
/// for value in &mut list {
/// *value += 1;
/// }
///
/// let mut iterator = list.iter();
/// assert_eq!(iterator.next(), Some(&2));
/// assert_eq!(iterator.next(), Some(&3));
/// assert_eq!(iterator.next(), None);
/// ```
pub fn iter_mut(&mut self) -> CountedSkipListIterMut<'_, T, S> {
unsafe {
CountedSkipListIterMut {
current: &mut (*self.head).get_pointer_mut(0).next,
}
}
}
}
impl<T, S: AdditiveGroup + Copy, F: Fn(&T, &T) -> S + Copy, A: Alloc> Drop for CountedSkipList<T, S, F, A> {
fn drop(&mut self) {
unsafe {
let next_node = (*self.head).get_pointer(0).next;
Node::free(mem::replace(&mut self.head, next_node), &mut self.alloc);
while !self.head.is_null() {
let next_node = (*self.head).get_pointer(0).next;
Node::free(mem::replace(&mut self.head, next_node), &mut self.alloc);
}
}
}
}
impl<T, S: AdditiveGroup + Copy, F: Fn(&T, &T) -> S + Copy, A: Alloc + Default> IntoIterator
for CountedSkipList<T, S, F, A>
{
type IntoIter = CountedSkipListIntoIter<T, S, A>;
type Item = T;
fn into_iter(mut self) -> Self::IntoIter {
unsafe {
let alloc = std::mem::replace(&mut self.alloc, A::default());
let ret = Self::IntoIter {
current: (*self.head).links.get_unchecked_mut(0).next,
alloc,
};
ptr::write_bytes((*self.head).links.get_unchecked_mut(0), 0, MAX_HEIGHT + 1);
ret
}
}
}
impl<'a, T, S: AdditiveGroup + Copy, F: Fn(&T, &T) -> S + Copy, A: Alloc> IntoIterator
for &'a CountedSkipList<T, S, F, A>
where
T: 'a,
{
type IntoIter = CountedSkipListIter<'a, T, S>;
type Item = &'a T;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl<'a, T, S: AdditiveGroup + Copy, F: Fn(&T, &T) -> S + Copy, A: Alloc> IntoIterator
for &'a mut CountedSkipList<T, S, F, A>
where
T: 'a,
{
type IntoIter = CountedSkipListIterMut<'a, T, S>;
type Item = &'a mut T;
fn into_iter(self) -> Self::IntoIter {
self.iter_mut()
}
}
/// An owning iterator for `CountedSkipList<T,S>`.
///
/// This iterator traverses the elements of the list and yields owned entries.
pub struct CountedSkipListIntoIter<T, S: AdditiveGroup + Copy, A: Alloc> {
current: *mut Node<T, S>,
alloc: A,
}
impl<T, S: AdditiveGroup + Copy, A: Alloc> Iterator for CountedSkipListIntoIter<T, S, A> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
if self.current.is_null() {
None
} else {
unsafe {
let ret = ptr::read(&(*self.current).value);
let next_node = (*self.current).get_pointer(0).next;
Node::deallocate(mem::replace(&mut self.current, next_node), &mut self.alloc);
Some(ret)
}
}
}
}
impl<T, S: AdditiveGroup + Copy, A: Alloc> Drop for CountedSkipListIntoIter<T, S, A> {
fn drop(&mut self) {
unsafe {
while !self.current.is_null() {
ptr::drop_in_place(&mut (*self.current).value);
let next_node = (*self.current).get_pointer(0).next;
Node::deallocate(mem::replace(&mut self.current, next_node), &mut self.alloc);
}
}
}
}
/// An iterator for `CountedSkipList<T,S>`.
///
/// This iterator traverses the elements of the list in-order and yields immutable references.
pub struct CountedSkipListIter<'a, T, S: AdditiveGroup + Copy> {
current: &'a *mut Node<T, S>,
}
impl<'a, T, S: AdditiveGroup + Copy> Iterator for CountedSkipListIter<'a, T, S>
where
T: 'a,
{
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if self.current.is_null() {
None
} else {
unsafe {
let ret = &(**self.current).value;
let next_node = &(**self.current).get_pointer(0).next;
mem::replace(&mut self.current, next_node);
Some(ret)
}
}
}
}
/// A mutable iterator for `CountedSkipList<T,S>`.
///
/// This iterator traverses the elements of the list in-order and yields mutable references.
pub struct CountedSkipListIterMut<'a, T, S: AdditiveGroup + Copy> {
current: &'a mut *mut Node<T, S>,
}
impl<'a, T, S: AdditiveGroup + Copy> Iterator for CountedSkipListIterMut<'a, T, S>
where
T: 'a,
{
type Item = &'a mut T;
fn next(&mut self) -> Option<Self::Item> {
if self.current.is_null() {
None
} else {
unsafe {
let ret = &mut (**self.current).value;
let next_node = &mut (**self.current).get_pointer_mut(0).next;
mem::replace(&mut self.current, next_node);
Some(ret)
}
}
}
}
impl<T> Default for CountedSkipList<T> {
fn default() -> Self {
Self::new()
}
}
impl<T, S: AdditiveGroup + Copy, F: Fn(&T, &T) -> S + Copy, A: Alloc> Add for CountedSkipList<T, S, F, A> {
type Output = CountedSkipList<T, S, F, A>;
fn add(mut self, other: CountedSkipList<T, S, F, A>) -> CountedSkipList<T, S, F, A> {
self.len += other.len();
let mut curr_nodes = [self.head; MAX_HEIGHT + 1];
unsafe {
let mut curr_height = MAX_HEIGHT;
let mut curr_node = self.head;
while !curr_node.is_null() {
while (*curr_node).get_pointer(curr_height).next.is_null() {
curr_nodes[curr_height] = curr_node;
if curr_height == 0 {
break;
}
curr_height -= 1;
}
curr_node = (*curr_node).get_pointer(curr_height).next;
}
for (i, curr_node) in curr_nodes.iter_mut().enumerate().take(MAX_HEIGHT + 1) {
let other_link = (*other.head).get_pointer_mut(i);
let distance =
(**curr_node).get_pointer_mut(i).next_distance + other_link.next_distance;
let sum = (**curr_node).get_pointer_mut(i).sum + other_link.sum;
swap_link(*curr_node, other.head, i);
(**curr_node).get_pointer_mut(i).next_distance = distance;
(**curr_node).get_pointer_mut(i).sum = sum;
}
}
self
}
}
impl<T, S: AdditiveGroup + Copy, F: Fn(&T, &T) -> S + Copy, A: Alloc> Index<usize>
for CountedSkipList<T, S, F, A>
{
type Output = T;
fn index(&self, index: usize) -> &Self::Output {
self.get(index).expect("Error: index out of bounds.")
}
}
impl<T, S: AdditiveGroup + Copy, F: Fn(&T, &T) -> S + Copy, A: Alloc> IndexMut<usize>
for CountedSkipList<T, S, F, A>
{
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
self.get_mut(index).expect("Error: index out of bounds.")
}
}
#[derive(Debug)]
struct LinkRep<'a, T: Debug, S: Debug> {
prev: Option<&'a T>,
next: Option<&'a T>,
next_distance: usize,
sum: S,
}
impl<T: Debug + Clone + Default, S: AdditiveGroup + Copy + Debug, F: Fn(&T, &T) -> S + Copy, A: Alloc> Debug
for CountedSkipList<T, S, F, A>
{
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
unsafe {
let mut curr_node = (*self.head).get_pointer(0).next;
let mut actual = vec![];
while !curr_node.is_null() {
actual.push(&(*curr_node).value);
let next_link = (*curr_node).get_pointer(0);
curr_node = next_link.next;
}
curr_node = (*self.head).get_pointer(0).next;
writeln!(f, "[")?;
while !curr_node.is_null() {
let links =
std::slice::from_raw_parts((*curr_node).get_pointer(0), (*curr_node).links_len);
let links_rep: Vec<_> = links
.iter()
.map(|l| {
LinkRep {
prev: l.prev.as_ref().map(|n| &n.value),
next: l.next.as_ref().map(|n| &n.value),
next_distance: l.next_distance,
sum: l.sum,
}
})
.collect();
let mut builder = f.debug_struct("Node");
let _ = builder.field("value", &(*curr_node).value);
let _ = builder.field("links", &links_rep);
builder.finish()?;
writeln!(f, ",")?;
let next_link = (*curr_node).get_pointer(0);
curr_node = next_link.next;
}
writeln!(f, "]")?;
}
Ok(())
}
}
/// Checks the internal validity of a CountedSkipList.
pub fn check_valid<T, S: AdditiveGroup + Copy, F: Fn(&T, &T) -> S + Copy, A: Alloc>(
list: &CountedSkipList<T, S, F, A>,
) where
T: PartialEq + Debug + Clone + Default,
S: Debug
{
//println!("check_valid()");
//println!("{:#?}", list);
unsafe {
let mut length = 0;
let mut expected_distances : Vec<usize> = (0..=MAX_HEIGHT).map(|i| (*list.head).get_pointer(i).next_distance).collect();
let mut expected_sums : Vec<S> = (0..=MAX_HEIGHT).map(|i| (*list.head).get_pointer(i).sum).collect();
let mut distances = [0; MAX_HEIGHT+1];
let mut sums = [S::identity(); MAX_HEIGHT+1];
assert_eq!((*list.head).get_pointer(0).next_distance, 0);
let mut curr_node = (*list.head).get_pointer(0).next;
while !curr_node.is_null() {
let next_node = (*curr_node).get_pointer(0).next;
let next_value = &next_node.as_ref().unwrap_or(&*curr_node).value;
let sum = (list.key_func)(&(*curr_node).value, next_value);
let height = (*curr_node).links_len;
for i in 0..height {
let skip_node = (*curr_node).get_pointer(i).next;
if !skip_node.is_null() {
assert_eq!((*skip_node).get_pointer(i).prev, curr_node);
}
assert_eq!(distances[i], expected_distances[i]);
assert_eq!(sums[i], expected_sums[i]);
let link = (*curr_node).get_pointer(i);
expected_distances[i] = link.next_distance;
expected_sums[i] = link.sum;
distances[i] = 1;
sums[i] = sum;
}
for i in height..=MAX_HEIGHT {
distances[i] += 1;
sums[i] += sum;
}
length +=1;
curr_node = next_node;
}
for i in 0..=MAX_HEIGHT {
assert_eq!(distances[i], expected_distances[i]);
assert_eq!(sums[i], expected_sums[i]);
}
assert_eq!(list.len, length);
}
}
#[test]
fn test_len_empty() {
let list: CountedSkipList<u32> = CountedSkipList::new();
assert_eq!(list.len(), 0);
}
#[test]
fn test_is_empty() {
let list: CountedSkipList<u32> = CountedSkipList::new();
check_valid(&list);
assert!(list.is_empty());
}
#[test]
fn test_insert() {
let mut list: CountedSkipList<u32> = CountedSkipList::new();
check_valid(&list);
list.insert(0, 1);
check_valid(&list);
assert_eq!(list.get(0), Some(&1));
}
#[test]
fn test_insert_order() {
let mut list: CountedSkipList<u32> = CountedSkipList::new();
list.insert(0, 1);
list.insert(0, 2);
list.insert(0, 3);
check_valid(&list);
assert_eq!(list.iter().collect::<Vec<&u32>>(), vec![&3, &2, &1],);
}
#[test]
fn test_insert_order2() {
let mut list: CountedSkipList<u32> = CountedSkipList::new();
list.insert(0, 1);
list.insert(0, 2);
check_valid(&list);
assert_eq!(list.iter().collect::<Vec<&u32>>(), vec![&2, &1],);
}
#[test]
fn test_insert_order3() {
let mut list: CountedSkipList<u32> = CountedSkipList::new();
list.insert(0, 1);
list.insert(0, 2);
list.insert(1, 3);
check_valid(&list);
assert_eq!(list.iter().collect::<Vec<&u32>>(), vec![&2, &3, &1],);
}
#[test]
fn test_remove() {
let mut list: CountedSkipList<u32> = CountedSkipList::new();
list.insert(0, 1);
let ret = list.remove(0);
check_valid(&list);
assert_eq!(list.get(0), None);
assert_eq!(ret, 1);
}
#[test]
fn test_remove_two() {
let mut list: CountedSkipList<u32> = CountedSkipList::new();
list.insert(0, 1);
list.insert(0, 2);
let ret = list.remove(1);
check_valid(&list);
assert_eq!(list.get(0), Some(&2));
assert_eq!(ret, 1);
}
#[test]
fn test_remove_fuzzed() {
let mut list: CountedSkipList<u32> = CountedSkipList::new();
list.insert(0, 1);
list.insert(0, 2);
check_valid(&list);
let ret = list.remove(1);
check_valid(&list);
assert_eq!(ret, 1);
}
#[test]
fn test_remove_fuzzed2() {
let mut list: CountedSkipList<u32> = CountedSkipList::new();
list.insert(0, 1);
list.insert(0, 2);
list.insert(2, 3);
list.insert(0, 5);
check_valid(&list);
let ret = list.remove(0);
check_valid(&list);
assert_eq!(ret, 5);
}
#[test]
fn test_get_mut() {
let mut list: CountedSkipList<u32> = CountedSkipList::new();
list.insert(0, 1);
{
let value = list.get_mut(0);
*value.unwrap() = 3;
}
assert_eq!(list.get(0), Some(&3));
}
#[test]
fn test_push_front() {
let mut list: CountedSkipList<u32> = CountedSkipList::new();
list.insert(0, 1);
list.push_front(2);
check_valid(&list);
assert_eq!(list.get(0), Some(&2));
}
#[test]
fn test_push_back() {
let mut list: CountedSkipList<u32> = CountedSkipList::new();
list.insert(0, 1);
list.push_back(2);
check_valid(&list);
assert_eq!(list.get(1), Some(&2));
}
#[test]
fn test_pop_front() {
let mut list: CountedSkipList<u32> = CountedSkipList::new();
list.insert(0, 1);
list.insert(1, 2);
check_valid(&list);
assert_eq!(list.pop_front(), 1);
}
#[test]
fn test_pop_back() {
let mut list: CountedSkipList<u32> = CountedSkipList::new();
list.insert(0, 1);
list.insert(1, 2);
assert_eq!(list.pop_back(), 2);
}
#[test]
fn test_add() {
let mut n: CountedSkipList<u32> = CountedSkipList::new();
n.insert(0, 1);
n.insert(0, 2);
n.insert(1, 3);
let mut m: CountedSkipList<u32> = CountedSkipList::new();
m.insert(0, 4);
m.insert(0, 5);
m.insert(1, 6);
check_valid(&n);
check_valid(&m);
let res = n + m;
check_valid(&res);
assert_eq!(
res.iter().collect::<Vec<&u32>>(),
vec![&2, &3, &1, &5, &6, &4],
);
assert_eq!(res.len(), 6);
}
#[test]
fn test_split_at_finger() {
let mut l: CountedSkipList<u32> = CountedSkipList::new();
l.insert(0, 1);
l.insert(0, 2);
let finger = l.insert(0, 3);
l.insert(0, 4);
check_valid(&l);
let m = unsafe { l.split_at_finger(finger) };
check_valid(&m);
check_valid(&l);
}
#[test]
fn test_add_fuzzed() {
let mut n: CountedSkipList<u32> = CountedSkipList::new();
n.insert(0, 1);
n.insert(0, 2);
let mut m: CountedSkipList<u32> = CountedSkipList::new();
m.insert(0, 4);
m.insert(0, 5);
m.remove(1);
check_valid(&n);
check_valid(&m);
let res = m + n;
check_valid(&res);
assert_eq!(res.iter().collect::<Vec<&u32>>(), vec![&5, &2, &1],);
assert_eq!(res.len(), 3);
}
#[test]
fn test_split_fuzzed() {
let mut m: CountedSkipList<u32> = CountedSkipList::new();
let finger = m.insert(0, 1);
let n = unsafe { m.split_at_finger(finger) };
check_valid(&n);
m.insert(0, 2);
check_valid(&m);
let res = m + n;
check_valid(&res);
}
#[test]
fn test_split_fuzzed2() {
let mut m: CountedSkipList<u32> = CountedSkipList::new();
m.insert(0, 1);
let finger = m.insert(0, 2);
let n = unsafe { m.split_at_finger(finger) };
check_valid(&m);
check_valid(&n);
let res = m + n;
check_valid(&res);
}
#[test]
fn test_split_fuzzed3() {
let mut m: CountedSkipList<u32> = CountedSkipList::new();
m.insert(0, 1);
m.insert(0, 2);
m.insert(0, 3);
let finger = m.insert(2, 4);
check_valid(&m);
let mut n = unsafe { m.split_at_finger(finger) };
check_valid(&n);
n.insert(1, 5);
check_valid(&n);
}
#[test]
fn test_finger_difference() {
let mut m = CountedSkipList::new_with_group(|&x, &_y| x as i32);
m.insert(0, 1);
let finger1 = m.insert(1, 2);
m.insert(2, 3);
let finger2 = m.insert(3, 4);
let (distance, _) = unsafe { m.finger_difference(finger1, finger2) };
let (rev_distance, _) = unsafe { m.finger_difference(finger2, finger1) };
assert_eq!(distance, 2);
assert_eq!(rev_distance, -2);
}
#[test]
fn test_subsum() {
let mut list = CountedSkipList::new_with_group(|&x, &_y| x as i32);
list.push_back(1);
let finger1 = list.push_back(2);
list.push_back(3);
list.push_back(4);
let finger2 =list.push_back(5);
list.push_back(6);
let (_distance, sum) = unsafe { list.finger_difference(finger1, finger2) };
assert_eq!(sum, 2+3+4);
}
#[test]
fn test_subsum_backwards() {
let mut m = CountedSkipList::new_with_group(|&x, &_y| x as i32);
let finger1 = m.insert(0, 1);
let finger2 = m.insert(1, 2);
check_valid(&m);
let (distance, sum) = unsafe { m.finger_difference(finger2, finger1) };
assert_eq!(distance, -1);
assert_eq!(sum, -1);
}
#[test]
fn test_into_iter() {
let mut list: CountedSkipList<u32> = CountedSkipList::new();
list.insert(0, 1);
list.insert(0, 2);
list.insert(1, 3);
check_valid(&list);
assert_eq!(list.into_iter().collect::<Vec<u32>>(), vec![2, 3, 1]);
}
#[test]
fn test_iter() {
let mut list: CountedSkipList<u32> = CountedSkipList::new();
list.insert(0, 1);
list.insert(0, 2);
list.insert(1, 3);
check_valid(&list);
assert_eq!(list.iter().collect::<Vec<&u32>>(), vec![&2, &3, &1]);
}
#[test]
fn test_iter_mut() {
let mut list: CountedSkipList<u32> = CountedSkipList::new();
list.insert(0, 1);
list.insert(0, 2);
list.insert(1, 3);
for value in &mut list {
*value += 1;
}
check_valid(&list);
assert_eq!(list.iter().collect::<Vec<&u32>>(), vec![&3, &4, &2]);
} |
use std::fs;
use cbc_mode;
fn main() {
let key = "YELLOW SUBMARINE";
let iv = "\x00\x00\x00";
let encypted_text = fs::read_to_string("encrypted_data.txt").expect("Unable to read file");
let decrypted_text = cbc_mode::decrypt_string(
&encypted_text,
key,
iv
);
println!("Decrypted_text: {:?}", decrypted_text);
} |
#[test]
fn test_fd_sync() {
assert_wasi_output!(
"../../wasitests/fd_sync.wasm",
"fd_sync",
vec![],
vec![(
".".to_string(),
::std::path::PathBuf::from("wasitests/test_fs/temp")
),],
vec![],
"../../wasitests/fd_sync.out"
);
}
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under both the MIT license found in the
* LICENSE-MIT file in the root directory of this source tree and the Apache
* License, Version 2.0 found in the LICENSE-APACHE file in the root directory
* of this source tree.
*/
use futures::{Async, Future, Poll, Stream};
use std::default::Default;
use std::mem;
/// Stream returned as a result of calling [crate::StreamExt::collect_to]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct CollectTo<S, C> {
stream: S,
collection: C,
}
impl<S: Stream, C> CollectTo<S, C>
where
C: Default + Extend<S::Item>,
{
fn finish(&mut self) -> C {
mem::take(&mut self.collection)
}
/// Create a new instance of [CollectTo] wrapping the provided stream
pub fn new(stream: S) -> CollectTo<S, C> {
CollectTo {
stream,
collection: Default::default(),
}
}
}
impl<S, C> Future for CollectTo<S, C>
where
S: Stream,
C: Default + Extend<S::Item>,
{
type Item = C;
type Error = S::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
loop {
match self.stream.poll() {
Ok(Async::Ready(Some(v))) => self.collection.extend(Some(v)),
Ok(Async::Ready(None)) => return Ok(Async::Ready(self.finish())),
Ok(Async::NotReady) => return Ok(Async::NotReady),
Err(e) => {
self.finish();
return Err(e);
}
}
}
}
}
|
use serde_repr::Deserialize_repr;
#[derive(Debug, Deserialize_repr)]
#[repr(u8)]
pub enum Composite {
Above = 1,
Below = 2,
}
impl Default for Composite {
fn default() -> Self {
Self::Above
}
}
|
use std::fs;
#[derive(Debug)]
pub struct Cartridge {
data: Vec<u8>,
gbcFlag: u8,
cartType: CartridgeType,
ramType: RamType,
romSize: u8,
ram: Option<Vec<u8>>,
}
#[derive(Debug)]
enum CartridgeType {
Rom = 0x00,
Mbc1 = 0x01,
Mbc1Ram = 0x02,
Mbc1RamBattery = 0x03,
}
#[derive(Debug)]
enum RamType {
NoRam = 0x00,
Unused = 0x01,
Kb8 = 0x02,
Kb32 = 0x03,
Kb128 = 0x04,
Kb64 = 0x05
}
impl Cartridge {
pub fn new(path: String) -> Self {
let d = fs::read(path).unwrap();
let gbcF = d[0x0143];
let t = match d[0x0147] {
0x00 => CartridgeType::Rom,
0x01 => CartridgeType::Mbc1,
0x02 => CartridgeType::Mbc1Ram,
0x03 => CartridgeType::Mbc1RamBattery,
_ => panic!("Unsupported cartridge type")
};
let (ram, rT) = match d[0x0149] {
0x00 => (None, RamType::NoRam),
0x01 => (None, RamType::Unused),
0x02 => (Some(Vec::with_capacity(8192)), RamType::Kb8),
0x03 => (Some(Vec::with_capacity(8192 * 4)), RamType::Kb32),
0x04 => (Some(Vec::with_capacity(8192 * 16)), RamType::Kb128),
0x05 => (Some(Vec::with_capacity(8192 * 8)), RamType::Kb64),
_ => panic!("Unreachable"),
};
let rSize = d[0x0148];
Self {
data: d,
gbcFlag: gbcF,
cartType: t,
ramType: rT,
romSize: rSize,
ram: ram
}
}
pub fn readRom(&self, addr: u16) -> u8 {
match self.cartType {
CartridgeType::Rom => {self.data[addr as usize]},
_ => panic!("Mappers not implemented")
}
}
pub fn readRam(&self, addr: u16) -> u8 {
match self.cartType {
CartridgeType::Rom => {0},
_ => panic!("Mappers not implemented")
}
}
pub fn writeRam(&mut self, addr: u16, d: u8) {
todo!("Not implemented")
}
}
/*
$00 ROM ONLY
$01 MBC1
$02 MBC1+RAM
$03 MBC1+RAM+BATTERY
$05 MBC2
$06 MBC2+BATTERY
$08 ROM+RAM *
$09 ROM+RAM+BATTERY *
$0B MMM01
$0C MMM01+RAM
$0D MMM01+RAM+BATTERY
$0F MBC3+TIMER+BATTERY
$10 MBC3+TIMER+RAM+BATTERY
$11 MBC3
$12 MBC3+RAM
$13 MBC3+RAM+BATTERY
$19 MBC5
$1A MBC5+RAM
$1B MBC5+RAM+BATTERY
$1C MBC5+RUMBLE
$1D MBC5+RUMBLE+RAM
$1E MBC5+RUMBLE+RAM+BATTERY
$20 MBC6
$22 MBC7+SENSOR+RUMBLE+RAM+BATTERY
$FC POCKET CAMERA
$FD BANDAI TAMA5
$FE HuC3
$FF
*/
/*
$00 0 No RAM *
$01 - Unused **
$02 8 KB 1 bank
$03 32 KB 4 banks of 8 KB each
$04 128 KB 16 banks of 8 KB each
$05 64 KB 8 banks of 8 KB each
*/
/*
$00 32 KByte 2 (No ROM banking)
$01 64 KByte 4
$02 128 KByte 8
$03 256 KByte 16
$04 512 KByte 32
$05 1 MByte 64
$06 2 MByte 128
$07 4 MByte 256
$08 8 MByte 512
*/ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.