text stringlengths 8 4.13M |
|---|
use std::{path::PathBuf};
use bevy::{
// math::vec2,
prelude::*,
render::{
mesh::Indices,
pipeline::DynamicBinding,
pipeline::PipelineDescriptor,
pipeline::PipelineSpecialization,
pipeline::RenderPipeline,
render_graph::base,
render_graph::AssetRenderResourcesNode,
render_graph::RenderGraph,
renderer::RenderResources,
shader::{self, ShaderDefs},
},
};
use shader::{ShaderStage, ShaderStages};
use crate::sky_sphere::SkySphere;
const SKYBOX_PIPELINE_HANDLE: Handle<PipelineDescriptor> =
Handle::from_u128(189483623150127713895864825450987265104);
#[derive(Debug, Clone)]
pub struct SkyboxPlugin {
pub size: f32,
pub basecolor: Color,
pub texture: Option<PathBuf>,
}
impl Default for SkyboxPlugin {
fn default() -> Self {
SkyboxPlugin {
size: 50000.,
basecolor: Color::BLACK,
texture: None,
}
}
}
#[derive(Default)]
struct SkyboxResource {
pub plugin: SkyboxPlugin,
pub mesh_handle: Option<Handle<Mesh>>,
pub material_handle: Option<Handle<SkyboxMaterial>>,
}
#[derive(RenderResources, ShaderDefs)]
pub struct SkyboxMaterial {
pub basecolor: Color,
#[shader_def]
pub texture: Option<Handle<Texture>>,
}
impl Plugin for SkyboxPlugin {
fn build(&self, app: &mut bevy::prelude::AppBuilder) {
app.add_resource(SkyboxResource {
plugin: self.clone(),
..Default::default()
})
.add_asset::<SkyboxMaterial>()
.add_system_to_stage(
stage::POST_UPDATE,
bevy::render::shader::asset_shader_defs_system::<SkyboxMaterial>.system(),
)
.add_startup_system(skybox_startup.system());
}
}
fn skybox_startup(
mut commands: Commands,
mut skybox: ResMut<SkyboxResource>,
mut pipelines: ResMut<Assets<PipelineDescriptor>>,
mut shaders: ResMut<Assets<Shader>>,
mut render_graph: ResMut<RenderGraph>,
mut meshes: ResMut<Assets<Mesh>>,
mut sky_materials: ResMut<Assets<SkyboxMaterial>>,
asset_server: Res<AssetServer>,
) {
pipelines.set(
SKYBOX_PIPELINE_HANDLE,
PipelineDescriptor::default_config(ShaderStages {
vertex: shaders.add(Shader::from_glsl(
ShaderStage::Vertex,
include_str!("../shaders/vert_shader.vert"),
)),
fragment: Some(shaders.add(Shader::from_glsl(
ShaderStage::Fragment,
include_str!("../shaders/frag_shader.frag"),
))),
}),
);
render_graph.add_system_node(
"skybox_material",
AssetRenderResourcesNode::<SkyboxMaterial>::new(true),
);
render_graph
.add_node_edge("skybox_material", base::node::MAIN_PASS)
.unwrap();
let sky_specialized_pipeline =
RenderPipelines::from_pipelines(vec![RenderPipeline::specialized(
SKYBOX_PIPELINE_HANDLE,
PipelineSpecialization {
dynamic_bindings: vec![
// Transform
DynamicBinding {
bind_group: 2,
binding: 0,
},
// SkyboxMaterial_basecolor
DynamicBinding {
bind_group: 3,
binding: 0,
},
],
..Default::default()
},
)]);
let s = skybox.plugin.size;
let skymesh = Mesh::from(SkySphere {
radius: s,
subdivisions: 50,
});
// let outputfile = &mut File::create(&Path::new(&format!("skybox.txt"))).unwrap();
// outputfile.write_all(format!("{:#?}", skymesh).as_bytes()).expect("else");
// skymesh.indices = reverse_triangles(skymesh.indices);
skybox.mesh_handle = Some(meshes.add(skymesh));
// skybox.mesh_handle = Some(meshes.add(Mesh::from(shape::Quad {
// size: vec2(skybox.plugin.size, skybox.plugin.size),
// flip: false,
// })));
if let Some(path) = skybox.plugin.texture.clone() {
let texture_handle = asset_server.load(path).unwrap();
skybox.material_handle = Some(sky_materials.add(SkyboxMaterial {
basecolor: skybox.plugin.basecolor,
texture: Some(texture_handle),
}));
} else {
skybox.material_handle = Some(sky_materials.add(SkyboxMaterial {
basecolor: skybox.plugin.basecolor,
texture: None,
}));
}
commands
.spawn(MeshComponents {
mesh: skybox.mesh_handle.unwrap(),
draw: Draw {
is_transparent: true,
..Default::default()
},
render_pipelines: sky_specialized_pipeline,
..Default::default()
})
.with(skybox.material_handle.unwrap());
}
pub fn reverse_triangles(indices: Option<Indices>) -> Option<Indices> {
if let Some(i) = indices {
match i {
Indices::U16(_) => None,
Indices::U32(ind) => {
let mut reversed = Vec::new();
for triangle in ind.rchunks_exact(3) {
reversed.push(triangle[2]);
reversed.push(triangle[1]);
reversed.push(triangle[0]);
}
Some(Indices::U32(reversed))
}
}
} else {
None
}
}
|
#[path = "../lib/intcode.rs"]
mod intcode;
use anyhow::Context;
use intcode::{IntCodeComputer, MemoryValue};
use itertools::Itertools;
use std::io::BufRead;
const INPUT: &str = include_str!("input.txt");
fn run(memory: &mut [MemoryValue]) -> anyhow::Result<()> {
let stdin = std::io::stdin();
let mut istream = stdin.lock();
let mut buffer = String::with_capacity(64);
let mut computer = IntCodeComputer::new(
memory,
|| match istream.read_line(&mut buffer)? {
0 => Ok(None),
_ => Ok(Some(buffer.trim().parse()?)),
},
|value| {
println!("{}", value);
Ok(())
},
);
computer.run()?;
Ok(())
}
fn part1(memory: &mut [MemoryValue]) -> anyhow::Result<MemoryValue> {
memory[1] = 12;
memory[2] = 2;
run(memory)?;
Ok(memory[0])
}
fn part2(source: &mut [MemoryValue]) -> anyhow::Result<MemoryValue> {
let mut memory = vec![0; source.len()];
let result = (0..100)
.cartesian_product(0..100)
.find(|&(noun, verb)| {
memory.copy_from_slice(&source);
memory[1] = noun;
memory[2] = verb;
run(&mut memory).is_ok() && memory[0] == 19690720
})
.map(|(noun, verb)| 100 * noun + verb)
.context("no valid pairs")?;
Ok(result)
}
fn main() -> anyhow::Result<()> {
let mut memory: Vec<MemoryValue> = INPUT
.trim_end()
.split(',')
.map(|s| s.parse())
.collect::<Result<_, _>>()?;
println!("part 1: {}", part1(&mut memory.clone())?);
println!("part 2: {}", part2(&mut memory)?);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let mut memory: Vec<MemoryValue> = INPUT
.trim_end()
.split(',')
.map(|s| s.parse())
.collect::<Result<_, _>>()
.unwrap();
assert_eq!(part1(&mut memory.clone()).unwrap(), 3895705);
assert_eq!(part2(&mut memory).unwrap(), 6417);
}
}
|
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::fmt;
use serde::{Deserialize, Serialize};
use super::fmt::FmtGuard;
use super::variable::{Keywords, Value};
pub type Outs = BTreeMap<String, Out>;
#[derive(Clone, PartialEq, Serialize, Deserialize)]
pub struct OutDim {
pub out: Out,
pub dim: usize,
}
impl From<OutDim> for Value {
fn from(value: OutDim) -> Self {
Self::Dim(value)
}
}
impl fmt::Debug for OutDim {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}[{}]", &self.out, self.dim)
}
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Out {
pub id: Option<u64>,
pub name: String,
}
impl Out {
pub fn with_name(name: String) -> Self {
Self { id: None, name }
}
pub fn new(id: u64, name: String) -> Self {
Self { id: Some(id), name }
}
}
impl fmt::Debug for Out {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", &self.name)?;
write!(f, "$")?;
if let Some(id) = &self.id {
write!(f, "{}", id)?;
}
Ok(())
}
}
#[derive(Clone, PartialEq)]
pub struct Shape(pub Vec<Value>);
impl Shape {
pub fn sum(&self) -> Value {
self.0.iter().sum()
}
pub fn product(&self) -> Value {
self.0.iter().product()
}
}
impl fmt::Debug for Shape {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for dim in &self.0 {
write!(f, "{:?}, ", dim)?;
}
Ok(())
}
}
#[derive(Clone, PartialEq)]
pub struct Shapes(pub RefCell<ShapesInner>);
type ShapesInner = BTreeMap<String, Option<Shape>>;
impl Shapes {
pub fn new(shapes: ShapesInner) -> Self {
Self(RefCell::new(shapes))
}
pub fn to_outs(&self, id: u64) -> Outs {
self.0
.borrow()
.keys()
.map(|n| (n.clone(), Out::new(id, n.clone())))
.collect()
}
}
crate::impl_debug_no_guard!(Shapes);
impl<'a> fmt::Debug for FmtGuard<'a, Shapes> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let borrowed = self.0.borrow();
if borrowed.len() == 1 {
if let Some(Some(shape)) = borrowed.get("x") {
return writeln!(f, " = {:?}", shape);
}
}
let indent = self.indent();
writeln!(f, ":")?;
for (name, shape) in borrowed.iter() {
write!(f, "{}{}", &indent, name)?;
match shape {
Some(shape) => writeln!(f, " = {:?}", shape)?,
None => writeln!(f)?,
}
writeln!(f)?;
}
Ok(())
}
}
#[derive(Clone)]
pub enum GraphInputs {
Dict(Outs),
List(Vec<Out>),
}
impl Default for GraphInputs {
fn default() -> Self {
Self::Dict(Outs::default())
}
}
impl GraphInputs {
pub fn ty(&self) -> GraphInputsType {
match self {
Self::Dict(_) => GraphInputsType::Dict,
Self::List(_) => GraphInputsType::List,
}
}
pub fn unwrap_dict(self) -> Option<Outs> {
match self {
Self::Dict(outs) => Some(outs),
_ => None,
}
}
pub fn unwrap_list(self) -> Option<Vec<Out>> {
match self {
Self::List(outs) => Some(outs),
_ => None,
}
}
}
impl fmt::Debug for GraphInputs {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Dict(dict) => {
write!(f, "{{")?;
for (k, x) in dict {
write!(f, "{}={:?}, ", k, x)?;
}
write!(f, "}}")
}
Self::List(list) => {
write!(f, "[")?;
for x in list {
write!(f, "{:?}, ", x)?;
}
write!(f, "]")
}
}
}
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum GraphInputsType {
UseLast,
Dict,
List,
}
#[derive(Clone)]
pub struct GraphCall {
pub name: String,
pub inputs: Option<GraphInputs>,
pub args: Option<Keywords>,
pub repeat: Option<Value>,
}
impl GraphCall {
pub fn get_inputs_ty(&self) -> GraphInputsType {
match &self.inputs {
Some(inputs) => inputs.ty(),
None => GraphInputsType::UseLast,
}
}
}
impl fmt::Debug for GraphCall {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", &self.name)?;
if let Some(inputs) = &self.inputs {
inputs.fmt(f)?;
}
if let Some(args) = &self.args {
write!(f, "(")?;
for (name, value) in args {
write!(f, "{}={:?}, ", name, value)?;
}
write!(f, ")")?;
}
if let Some(repeat) = &self.repeat {
write!(f, " * {:?}", repeat)?;
}
Ok(())
}
}
#[derive(Clone)]
pub struct GraphNode {
pub id: u64,
pub calls: Vec<GraphCall>,
pub shapes: Option<Shapes>,
}
crate::impl_debug_no_guard!(GraphNode);
impl<'a> fmt::Debug for FmtGuard<'a, GraphNode> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let indent = self.indent();
write!(f, "{}{}. ", &indent, self.id)?;
for value in &self.calls {
write!(f, "{:?} + ", value)?;
}
if let Some(shapes) = &self.shapes {
self.child(shapes).fmt(f)
} else {
writeln!(f)
}
}
}
|
#![allow(dead_code)]
#[derive(Default)]
pub struct Triangle {
pub v: [glm::Vec3; 3],
pub color: [glm::Vec3; 3],
pub tex_coords: [glm::Vec3; 3],
pub normal: [glm::Vec3; 3],
pub position: [glm::Vec3; 3],
pub perp_pos: [glm::Vec4; 3],
}
impl Triangle {
pub fn new() -> Triangle{
Triangle{
..Default::default()
}
}
pub fn a(&self) -> glm::Vec3 {
self.v[0]
}
pub fn b(&self) -> glm::Vec3 {
self.v[1]
}
pub fn c(&self) -> glm::Vec3 {
self.v[2]
}
pub fn set_vertex(&mut self, ind: usize, v: &glm::Vec3) {
assert!(ind < 3);
self.v[ind] = v.clone();
}
pub fn set_normal(&mut self, ind: usize, n: &glm::Vec3) {
assert!(ind < 3);
self.normal[ind] = n.clone();
}
pub fn set_tex_coord(&mut self, ind: usize, s: f32, t: f32) {
assert!(ind < 3);
self.tex_coords[ind] = glm::vec3(s, t, 1.0);
}
pub fn set_color(&mut self, ind: usize, r: f32, g: f32, b: f32) {
assert!(ind < 3);
self.color[ind] = glm::vec3(r, g, b);
}
pub fn set_position(&mut self, ind: usize, p: &glm::Vec3) {
assert!(ind < 3);
self.position[ind] = p.clone();
}
pub fn set_perp_pos(&mut self, ind:usize, p: &glm::Vec4) {
assert!(ind < 4);
self.perp_pos[ind] = p.clone();
}
pub fn to_vector4(&self) -> [glm::Vec4; 3] {
let mut v3 = [glm::vec4(0f32, 0f32, 0f32, 0f32); 3];
for ind in 0..3 {
v3[ind].x = self.v[ind].x;
v3[ind].y = self.v[ind].y;
v3[ind].z = self.v[ind].z;
v3[ind].w = 1f32;
}
v3
}
}
|
#[allow(unused_imports)]
use proconio::{marker::*, *};
#[allow(unused_imports)]
use std::{cmp::Ordering, convert::TryInto};
#[fastout]
fn main() {
input! {
n: i32,
s: String,
// s: Chars,
}
}
pub trait CumlativeSum {
/// 累積和を取る
/// 返り値の先頭要素は番兵の 0 である。
fn cumlative_sum(&self) -> Self;
/// in-place に累積和を取る
fn cumlative_sum_in_place(&mut self) -> &Self;
}
impl CumlativeSum for Vec<i32> {
fn cumlative_sum(&self) -> Self {
let mut s = vec![0; self.len() + 1];
for (i, v) in self.iter().enumerate() {
s[i + 1] = s[i] + v;
}
s
}
fn cumlative_sum_in_place(&mut self) -> &Self {
let mut prev = *self.get(0).unwrap();
for v in self.iter_mut().skip(1) {
*v += prev;
prev = *v;
}
self
}
}
impl CumlativeSum for Vec<Vec<i32>> {
fn cumlative_sum(&self) -> Self {
let h = self.len() as usize;
let w = self.get(0).unwrap().len() as usize;
let mut s = Vec::with_capacity(h + 1);
s.push(vec![0; w + 1]);
// 横方向合計
for xs in self.iter() {
s.push(xs.cumlative_sum());
}
// 縦方向合計
for c in 1..=w {
for r in 1..=h {
s[r][c] += s[r - 1][c];
}
}
s
}
fn cumlative_sum_in_place(&mut self) -> &Self {
let h = self.len() as usize;
let w = self.get(0).unwrap().len() as usize;
// 横方向合計
for xs in self.iter_mut() {
xs.cumlative_sum_in_place();
}
// 縦方向合計
for c in 0..w {
for r in 1..h {
self[r][c] += self[r - 1][c];
}
}
self
}
}
|
use gl::types::*;
use std::ffi::CString;
use std::fs::File;
use std::io::Read;
use std::ptr;
use std::str;
#[allow(non_snake_case)]
pub struct Shader {
pub ID: u32,
}
#[allow(non_snake_case)]
impl Shader {
pub fn new(vertex_path: &str, fragment_path: &str) -> Self {
let mut shader = Self { ID: 0 };
let mut vshader_file =
File::open(vertex_path).unwrap_or_else(|_| panic!("Failed to open {}", vertex_path));
let mut fshader_file = File::open(fragment_path)
.unwrap_or_else(|_| panic!("Failed to open {}", fragment_path));
let mut vertex_code = String::new();
let mut fragment_code = String::new();
vshader_file
.read_to_string(&mut vertex_code)
.expect("Failed to read vertex shader");
fshader_file
.read_to_string(&mut fragment_code)
.expect("Failed to read fragment shader");
let vshader_code = CString::new(vertex_code.as_bytes()).unwrap();
let fshader_code = CString::new(fragment_code.as_bytes()).unwrap();
unsafe {
let mut success = gl::FALSE as GLint;
let mut info_log = Vec::with_capacity(512);
let vertex = gl::CreateShader(gl::VERTEX_SHADER);
gl::ShaderSource(vertex, 1, &vshader_code.as_ptr(), ptr::null());
gl::CompileShader(vertex);
gl::GetShaderiv(vertex, gl::COMPILE_STATUS, &mut success);
if success != gl::TRUE as GLint {
gl::GetShaderInfoLog(
vertex,
512,
ptr::null_mut(),
info_log.as_mut_ptr() as *mut GLchar,
);
println!(
"ERROR::SHADER::VERTEX::COMPILATION_FAILED\n{}",
str::from_utf8(&info_log).unwrap(),
);
};
let fragment = gl::CreateShader(gl::FRAGMENT_SHADER);
gl::ShaderSource(fragment, 1, &fshader_code.as_ptr(), ptr::null());
gl::CompileShader(fragment);
gl::GetShaderiv(fragment, gl::COMPILE_STATUS, &mut success);
if success != gl::TRUE as GLint {
gl::GetShaderInfoLog(
fragment,
512,
ptr::null_mut(),
info_log.as_mut_ptr() as *mut GLchar,
);
println!(
"ERROR::SHADER::VERTEX::COMPILATION_FAILED\n{}",
str::from_utf8(&info_log).unwrap()
);
};
shader.ID = gl::CreateProgram();
gl::AttachShader(shader.ID, vertex);
gl::AttachShader(shader.ID, fragment);
gl::LinkProgram(shader.ID);
gl::GetProgramiv(shader.ID, gl::LINK_STATUS, &mut success);
if success != gl::TRUE as GLint {
gl::GetProgramInfoLog(
shader.ID,
512,
ptr::null_mut(),
info_log.as_mut_ptr() as *mut GLchar,
);
println!(
"ERROR::SHADER::PROGRAM::LINKING_FAILED\n{}",
str::from_utf8(&info_log).unwrap()
);
}
gl::DeleteShader(vertex);
gl::DeleteShader(fragment);
}
shader
}
pub unsafe fn useProgram(&self) {
gl::UseProgram(self.ID);
}
pub unsafe fn setInt(&self, name: &str, value: i32) {
let name = std::ffi::CString::new(name).unwrap();
gl::Uniform1i(gl::GetUniformLocation(self.ID, name.as_ptr()), value);
}
pub unsafe fn setFloat(&self, name: &str, value: f32) {
let name = std::ffi::CString::new(name).unwrap();
gl::Uniform1f(gl::GetUniformLocation(self.ID, name.as_ptr()), value);
}
}
|
//! # Transient Storage Adapters
//!
//! A collection of adapters on top of the substrate storage API.
//!
//! Currently implements a bounded priority queue in the `priority_queue` module.
//! Implements a ringbuffer queue in the `ringbuffer` module.
pub mod priority_queue;
pub mod bounded_deque;
pub use priority_queue::BoundedPriorityQueue;
pub use bounded_deque::BoundedDeque;
|
use serde::{Deserialize, Serialize};
use std::fmt;
#[derive(Clone, Debug, Deserialize, Serialize, Default, Eq, PartialEq, Ord, PartialOrd)]
pub struct PlayCount(pub i32);
impl PlayCount {
pub fn new(count: i32) -> PlayCount {
PlayCount(count)
}
}
impl fmt::Display for PlayCount {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl std::ops::Sub<PlayCount> for PlayCount {
type Output = PlayCount;
fn sub(self, rhs: PlayCount) -> PlayCount {
PlayCount::new(self.0 - rhs.0)
}
}
|
extern crate serde;
mod test_utils;
use flexi_logger::LoggerHandle;
use hdbconnect_async::{Connection, HdbResult};
use log::{debug, info};
// cargo test test_036_bool -- --nocapture
#[tokio::test]
async fn test_036_bool() -> HdbResult<()> {
let mut log_handle = test_utils::init_logger();
let start = std::time::Instant::now();
let mut connection = test_utils::get_authenticated_connection().await?;
test_text(&mut log_handle, &mut connection).await?;
test_utils::closing_info(connection, start).await
}
async fn test_text(
_logger_handle: &mut LoggerHandle,
connection: &mut Connection,
) -> HdbResult<()> {
info!("create a bool in the database, and read it");
debug!("setup...");
connection
.multiple_statements_ignore_err(vec!["drop table TEST_BOOL"])
.await;
let stmts = vec![
"create table TEST_BOOL ( \
ob0 BOOLEAN, ob1 BOOLEAN, ob2 BOOLEAN, b3 BOOLEAN NOT NULL, b4 BOOLEAN NOT NULL \
)",
];
connection.multiple_statements(stmts).await?;
let mut insert_stmt = connection
.prepare("insert into TEST_BOOL (ob0, ob1, ob2, b3, b4) values (?,?,?,?,?)")
.await?;
debug!("trying add batch");
let none: Option<bool> = None;
insert_stmt.add_batch(&(true, false, none, true, false))?;
debug!("trying execute_batch");
insert_stmt.execute_batch().await?;
debug!("trying query");
let resultset = connection.query("select * FROM TEST_BOOL").await?;
debug!("trying deserialize result set: {:?}", resultset);
let tuple: (Option<bool>, Option<bool>, Option<bool>, bool, bool) =
resultset.try_into().await?;
assert_eq!(Some(true), tuple.0);
assert_eq!(Some(false), tuple.1);
assert_eq!(None, tuple.2);
assert!(tuple.3);
assert!(!tuple.4);
Ok(())
}
|
use crate::ConnectParams;
use std::net::TcpStream;
#[derive(Debug)]
pub struct SyncPlainTcpClient {
params: ConnectParams,
reader: std::io::BufReader<TcpStream>,
writer: std::io::BufWriter<TcpStream>,
}
impl SyncPlainTcpClient {
// Returns an initialized plain tcp connection
pub fn try_new(params: ConnectParams) -> std::io::Result<Self> {
let tcpstream = TcpStream::connect(params.addr())?;
Ok(Self {
params,
writer: std::io::BufWriter::new(tcpstream.try_clone()?),
reader: std::io::BufReader::new(tcpstream),
})
}
pub fn connect_params(&self) -> &ConnectParams {
&self.params
}
pub fn writer(&mut self) -> &mut std::io::BufWriter<TcpStream> {
&mut self.writer
}
pub fn reader(&mut self) -> &mut std::io::BufReader<TcpStream> {
&mut self.reader
}
}
|
mod segment_tree;
pub use segment_tree::SegmentTree;
mod lazy_segment_tree;
pub use lazy_segment_tree::LazySegmentTree;
mod union_find_tree;
pub use union_find_tree::UnionFindTree;
mod vector_as_number_collection;
pub use vector_as_number_collection::VectorAsNumberCollection; |
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
crate::{
mod_manager::ModManager, story_context_store::StoryContextStore,
story_module::StoryModuleService,
},
failure::{Error, ResultExt},
fidl_fuchsia_app_discover::{DiscoverRegistryRequest, DiscoverRegistryRequestStream},
futures::prelude::*,
parking_lot::Mutex,
std::sync::Arc,
};
/// Handle DiscoveryRegistry requests.
pub async fn run_server(
story_context_store: Arc<Mutex<StoryContextStore>>,
mod_manager: Arc<Mutex<ModManager<StoryContextStore>>>,
mut stream: DiscoverRegistryRequestStream,
) -> Result<(), Error> {
while let Some(request) = stream.try_next().await.context("Error running discover registry")? {
match request {
DiscoverRegistryRequest::RegisterStoryModule { module, request, .. } => {
let story_module_stream = request.into_stream()?;
StoryModuleService::new(story_context_store.clone(), mod_manager.clone(), module)?
.spawn(story_module_stream);
}
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use {
super::*,
crate::{
story_context_store::{ContextEntity, ContextReader, Contributor},
testing::{init_state, FakeEntityData, FakeEntityResolver},
},
fidl_fuchsia_app_discover::{DiscoverRegistryMarker, ModuleIdentifier, StoryModuleMarker},
fidl_fuchsia_modular::{EntityResolverMarker, PuppetMasterMarker},
fuchsia_async as fasync,
maplit::hashset,
};
#[fasync::run_until_stalled(test)]
async fn test_register_story_module() -> Result<(), Error> {
// Initialize the fake entity resolver.
let (entity_resolver, request_stream) =
fidl::endpoints::create_proxy_and_stream::<EntityResolverMarker>().unwrap();
let mut fake_entity_resolver = FakeEntityResolver::new();
fake_entity_resolver
.register_entity("foo", FakeEntityData::new(vec!["some-type".into()], ""));
fake_entity_resolver.spawn(request_stream);
// Initialize service client and server.
let (client, request_stream) =
fidl::endpoints::create_proxy_and_stream::<DiscoverRegistryMarker>().unwrap();
let (puppet_master_client, _) =
fidl::endpoints::create_proxy_and_stream::<PuppetMasterMarker>().unwrap();
let (state, _, mod_manager) = init_state(puppet_master_client, entity_resolver);
let story_context = state.clone();
fasync::spawn_local(
async move { run_server(story_context, mod_manager, request_stream).await }
.unwrap_or_else(|e: Error| eprintln!("error running server {}", e)),
);
// Get the StoryModule connection.
let (story_module_proxy, server_end) =
fidl::endpoints::create_proxy::<StoryModuleMarker>()?;
let module = ModuleIdentifier {
story_id: Some("story1".to_string()),
module_path: Some(vec!["mod-a".to_string()]),
};
assert!(client.register_story_module(module, server_end).is_ok());
// Exercise the module output we got
assert!(story_module_proxy.write_output("param-foo", Some("foo")).await.is_ok());
// Verify state.
let expected_entity = ContextEntity::new_test(
"foo",
hashset!["some-type".to_string()],
hashset!(Contributor::module_new("story1", "mod-a", "param-foo")),
);
let context_store = state.lock();
let result = context_store.current().collect::<Vec<&ContextEntity>>();
assert_eq!(result.len(), 1);
assert_eq!(result[0], &expected_entity);
Ok(())
}
}
|
#![cfg(any(unix, target_os = "redox"))]
// FIXME: Remove once we test everything
#![allow(dead_code)]
/// SharedMimeInfo allows to look up the MIME type associated to a file name
/// or to the contents of a file, using the [Freedesktop.org Shared MIME
/// database specification][xdg-mime].
///
/// Alongside the MIME type, the Shared MIME database contains other ancillary
/// information, like the icon associated to the MIME type; the aliases for
/// a given MIME type; and the various sub-classes of a MIME type.
///
/// [xdg-mime]: https://specifications.freedesktop.org/shared-mime-info-spec/shared-mime-info-spec-latest.html
use std::env;
use std::path::{Path, PathBuf};
extern crate dirs;
#[macro_use]
extern crate nom;
mod alias;
mod glob;
mod icon;
mod magic;
mod parent;
/// Convenience identifier for an unknown MIME type.
pub static UNKNOWN_TYPE: &str = "application/octet-stream";
/// Convenience identifier for the MIME type for an empty file.
pub static EMPTY_TYPE: &str = "application/x-zerosize";
/// Convenience identifier for the MIME type for a plain text file.
pub static TEXT_PLAIN_TYPE: &str = "text/plain";
pub struct SharedMimeInfo {
aliases: alias::AliasesList,
parents: parent::ParentsMap,
icons: Vec<icon::Icon>,
generic_icons: Vec<icon::Icon>,
globs: glob::GlobMap,
magic: Vec<magic::MagicEntry>,
}
impl Default for SharedMimeInfo {
fn default() -> Self {
Self::new()
}
}
impl SharedMimeInfo {
fn create() -> SharedMimeInfo {
SharedMimeInfo {
aliases: alias::AliasesList::new(),
parents: parent::ParentsMap::new(),
icons: Vec::new(),
generic_icons: Vec::new(),
globs: glob::GlobMap::new(),
magic: Vec::new(),
}
}
fn load_directory<P: AsRef<Path>>(&mut self, directory: P) {
let mut mime_path = PathBuf::new();
mime_path.push(directory);
mime_path.push("mime");
let aliases = alias::read_aliases_from_dir(&mime_path);
self.aliases.add_aliases(aliases);
let icons = icon::read_icons_from_dir(&mime_path, false);
self.icons.extend(icons);
let generic_icons = icon::read_icons_from_dir(&mime_path, true);
self.generic_icons.extend(generic_icons);
let subclasses = parent::read_subclasses_from_dir(&mime_path);
self.parents.add_subclasses(subclasses);
let globs = glob::read_globs_from_dir(&mime_path);
self.globs.add_globs(globs);
let magic_entries = magic::read_magic_from_dir(&mime_path);
self.magic.extend(magic_entries);
}
/// Creates a new SharedMimeInfo database containing all MIME information
/// under the [XDG base directories][xdg-base-dir].
///
/// [xdg-base-dir]: http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
pub fn new() -> SharedMimeInfo {
let mut db = SharedMimeInfo::create();
let data_home = dirs::data_dir().expect("Data directory is unset");
db.load_directory(data_home);
let data_dirs = match env::var_os("XDG_DATA_DIRS") {
Some(v) => env::split_paths(&v).collect(),
None => vec![
PathBuf::from("/usr/local/share"),
PathBuf::from("/usr/share"),
],
};
for dir in data_dirs {
db.load_directory(dir)
}
db
}
/// Load all the MIME information under @directory, and create a new
/// SharedMimeInfo for it. This method is only really useful for
/// testing purposes; you should use SharedMimeInfo::new() instead.
pub fn new_for_directory<P: AsRef<Path>>(directory: P) -> SharedMimeInfo {
let mut db = SharedMimeInfo::create();
db.load_directory(directory);
db
}
/// Retrieves the MIME type aliased by a MIME type, if any.
pub fn unalias_mime_type(&self, mime_type: &str) -> Option<String> {
self.aliases.unalias_mime_type(mime_type)
}
/// Looks up the icons associated to a MIME type.
///
/// The icons can be looked up within the current icon theme.
pub fn lookup_icon_names(&self, mime_type: &str) -> Vec<String> {
let mut res = Vec::new();
if let Some(v) = icon::find_icon(&self.icons, &mime_type) {
res.push(v);
};
res.push(mime_type.replace("/", "-"));
match icon::find_icon(&self.generic_icons, mime_type) {
Some(v) => res.push(v),
None => {
let split_type = mime_type.split('/').collect::<Vec<&str>>();
let generic = format!("{}-x-generic", split_type.get(0).unwrap());
res.push(generic);
}
};
res
}
/// Looks up the generic icon associated to a MIME type.
///
/// The icon can be looked up within the current icon theme.
pub fn lookup_generic_icon_name(&self, mime_type: &str) -> Option<String> {
let res = match icon::find_icon(&self.generic_icons, mime_type) {
Some(v) => v,
None => {
let split_type = mime_type.split('/').collect::<Vec<&str>>();
format!("{}-x-generic", split_type.get(0).unwrap())
}
};
Some(res)
}
/// Looks up all the parent MIME types associated to @mime_type
pub fn get_parents(&self, mime_type: &str) -> Option<Vec<String>> {
let unaliased = match self.aliases.unalias_mime_type(mime_type) {
Some(v) => v,
None => return None,
};
let mut res = Vec::new();
res.push(unaliased.clone());
if let Some(parents) = self.parents.lookup(unaliased) {
for parent in parents {
res.push(parent.clone());
}
};
Some(res)
}
/// Retrieves the list of matching MIME types for the given file name,
/// without looking at the data inside the file.
pub fn get_mime_types_from_file_name(&self, file_name: &str) -> Vec<String> {
match self.globs.lookup_mime_type_for_file_name(file_name) {
Some(v) => v,
None => {
let mut res = Vec::new();
res.push(UNKNOWN_TYPE.to_string());
res
}
}
}
/// Retrieves the MIME type for the given data, and the priority of the
/// match. A priority above 80 means a certain match.
pub fn get_mime_type_for_data(&self, data: &[u8]) -> Option<(String, u32)> {
magic::lookup_data(&self.magic, data)
}
/// Checks whether two MIME types are equal, taking into account
/// eventual aliases.
pub fn mime_type_equal(&self, mime_a: &str, mime_b: &str) -> bool {
let unaliased_a = self
.unalias_mime_type(mime_a)
.unwrap_or_else(|| mime_a.to_string());
let unaliased_b = self
.unalias_mime_type(mime_b)
.unwrap_or_else(|| mime_b.to_string());
unaliased_a == unaliased_b
}
/// Checks whether a MIME type is a subclass of another MIME type
pub fn mime_type_subclass(&self, mime_type: &str, base: &str) -> bool {
let unaliased_mime = self
.unalias_mime_type(mime_type)
.unwrap_or_else(|| mime_type.to_string());
let unaliased_base = self
.unalias_mime_type(base)
.unwrap_or_else(|| base.to_string());
if unaliased_mime == unaliased_base {
return true;
}
// Handle super-types
if unaliased_base.ends_with("/*") {
let chunks = unaliased_base.split('/').collect::<Vec<&str>>();
if unaliased_mime.starts_with(chunks.get(0).unwrap()) {
return true;
}
}
// The text/plain and application/octet-stream require some
// special handling:
//
// - All text/* types are subclasses of text/plain.
// - All streamable types (ie, everything except the
// inode/* types) are subclasses of application/octet-stream
//
// https://specifications.freedesktop.org/shared-mime-info-spec/shared-mime-info-spec-latest.html#subclassing
if unaliased_base == "text/plain" && unaliased_mime.starts_with("text/") {
return true;
}
if unaliased_base == "application/octet-stream" && !unaliased_mime.starts_with("inode/") {
return true;
}
if let Some(parents) = self.parents.lookup(&unaliased_mime) {
for parent in parents {
if self.mime_type_subclass(parent, &unaliased_base) {
return true;
}
}
}
false
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::env;
fn load_test_data() -> SharedMimeInfo {
let cwd = env::current_dir().unwrap().to_string_lossy().into_owned();
let dir = PathBuf::from(&format!("{}/test_files", cwd));
SharedMimeInfo::new_for_directory(dir)
}
#[test]
fn load_from_directory() {
let cwd = env::current_dir().unwrap().to_string_lossy().into_owned();
let dir = PathBuf::from(&format!("{}/test_files", cwd));
SharedMimeInfo::new_for_directory(dir);
}
#[test]
fn load_system() {
let _db = SharedMimeInfo::new();
}
#[test]
fn load_default() {
let _db: SharedMimeInfo = Default::default();
}
#[test]
fn lookup_generic_icons() {
let mime_db = load_test_data();
assert_eq!(
mime_db.lookup_generic_icon_name("application/json"),
Some("text-x-script".to_string())
);
assert_eq!(
mime_db.lookup_generic_icon_name("text/plain"),
Some("text-x-generic".to_string())
);
}
#[test]
fn unalias() {
let mime_db = load_test_data();
assert_eq!(
mime_db.unalias_mime_type("application/ics"),
Some("text/calendar".to_string())
);
assert_eq!(mime_db.unalias_mime_type("text/plain"), None);
}
#[test]
fn mime_type_equal() {
let mime_db = load_test_data();
assert_eq!(
mime_db.mime_type_equal("application/wordperfect", "application/vnd.wordperfect"),
true
);
assert_eq!(
mime_db.mime_type_equal("application/x-gnome-app-info", "application/x-desktop"),
true
);
assert_eq!(
mime_db.mime_type_equal("application/x-wordperfect", "application/vnd.wordperfect"),
true
);
assert_eq!(
mime_db.mime_type_equal("application/x-wordperfect", "audio/x-midi"),
false
);
assert_eq!(mime_db.mime_type_equal("/", "vnd/vnd"), false);
assert_eq!(
mime_db.mime_type_equal("application/octet-stream", "text/plain"),
false
);
assert_eq!(mime_db.mime_type_equal("text/plain", "text/*"), false);
}
#[test]
fn mime_type_for_file_name() {
let mime_db = load_test_data();
assert_eq!(
mime_db.get_mime_types_from_file_name("foo.txt"),
vec!["text/plain".to_string()]
);
assert_eq!(
mime_db.get_mime_types_from_file_name("bar.gif"),
vec!["image/gif".to_string()]
);
}
#[test]
fn mime_type_for_file_data() {
let mime_db = load_test_data();
let svg_data = include_bytes!("../test_files/files/rust-logo.svg");
assert_eq!(
mime_db.get_mime_type_for_data(svg_data),
Some(("image/svg+xml".to_string(), 80))
);
let png_data = include_bytes!("../test_files/files/rust-logo.png");
assert_eq!(
mime_db.get_mime_type_for_data(png_data),
Some(("image/png".to_string(), 50))
);
}
#[test]
fn mime_type_subclass() {
let mime_db = load_test_data();
assert_eq!(
mime_db.mime_type_subclass("application/rtf", "text/plain"),
true
);
assert_eq!(
mime_db.mime_type_subclass("message/news", "text/plain"),
true
);
assert_eq!(
mime_db.mime_type_subclass("message/news", "message/*"),
true
);
assert_eq!(mime_db.mime_type_subclass("message/news", "text/*"), true);
assert_eq!(
mime_db.mime_type_subclass("message/news", "application/octet-stream"),
true
);
assert_eq!(
mime_db.mime_type_subclass("application/rtf", "application/octet-stream"),
true
);
assert_eq!(
mime_db.mime_type_subclass("application/x-gnome-app-info", "text/plain"),
true
);
assert_eq!(
mime_db.mime_type_subclass("image/x-djvu", "image/vnd.djvu"),
true
);
assert_eq!(
mime_db.mime_type_subclass("image/vnd.djvu", "image/x-djvu"),
true
);
assert_eq!(
mime_db.mime_type_subclass("image/vnd.djvu", "text/plain"),
false
);
assert_eq!(
mime_db.mime_type_subclass("image/vnd.djvu", "text/*"),
false
);
assert_eq!(mime_db.mime_type_subclass("text/*", "text/plain"), true);
}
}
|
use iostream::io::*;
use std::fs::remove_file;
fn remove_file_s() {
let _r = remove_file("1.txt");
let _r = remove_file("2.txt");
let _r = remove_file("3.txt");
}
#[test]
fn test_create() {
{
let r = FileStream::new("1.txt", FileMode::Create, FileAccess::ReadWrite);
if let Err(i) = r {
panic!(format!("{}", i))
}
}
{
let r = FileStream::new("1.txt", FileMode::CreateNew, FileAccess::ReadWrite);
if let Err(i) = r {
panic!(format!("{}", i))
}
}
{
let r = FileStream::new("3.txt", FileMode::Create, FileAccess::Write);
if let Err(i) = r {
panic!(format!("{}", i))
}
}
{
let r = FileStream::new("3.txt", FileMode::CreateNew, FileAccess::Write);
if let Err(i) = r {
panic!(format!("{}", i))
}
}
remove_file_s();
}
#[test]
#[should_panic]
fn test_create_2() {
{
let r = FileStream::new("2.txt", FileMode::Create, FileAccess::Read);
if let Err(i) = r {
panic!(format!("{}", i))
}
}
}
#[test]
#[should_panic]
fn test_create_3() {
{
let r = FileStream::new("2.txt", FileMode::CreateNew, FileAccess::Read);
if let Err(i) = r {
panic!(format!("{}", i))
}
}
}
#[test]
fn test_open() {
remove_file_s();
let r = FileStream::new("1.txt", FileMode::OpenOrCreate, FileAccess::ReadWrite);
if let Err(i) = r {
panic!(format!("{}", i))
}
let r = FileStream::new("1.txt", FileMode::Open, FileAccess::ReadWrite);
if let Err(i) = r {
panic!(format!("{}", i))
}
{
let r = FileStream::new("2.txt", FileMode::CreateNew, FileAccess::ReadWrite);
if let Err(i) = r {
panic!(format!("{}", i))
}
}
let r = FileStream::new("2.txt", FileMode::Open, FileAccess::Read);
if let Err(i) = r {
panic!(format!("{}", i))
}
let r = FileStream::new("3.txt", FileMode::OpenOrCreate, FileAccess::Write);
if let Err(i) = r {
panic!(format!("{}", i))
}
let r = FileStream::new("3.txt", FileMode::Open, FileAccess::Write);
if let Err(i) = r {
panic!(format!("{}", i))
}
remove_file_s();
}
#[test]
#[should_panic]
fn test_open_err() {
let r = FileStream::new("2.txt", FileMode::OpenOrCreate, FileAccess::Read);
if let Err(i) = r {
panic!(format!("{}", i))
}
}
#[test]
fn test_truncate() {
{
let r = FileStream::new("2.txt", FileMode::CreateNew, FileAccess::ReadWrite);
if let Err(i) = r {
panic!(format!("{}", i))
}
}
{
let r = FileStream::new("2.txt", FileMode::Truncate, FileAccess::Write);
if let Err(i) = r {
panic!(format!("{}", i))
}
}
{
let r = FileStream::new("2.txt", FileMode::Truncate, FileAccess::ReadWrite);
if let Err(i) = r {
panic!(format!("{}", i))
}
}
remove_file_s();
}
#[test]
#[should_panic]
fn test_truncate_err() {
{
let r = FileStream::new("2.txt", FileMode::CreateNew, FileAccess::ReadWrite);
if let Err(i) = r {
panic!(format!("{}", i))
}
}
remove_file_s();
{
let r = FileStream::new("2.txt", FileMode::Truncate, FileAccess::Read);
if let Err(i) = r {
panic!(format!("{}", i))
}
}
}
#[test]
fn test_append() {
{
let r = FileStream::new("2.txt", FileMode::CreateNew, FileAccess::ReadWrite);
if let Err(i) = r {
panic!(format!("{}", i))
}
}
{
let r = FileStream::new("2.txt", FileMode::Append, FileAccess::ReadWrite);
if let Err(i) = r {
panic!(format!("{}", i))
}
}
{
let r = FileStream::new("2.txt", FileMode::Append, FileAccess::Write);
if let Err(i) = r {
panic!(format!("{}", i))
}
}
remove_file_s();
}
#[test]
#[should_panic]
fn test_append_err() {
{
let r = FileStream::new("2.txt", FileMode::CreateNew, FileAccess::ReadWrite);
if let Err(i) = r {
panic!(format!("{}", i))
} else {
println!("Have1");
}
}
remove_file_s();
{
let r = FileStream::new("2.txt", FileMode::Append, FileAccess::Read);
if let Err(i) = r {
let errmsg = format!("{}", i);
panic!(errmsg);
} else {
println!("Have2");
}
}
}
|
use crate::arrow2::error::Result;
use crate::arrow2::ffi::{FFIArrowChunk, FFIArrowSchema, FFIArrowTable};
use arrow2::array::Array;
use arrow2::chunk::Chunk;
use arrow2::io::ipc::write::{StreamWriter as IPCStreamWriter, WriteOptions as IPCWriteOptions};
use arrow2::io::parquet::read::{
infer_schema, read_metadata as parquet_read_metadata, FileReader as ParquetFileReader,
};
use parquet2::metadata::{FileMetaData, RowGroupMetaData};
use std::io::Cursor;
/// Internal function to read a buffer with Parquet data into a buffer with Arrow IPC Stream data
/// using the arrow2 and parquet2 crates
pub fn read_parquet(
parquet_file: &[u8],
chunk_fn: impl Fn(Chunk<Box<dyn Array>>) -> Chunk<Box<dyn Array>>,
) -> Result<Vec<u8>> {
// Create Parquet reader
let mut input_file = Cursor::new(parquet_file);
let metadata = parquet_read_metadata(&mut input_file)?;
let schema = infer_schema(&metadata)?;
let file_reader = ParquetFileReader::new(
input_file,
metadata.row_groups,
schema.clone(),
None,
None,
None,
);
// Create IPC writer
let mut output_file = Vec::new();
let options = IPCWriteOptions { compression: None };
let mut writer = IPCStreamWriter::new(&mut output_file, options);
writer.start(&schema, None)?;
// Iterate over reader chunks, writing each into the IPC writer
for maybe_chunk in file_reader {
let chunk = chunk_fn(maybe_chunk?);
writer.write(&chunk, None)?;
}
writer.finish()?;
Ok(output_file)
}
pub fn read_parquet_ffi(
parquet_file: &[u8],
chunk_fn: impl Fn(Chunk<Box<dyn Array>>) -> Chunk<Box<dyn Array>>,
) -> Result<FFIArrowTable> {
// Create Parquet reader
let mut input_file = Cursor::new(parquet_file);
let metadata = parquet_read_metadata(&mut input_file)?;
let schema = infer_schema(&metadata)?;
let file_reader = ParquetFileReader::new(
input_file,
metadata.row_groups,
schema.clone(),
None,
None,
None,
);
let ffi_schema: FFIArrowSchema = (&schema).into();
let mut ffi_chunks: Vec<FFIArrowChunk> = vec![];
// Iterate over reader chunks, storing each in memory to be used for FFI
for maybe_chunk in file_reader {
let chunk = chunk_fn(maybe_chunk?);
ffi_chunks.push(chunk.into());
}
Ok((ffi_schema, ffi_chunks).into())
}
/// Read metadata from parquet buffer
pub fn read_metadata(parquet_file: &[u8]) -> Result<FileMetaData> {
let mut input_file = Cursor::new(parquet_file);
Ok(parquet_read_metadata(&mut input_file)?)
}
/// Read single row group
pub fn read_row_group(
parquet_file: &[u8],
schema: arrow2::datatypes::Schema,
row_group: RowGroupMetaData,
chunk_fn: impl Fn(Chunk<Box<dyn Array>>) -> Chunk<Box<dyn Array>>,
) -> Result<Vec<u8>> {
let input_file = Cursor::new(parquet_file);
let file_reader = ParquetFileReader::new(
input_file,
vec![row_group],
schema.clone(),
None,
None,
None,
);
// Create IPC writer
let mut output_file = Vec::new();
let options = IPCWriteOptions { compression: None };
let mut writer = IPCStreamWriter::new(&mut output_file, options);
writer.start(&schema, None)?;
// Iterate over reader chunks, writing each into the IPC writer
for maybe_chunk in file_reader {
let chunk = chunk_fn(maybe_chunk?);
writer.write(&chunk, None)?;
}
writer.finish()?;
Ok(output_file)
}
|
use std::borrow::Cow;
use std::ops::Deref;
use std::{cmp, mem};
use alacritty_terminal::ansi::{Color, CursorShape, NamedColor};
use alacritty_terminal::event::EventListener;
use alacritty_terminal::grid::Indexed;
use alacritty_terminal::index::{Column, Line, Point};
use alacritty_terminal::selection::SelectionRange;
use alacritty_terminal::term::cell::{Cell, Flags, Hyperlink};
use alacritty_terminal::term::color::{CellRgb, Rgb};
use alacritty_terminal::term::search::{Match, RegexSearch};
use alacritty_terminal::term::{self, RenderableContent as TerminalContent, Term, TermMode};
use crate::config::UiConfig;
use crate::display::color::{List, DIM_FACTOR};
use crate::display::hint::{self, HintState};
use crate::display::Display;
use crate::event::SearchState;
/// Minimum contrast between a fixed cursor color and the cell's background.
pub const MIN_CURSOR_CONTRAST: f64 = 1.5;
/// Renderable terminal content.
///
/// This provides the terminal cursor and an iterator over all non-empty cells.
pub struct RenderableContent<'a> {
terminal_content: TerminalContent<'a>,
cursor: RenderableCursor,
cursor_shape: CursorShape,
cursor_point: Point<usize>,
search: Option<HintMatches<'a>>,
hint: Option<Hint<'a>>,
config: &'a UiConfig,
colors: &'a List,
focused_match: Option<&'a Match>,
}
impl<'a> RenderableContent<'a> {
pub fn new<T: EventListener>(
config: &'a UiConfig,
display: &'a mut Display,
term: &'a Term<T>,
search_state: &'a SearchState,
) -> Self {
let search = search_state.dfas().map(|dfas| HintMatches::visible_regex_matches(term, dfas));
let focused_match = search_state.focused_match();
let terminal_content = term.renderable_content();
// Find terminal cursor shape.
let cursor_shape = if terminal_content.cursor.shape == CursorShape::Hidden
|| display.cursor_hidden
|| search_state.regex().is_some()
|| display.ime.preedit().is_some()
{
CursorShape::Hidden
} else if !term.is_focused && config.terminal_config.cursor.unfocused_hollow {
CursorShape::HollowBlock
} else {
terminal_content.cursor.shape
};
// Convert terminal cursor point to viewport position.
let cursor_point = terminal_content.cursor.point;
let display_offset = terminal_content.display_offset;
let cursor_point = term::point_to_viewport(display_offset, cursor_point).unwrap();
let hint = if display.hint_state.active() {
display.hint_state.update_matches(term);
Some(Hint::from(&display.hint_state))
} else {
None
};
Self {
colors: &display.colors,
cursor: RenderableCursor::new_hidden(),
terminal_content,
focused_match,
cursor_shape,
cursor_point,
search,
config,
hint,
}
}
/// Viewport offset.
pub fn display_offset(&self) -> usize {
self.terminal_content.display_offset
}
/// Get the terminal cursor.
pub fn cursor(mut self) -> RenderableCursor {
// Assure this function is only called after the iterator has been drained.
debug_assert!(self.next().is_none());
self.cursor
}
/// Get the RGB value for a color index.
pub fn color(&self, color: usize) -> Rgb {
self.terminal_content.colors[color].unwrap_or(self.colors[color])
}
pub fn selection_range(&self) -> Option<SelectionRange> {
self.terminal_content.selection
}
/// Assemble the information required to render the terminal cursor.
fn renderable_cursor(&mut self, cell: &RenderableCell) -> RenderableCursor {
// Cursor colors.
let color = if self.terminal_content.mode.contains(TermMode::VI) {
self.config.colors.vi_mode_cursor
} else {
self.config.colors.cursor
};
let cursor_color =
self.terminal_content.colors[NamedColor::Cursor].map_or(color.background, CellRgb::Rgb);
let text_color = color.foreground;
let insufficient_contrast = (!matches!(cursor_color, CellRgb::Rgb(_))
|| !matches!(text_color, CellRgb::Rgb(_)))
&& cell.fg.contrast(*cell.bg) < MIN_CURSOR_CONTRAST;
// Convert from cell colors to RGB.
let mut text_color = text_color.color(cell.fg, cell.bg);
let mut cursor_color = cursor_color.color(cell.fg, cell.bg);
// Invert cursor color with insufficient contrast to prevent invisible cursors.
if insufficient_contrast {
cursor_color = self.config.colors.primary.foreground;
text_color = self.config.colors.primary.background;
}
RenderableCursor {
is_wide: cell.flags.contains(Flags::WIDE_CHAR),
shape: self.cursor_shape,
point: self.cursor_point,
cursor_color,
text_color,
}
}
}
impl<'a> Iterator for RenderableContent<'a> {
type Item = RenderableCell;
/// Gets the next renderable cell.
///
/// Skips empty (background) cells and applies any flags to the cell state
/// (eg. invert fg and bg colors).
#[inline]
fn next(&mut self) -> Option<Self::Item> {
loop {
let cell = self.terminal_content.display_iter.next()?;
let mut cell = RenderableCell::new(self, cell);
if self.cursor_point == cell.point {
// Store the cursor which should be rendered.
self.cursor = self.renderable_cursor(&cell);
if self.cursor.shape == CursorShape::Block {
cell.fg = self.cursor.text_color;
cell.bg = self.cursor.cursor_color;
// Since we draw Block cursor by drawing cell below it with a proper color,
// we must adjust alpha to make it visible.
cell.bg_alpha = 1.;
}
return Some(cell);
} else if !cell.is_empty() && !cell.flags.contains(Flags::WIDE_CHAR_SPACER) {
// Skip empty cells and wide char spacers.
return Some(cell);
}
}
}
}
/// Cell ready for rendering.
#[derive(Clone, Debug)]
pub struct RenderableCell {
pub character: char,
pub point: Point<usize>,
pub fg: Rgb,
pub bg: Rgb,
pub bg_alpha: f32,
pub underline: Rgb,
pub flags: Flags,
pub extra: Option<Box<RenderableCellExtra>>,
}
/// Extra storage with rarely present fields for [`RenderableCell`], to reduce the cell size we
/// pass around.
#[derive(Clone, Debug)]
pub struct RenderableCellExtra {
pub zerowidth: Option<Vec<char>>,
pub hyperlink: Option<Hyperlink>,
}
impl RenderableCell {
fn new(content: &mut RenderableContent<'_>, cell: Indexed<&Cell>) -> Self {
// Lookup RGB values.
let mut fg = Self::compute_fg_rgb(content, cell.fg, cell.flags);
let mut bg = Self::compute_bg_rgb(content, cell.bg);
let mut bg_alpha = if cell.flags.contains(Flags::INVERSE) {
mem::swap(&mut fg, &mut bg);
1.0
} else {
Self::compute_bg_alpha(content.config, cell.bg)
};
let is_selected = content.terminal_content.selection.map_or(false, |selection| {
selection.contains_cell(
&cell,
content.terminal_content.cursor.point,
content.cursor_shape,
)
});
let display_offset = content.terminal_content.display_offset;
let viewport_start = Point::new(Line(-(display_offset as i32)), Column(0));
let colors = &content.config.colors;
let mut character = cell.c;
if let Some((c, is_first)) =
content.hint.as_mut().and_then(|hint| hint.advance(viewport_start, cell.point))
{
let (config_fg, config_bg) = if is_first {
(colors.hints.start.foreground, colors.hints.start.background)
} else {
(colors.hints.end.foreground, colors.hints.end.background)
};
Self::compute_cell_rgb(&mut fg, &mut bg, &mut bg_alpha, config_fg, config_bg);
character = c;
} else if is_selected {
let config_fg = colors.selection.foreground;
let config_bg = colors.selection.background;
Self::compute_cell_rgb(&mut fg, &mut bg, &mut bg_alpha, config_fg, config_bg);
if fg == bg && !cell.flags.contains(Flags::HIDDEN) {
// Reveal inversed text when fg/bg is the same.
fg = content.color(NamedColor::Background as usize);
bg = content.color(NamedColor::Foreground as usize);
bg_alpha = 1.0;
}
} else if content.search.as_mut().map_or(false, |search| search.advance(cell.point)) {
let focused = content.focused_match.map_or(false, |fm| fm.contains(&cell.point));
let (config_fg, config_bg) = if focused {
(colors.search.focused_match.foreground, colors.search.focused_match.background)
} else {
(colors.search.matches.foreground, colors.search.matches.background)
};
Self::compute_cell_rgb(&mut fg, &mut bg, &mut bg_alpha, config_fg, config_bg);
}
// Apply transparency to all renderable cells if `transparent_background_colors` is set
if bg_alpha > 0. && content.config.colors.transparent_background_colors {
bg_alpha = content.config.window_opacity();
}
// Convert cell point to viewport position.
let cell_point = cell.point;
let point = term::point_to_viewport(display_offset, cell_point).unwrap();
let flags = cell.flags;
let underline = cell
.underline_color()
.map_or(fg, |underline| Self::compute_fg_rgb(content, underline, flags));
let zerowidth = cell.zerowidth();
let hyperlink = cell.hyperlink();
let extra = (zerowidth.is_some() || hyperlink.is_some()).then(|| {
Box::new(RenderableCellExtra {
zerowidth: zerowidth.map(|zerowidth| zerowidth.to_vec()),
hyperlink,
})
});
RenderableCell { flags, character, bg_alpha, point, fg, bg, underline, extra }
}
/// Check if cell contains any renderable content.
fn is_empty(&self) -> bool {
self.bg_alpha == 0.
&& self.character == ' '
&& self.extra.is_none()
&& !self.flags.intersects(Flags::ALL_UNDERLINES | Flags::STRIKEOUT)
}
/// Apply [`CellRgb`] colors to the cell's colors.
fn compute_cell_rgb(
cell_fg: &mut Rgb,
cell_bg: &mut Rgb,
bg_alpha: &mut f32,
fg: CellRgb,
bg: CellRgb,
) {
let old_fg = mem::replace(cell_fg, fg.color(*cell_fg, *cell_bg));
*cell_bg = bg.color(old_fg, *cell_bg);
if bg != CellRgb::CellBackground {
*bg_alpha = 1.0;
}
}
/// Get the RGB color from a cell's foreground color.
fn compute_fg_rgb(content: &RenderableContent<'_>, fg: Color, flags: Flags) -> Rgb {
let config = &content.config;
match fg {
Color::Spec(rgb) => match flags & Flags::DIM {
Flags::DIM => {
let rgb: Rgb = rgb.into();
rgb * DIM_FACTOR
},
_ => rgb.into(),
},
Color::Named(ansi) => {
match (config.draw_bold_text_with_bright_colors(), flags & Flags::DIM_BOLD) {
// If no bright foreground is set, treat it like the BOLD flag doesn't exist.
(_, Flags::DIM_BOLD)
if ansi == NamedColor::Foreground
&& config.colors.primary.bright_foreground.is_none() =>
{
content.color(NamedColor::DimForeground as usize)
},
// Draw bold text in bright colors *and* contains bold flag.
(true, Flags::BOLD) => content.color(ansi.to_bright() as usize),
// Cell is marked as dim and not bold.
(_, Flags::DIM) | (false, Flags::DIM_BOLD) => {
content.color(ansi.to_dim() as usize)
},
// None of the above, keep original color..
_ => content.color(ansi as usize),
}
},
Color::Indexed(idx) => {
let idx = match (
config.draw_bold_text_with_bright_colors(),
flags & Flags::DIM_BOLD,
idx,
) {
(true, Flags::BOLD, 0..=7) => idx as usize + 8,
(false, Flags::DIM, 8..=15) => idx as usize - 8,
(false, Flags::DIM, 0..=7) => NamedColor::DimBlack as usize + idx as usize,
_ => idx as usize,
};
content.color(idx)
},
}
}
/// Get the RGB color from a cell's background color.
#[inline]
fn compute_bg_rgb(content: &RenderableContent<'_>, bg: Color) -> Rgb {
match bg {
Color::Spec(rgb) => rgb.into(),
Color::Named(ansi) => content.color(ansi as usize),
Color::Indexed(idx) => content.color(idx as usize),
}
}
/// Compute background alpha based on cell's original color.
///
/// Since an RGB color matching the background should not be transparent, this is computed
/// using the named input color, rather than checking the RGB of the background after its color
/// is computed.
#[inline]
fn compute_bg_alpha(config: &UiConfig, bg: Color) -> f32 {
if bg == Color::Named(NamedColor::Background) {
0.
} else if config.colors.transparent_background_colors {
config.window_opacity()
} else {
1.
}
}
}
/// Cursor storing all information relevant for rendering.
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
pub struct RenderableCursor {
shape: CursorShape,
cursor_color: Rgb,
text_color: Rgb,
is_wide: bool,
point: Point<usize>,
}
impl RenderableCursor {
fn new_hidden() -> Self {
let shape = CursorShape::Hidden;
let cursor_color = Rgb::default();
let text_color = Rgb::default();
let is_wide = false;
let point = Point::default();
Self { shape, cursor_color, text_color, is_wide, point }
}
}
impl RenderableCursor {
pub fn new(point: Point<usize>, shape: CursorShape, cursor_color: Rgb, is_wide: bool) -> Self {
Self { shape, cursor_color, text_color: cursor_color, is_wide, point }
}
pub fn color(&self) -> Rgb {
self.cursor_color
}
pub fn shape(&self) -> CursorShape {
self.shape
}
pub fn is_wide(&self) -> bool {
self.is_wide
}
pub fn point(&self) -> Point<usize> {
self.point
}
}
/// Regex hints for keyboard shortcuts.
struct Hint<'a> {
/// Hint matches and position.
matches: HintMatches<'a>,
/// Last match checked against current cell position.
labels: &'a Vec<Vec<char>>,
}
impl<'a> Hint<'a> {
/// Advance the hint iterator.
///
/// If the point is within a hint, the keyboard shortcut character that should be displayed at
/// this position will be returned.
///
/// The tuple's [`bool`] will be `true` when the character is the first for this hint.
fn advance(&mut self, viewport_start: Point, point: Point) -> Option<(char, bool)> {
// Check if we're within a match at all.
if !self.matches.advance(point) {
return None;
}
// Match starting position on this line; linebreaks interrupt the hint labels.
let start = self
.matches
.get(self.matches.index)
.map(|bounds| cmp::max(*bounds.start(), viewport_start))
.filter(|start| start.line == point.line)?;
// Position within the hint label.
let label_position = point.column.0 - start.column.0;
let is_first = label_position == 0;
// Hint label character.
self.labels[self.matches.index].get(label_position).copied().map(|c| (c, is_first))
}
}
impl<'a> From<&'a HintState> for Hint<'a> {
fn from(hint_state: &'a HintState) -> Self {
let matches = HintMatches::new(hint_state.matches());
Self { labels: hint_state.labels(), matches }
}
}
/// Visible hint match tracking.
#[derive(Default)]
struct HintMatches<'a> {
/// All visible matches.
matches: Cow<'a, [Match]>,
/// Index of the last match checked.
index: usize,
}
impl<'a> HintMatches<'a> {
/// Create new renderable matches iterator..
fn new(matches: impl Into<Cow<'a, [Match]>>) -> Self {
Self { matches: matches.into(), index: 0 }
}
/// Create from regex matches on term visable part.
fn visible_regex_matches<T>(term: &Term<T>, dfas: &RegexSearch) -> Self {
let matches = hint::visible_regex_match_iter(term, dfas).collect::<Vec<_>>();
Self::new(matches)
}
/// Advance the regex tracker to the next point.
///
/// This will return `true` if the point passed is part of a regex match.
fn advance(&mut self, point: Point) -> bool {
while let Some(bounds) = self.get(self.index) {
if bounds.start() > &point {
break;
} else if bounds.end() < &point {
self.index += 1;
} else {
return true;
}
}
false
}
}
impl<'a> Deref for HintMatches<'a> {
type Target = [Match];
fn deref(&self) -> &Self::Target {
self.matches.deref()
}
}
|
#[cfg(not(target_os = "linux"))]
compile_error!("PidFd is only supported on Linux >= 5.3");
use fd_reactor::{Interest, REACTOR};
use std::{
convert::TryInto,
future::Future,
io,
mem::MaybeUninit,
os::unix::{
io::{AsRawFd, RawFd},
process::ExitStatusExt,
},
pin::Pin,
process::ExitStatus,
sync::{
atomic::{AtomicBool, Ordering},
mpsc, Arc, Mutex,
},
task::{Context, Poll, Waker},
time::Duration,
};
const PIDFD_OPEN: libc::c_int = 434;
const PID_SEND: libc::c_int = 424;
const P_PIDFD: libc::idtype_t = 3;
/// A file descriptor which refers to a process
pub struct PidFd(RawFd);
impl PidFd {
/// Converts a `Child` into a `PidFd`; validating if the PID is in range
pub fn from_std_checked(child: &std::process::Child) -> io::Result<Self> {
child
.id()
.try_into()
.map_err(|_| {
io::Error::new(
io::ErrorKind::Other,
"child process ID is outside the range of libc::pid_t",
)
})
.and_then(|pid| unsafe { Self::open(pid, 0) })
}
pub fn into_future(self) -> PidFuture {
self.into()
}
#[cfg(feature = "waitid")]
pub fn wait(&self) -> io::Result<ExitStatus> {
waitid(self.0)
}
/// Creates a PID file descriptor from a PID
pub unsafe fn open(pid: libc::pid_t, flags: libc::c_uint) -> io::Result<Self> {
let pidfd = pidfd_create(pid, flags);
if -1 == pidfd {
Err(io::Error::last_os_error())
} else {
Ok(Self(pidfd))
}
}
/// Sends a signal to the process owned by this PID file descriptor
pub unsafe fn send_raw_signal(
&self,
sig: libc::c_int,
info: *const libc::siginfo_t,
flags: libc::c_uint,
) -> io::Result<()> {
if -1 == pidfd_send_signal(self.0, sig, info, flags) {
Err(io::Error::last_os_error())
} else {
Ok(())
}
}
}
impl From<PidFd> for PidFuture {
fn from(fd: PidFd) -> Self {
Self {
fd,
completed: Arc::new(AtomicBool::new(false)),
registered: false,
}
}
}
pub struct PidFuture {
fd: PidFd,
completed: Arc<AtomicBool>,
registered: bool,
}
impl Future for PidFuture {
type Output = io::Result<ExitStatus>;
fn poll(mut self: Pin<&mut Self>, context: &mut Context) -> Poll<Self::Output> {
if self.completed.load(Ordering::SeqCst) {
REACTOR.unregister(self.fd.0);
#[cfg(feature = "waitid")]
{
Poll::Ready(waitid(self.fd.0))
}
#[cfg(not(feature = "waitid"))]
{
Poll::Ready(Ok(ExitStatus::from_raw(0)))
}
} else {
if !self.registered {
REACTOR.register(
self.fd.0,
Interest::READ,
Arc::clone(&self.completed),
context.waker().clone(),
);
self.registered = true;
}
Poll::Pending
}
}
}
impl AsRawFd for PidFd {
fn as_raw_fd(&self) -> RawFd {
self.0
}
}
impl Drop for PidFd {
fn drop(&mut self) {
let _ = unsafe { libc::close(self.0) };
}
}
impl From<&std::process::Child> for PidFd {
fn from(child: &std::process::Child) -> Self {
Self::from_std_checked(child).unwrap()
}
}
impl From<std::process::Child> for PidFd {
fn from(child: std::process::Child) -> Self {
Self::from(&child)
}
}
extern "C" {
fn syscall(num: libc::c_int, ...) -> libc::c_int;
}
unsafe fn pidfd_create(pid: libc::pid_t, flags: libc::c_uint) -> libc::c_int {
syscall(PIDFD_OPEN, pid, flags)
}
unsafe fn pidfd_send_signal(
pidfd: libc::c_int,
sig: libc::c_int,
info: *const libc::siginfo_t,
flags: libc::c_uint,
) -> libc::c_int {
syscall(PID_SEND, pidfd, sig, info, flags)
}
#[cfg(feature = "waitid")]
fn waitid(pidfd: RawFd) -> io::Result<ExitStatus> {
unsafe {
let mut info = MaybeUninit::<libc::siginfo_t>::uninit();
let exit_status = libc::waitid(P_PIDFD, pidfd as u32, info.as_mut_ptr(), libc::WEXITED);
if -1 == exit_status {
Err(io::Error::last_os_error())
} else {
Ok(ExitStatus::from_raw(info.assume_init().si_errno))
}
}
}
|
use std::{
future::Future,
pin::Pin,
task::{Context, Poll},
time::Duration,
};
use pin_project_lite::pin_project;
use crate::{
actor::Actor,
clock::{sleep, Sleep},
fut::ActorFuture,
};
pin_project! {
/// Future for the [`timeout`](super::ActorFutureExt::timeout) combinator, interrupts computations if it takes
/// more than [`timeout`](super::ActorFutureExt::timeout).
///
/// This is created by the [`timeout`](super::ActorFutureExt::timeout) method.
#[derive(Debug)]
#[must_use = "futures do nothing unless polled"]
pub struct Timeout<F>{
#[pin]
fut: F,
#[pin]
timeout: Sleep,
}
}
impl<F> Timeout<F> {
pub(super) fn new(future: F, timeout: Duration) -> Self {
Self {
fut: future,
timeout: sleep(timeout),
}
}
}
impl<F, A> ActorFuture<A> for Timeout<F>
where
F: ActorFuture<A>,
A: Actor,
{
type Output = Result<F::Output, ()>;
fn poll(
self: Pin<&mut Self>,
act: &mut A,
ctx: &mut A::Context,
task: &mut Context<'_>,
) -> Poll<Self::Output> {
let this = self.project();
match this.fut.poll(act, ctx, task) {
Poll::Ready(res) => Poll::Ready(Ok(res)),
Poll::Pending => this.timeout.poll(task).map(Err),
}
}
}
|
use bitfield::bitfield;
#[allow(dead_code)]
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum Register {
LeftInputVol = 0x00,
RightInputVol = 0x01,
Lout1Vol = 0x02,
Rout1Vol = 0x03,
Clocking = 0x04,
Ctr1 = 0x05,
Ctr2 = 0x06,
AudioIface = 0x07,
Clocking2 = 0x08,
AudioIface2 = 0x09,
LdacVol = 0x0A,
RdacVol = 0x0B,
Reset = 0x0F,
Ctr3D = 0x10,
Alc1 = 0x11,
Alc2 = 0x12,
Alc3 = 0x13,
NoiseGate = 0x14,
LadcVol = 0x15,
RadcVol = 0x16,
Addctr1 = 0x17,
Addctr2 = 0x18,
PwrMgmt1 = 0x19,
PwrMgmt2 = 0x1A,
Addctr3 = 0x1B,
AntiPop1 = 0x1C,
AntiPop2 = 0x1D,
LadcSignalPath = 0x20,
RadcSignalPath = 0x21,
LoutMix1 = 0x22,
RoutMix1 = 0x25,
MonoOutMix1 = 0x26,
MonoOutMix2 = 0x27,
Lout2Vol = 0x28,
Rout2Vol = 0x29,
MonoOutVol = 0x2A,
InputBoostMixer1 = 0x2B,
InputBoostMixer2 = 0x2C,
Bypass1 = 0x2D,
Bypass2 = 0x2E,
PwrMgmt3 = 0x2F,
Addctr4 = 0x30,
ClassdCtr1 = 0x31,
ClassdCtr3 = 0x33,
PllN = 0x34,
PllK1 = 0x35,
PllK2 = 0x36,
PllK3 = 0x37,
}
impl Register {
pub(crate) fn addr(&self) -> u8 {
*self as u8
}
}
bitfield! {
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct LeftInputVol(u16);
u16;
pub linvol, set_linvol : 5, 0;
pub lizc, set_lizc : 6;
pub linmute, set_linmute : 7;
pub ipvu, set_ipvu : 8;
}
bitfield! {
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct RightInputVol(u16);
u16;
pub rinvol, set_rinvol : 5, 0;
pub rizc, set_rizc : 6;
pub rinmute, set_rinmute : 7;
pub ipvu, set_ipvu : 8;
}
bitfield! {
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Lout1Vol(u16);
u16;
pub lout1vol, set_lout1vol : 6, 0;
pub lo1zc, set_lo1zc : 7;
pub out1vu, set_out1vu : 8;
}
bitfield! {
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Rout1Vol(u16);
u16;
pub rout1vol, set_rout1vol : 6, 0;
pub ro1zc, set_ro1zc : 7;
pub out1vu, set_out1vu : 8;
}
bitfield! {
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Clocking(u16);
u16;
pub clksel, set_clksel : 0;
pub sysclkdiv, set_sysclkdiv : 2, 1;
pub dacdiv, set_dacdiv : 5, 3;
pub adcdiv, set_adcdiv : 8, 6;
}
bitfield! {
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Ctr1(u16);
u16;
pub deemph, set_deemph : 2, 1;
pub dacmu, set_dacmu : 3;
pub adcpol, set_adpol : 6, 5;
pub dacdiv2, set_dacdiv2 : 7;
}
bitfield! {
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Ctr2(u16);
u16;
pub dacslope, set_dacslope : 1;
pub dacmr, set_dacmr : 2;
pub dacsmm, set_dacsmm : 3;
pub dacpol, set_dacpol : 6, 5;
}
bitfield! {
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct AudioIface(u16);
u16;
pub format, set_format : 1, 0;
pub wl, set_wl : 3, 2;
pub lrp, set_lrp : 4;
pub dlrswap, set_dlrswap : 5;
pub ms, set_ms : 6;
pub bclkinv, set_bclkinv : 7;
pub alrswap, set_alrswap : 8;
}
bitfield! {
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct LdacVol(u16);
u16;
pub ldacvol, set_ldacvol : 7, 0;
pub dacvu, set_dacvu : 8;
}
bitfield! {
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct RdacVol(u16);
u16;
pub rdacvol, set_rdacvol : 7, 0;
pub dacvu, set_dacvu : 8;
}
bitfield! {
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct NoiseGate(u16);
u16;
pub ngat, set_ngat : 0;
pub ngth, set_ngth : 7, 3;
}
bitfield! {
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct LadcVol(u16);
u16;
pub ladcvol, set_ladcvol : 7, 0;
pub adcvu, set_adcvu : 8;
}
bitfield! {
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct RadcVol(u16);
u16;
pub radcvol, set_radcvol : 7, 0;
pub adcvu, set_adcvu : 8;
}
bitfield! {
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Addctr1(u16);
u16;
pub toen, set_toen : 0;
pub toclksel, set_toclksel : 1;
pub datsel, set_datsel : 3, 2;
pub dmonomix, set_dmonomix : 4;
pub vsel, set_vsel : 7, 6;
pub tsden, set_tsden : 8;
}
bitfield! {
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Addctr2(u16);
u16;
pub lrcm, set_lrcm : 2;
pub tris, set_tris : 3;
pub hpswpol, set_hpswpol : 5;
pub hpswen, set_hpswen : 6;
}
bitfield! {
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Addctr3(u16);
u16;
pub adc_alc_sr, set_adc_alc_sr : 2, 0;
pub out3cap, set_out3cap : 3;
pub vroi, set_vroi : 6;
}
bitfield! {
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct PwrMgmt1(u16);
u16;
pub digenb, set_digenb : 0;
pub micb, set_micb : 1;
pub adcr, set_adcr : 2;
pub adcl, set_adcl : 3;
pub ainr, set_ainr : 4;
pub ainl, set_ainl : 5;
pub vref, set_vref : 6;
pub vmidsel, set_vmidsel : 8, 7;
}
bitfield! {
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct PwrMgmt2(u16);
u16;
pub pllen, set_pllen : 0;
pub out3, set_out3 : 1;
pub spkr, set_spkr : 3;
pub spkl, set_spkl : 4;
pub rout1, set_rout1 : 5;
pub lout1, set_lout1 : 6;
pub dacr, set_dacr : 7;
pub dacl, set_dacl : 8;
}
bitfield! {
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct LadcSignalPath(u16);
u16;
pub lmic2b, set_lmic2b : 3;
pub lmicboost, set_lmicboost : 5, 4;
pub lmp2, set_lmp2 : 6;
pub lmp3, set_lmp3 : 7;
pub lmn1, set_lmn1 : 8;
}
bitfield! {
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct RadcSignalPath(u16);
u16;
pub rmic2b, set_rmic2b : 3;
pub rmicboost, set_rmicboost : 5, 4;
pub rmp2, set_rmp2 : 6;
pub rmp3, set_rmp3 : 7;
pub rmn1, set_rmn1 : 8;
}
bitfield! {
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct LoutMix1(u16);
u16;
pub li2lovol, set_li2lovol : 6, 4;
pub li2lo, set_li2lo : 7;
pub ld2lo, set_ld2lo : 8;
}
bitfield! {
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct RoutMix1(u16);
u16;
pub ri2rovol, set_ri2rovol : 6, 4;
pub ri2ro, set_ri2ro : 7;
pub rd2ro, set_rd2ro : 8;
}
bitfield! {
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Lout2Vol(u16);
u16;
pub spklvol, set_spklvol : 6, 0;
pub spklzc, set_spklzc : 7;
pub spkvu, set_spkvu : 8;
}
bitfield! {
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Rout2Vol(u16);
u16;
pub spkrvol, set_spkrvol : 6, 0;
pub spkrzc, set_spkrzc : 7;
pub spkvu, set_spkvu : 8;
}
bitfield! {
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct PwrMgmt3(u16);
u16;
pub romix, set_romix : 2;
pub lomix, set_lomix : 3;
pub rmic, set_rmic : 4;
pub lmic, set_lmic : 5;
}
bitfield! {
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Addctr4(u16);
u16;
pub mbsel, set_mbsel : 0;
pub tsensen, set_tsensen : 1;
pub hpsel, set_hpsel : 3, 2;
pub gpiosel, set_gpiosel : 6, 4;
pub gpiopol, set_gpiopol : 7;
}
bitfield! {
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct ClassdCtr1(u16);
u16;
/// Should be 0b110111
pub reserved, set_reserved : 5, 0;
pub spkopen, set_spkopen : 7, 6;
}
|
#![crate_name = "uu_link"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Michael Gehring <mg@ebfe.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
#[macro_use]
extern crate uucore;
use std::fs::hard_link;
use std::io::Write;
use std::path::Path;
use std::io::Error;
static NAME: &'static str = "link";
static VERSION: &'static str = env!("CARGO_PKG_VERSION");
pub fn normalize_error_message(e: Error) -> String {
match e.raw_os_error() {
Some(2) => { String::from("No such file or directory (os error 2)") }
_ => { format!("{}", e) }
}
}
pub fn uumain(args: Vec<String>) -> i32 {
let mut opts = getopts::Options::new();
opts.optflag("h", "help", "display this help and exit");
opts.optflag("V", "version", "output version information and exit");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(err) => panic!("{}", err),
};
if matches.opt_present("version") {
println!("{} {}", NAME, VERSION);
return 0;
}
if matches.opt_present("help") || matches.free.len() != 2 {
let msg = format!("{0} {1}
Usage:
{0} [OPTIONS] FILE1 FILE2
Create a link named FILE2 to FILE1.", NAME, VERSION);
println!("{}", opts.usage(&msg));
if matches.free.len() != 2 {
return 1;
}
return 0;
}
let old = Path::new(&matches.free[0]);
let new = Path::new(&matches.free[1]);
match hard_link(old, new) {
Ok(_) => 0,
Err(err) => {
show_error!("{}",normalize_error_message(err));
1
}
}
}
|
fn main() {
let pair = (-2, 0);
println!("Katakan padaku tentang {:?}", pair);
match pair {
(0, y) => println!("Pertama `0` dan `y` adalah `{:?}`", y),
(x, 0) => println!("`x` adalah `{:?}` dan terakhir adalah `0`", x),
_ => println!("Tidak masallah apa mereka itu"),
}
}
|
const MAX_PORT:u64 = 10000;
fn main() {
let a = 1;
let b = 2;
let mut ab = 1;
println!("hello world{}", a);
println!("hello world{}", ab);
println!("hello world{}", b);
println!("Hello, world!");
ab = 44;
println!("{}", ab);
let b: f32 = 2.22;
println!("b = {}", b);
println!("max_port = {}",MAX_PORT);
let mut ss: u64 = 3;
println!("ss{}", ss);
ss = 55;
println!("{}",ss);
let wuhaurou: u64 = 555;
println!("{}",wuhaurou)
}
|
use libc;
extern "C" {
pub type __sFILEX;
#[no_mangle]
fn strerror(_: libc::c_int) -> *mut libc::c_char;
#[no_mangle]
static mut __stdinp: *mut FILE;
#[no_mangle]
static mut __stdoutp: *mut FILE;
#[no_mangle]
static mut __stderrp: *mut FILE;
#[no_mangle]
fn fclose(_: *mut FILE) -> libc::c_int;
#[no_mangle]
fn feof(_: *mut FILE) -> libc::c_int;
#[no_mangle]
fn ferror(_: *mut FILE) -> libc::c_int;
#[no_mangle]
fn fopen(__filename: *const libc::c_char, __mode: *const libc::c_char) -> *mut FILE;
#[no_mangle]
fn fprintf(_: *mut FILE, _: *const libc::c_char, ...) -> libc::c_int;
#[no_mangle]
fn fread(
__ptr: *mut libc::c_void,
__size: size_t,
__nitems: size_t,
__stream: *mut FILE,
) -> size_t;
#[no_mangle]
fn perror(_: *const libc::c_char) -> ();
#[no_mangle]
fn puts(_: *const libc::c_char) -> libc::c_int;
#[no_mangle]
fn cbor_error_string(error: CborError_0) -> *const libc::c_char;
#[no_mangle]
fn cbor_parser_init(
buffer: *const uint8_t,
size: size_t,
flags: uint32_t,
parser: *mut CborParser_0,
it: *mut CborValue_0,
) -> CborError_0;
/* The following API requires a hosted C implementation (uses FILE*) */
#[no_mangle]
fn cbor_value_to_pretty_advance_flags(
out: *mut FILE,
value: *mut CborValue_0,
flags: libc::c_int,
) -> CborError_0;
#[no_mangle]
fn cbor_value_to_json_advance(
out: *mut FILE,
value: *mut CborValue_0,
flags: libc::c_int,
) -> CborError_0;
#[no_mangle]
fn __error() -> *mut libc::c_int;
#[no_mangle]
fn realloc(_: *mut libc::c_void, _: libc::c_ulong) -> *mut libc::c_void;
#[no_mangle]
fn exit(_: libc::c_int) -> !;
#[no_mangle]
fn getopt(_: libc::c_int, _: *const *mut libc::c_char, _: *const libc::c_char) -> libc::c_int;
#[no_mangle]
static mut optind: libc::c_int;
#[no_mangle]
static mut optopt: libc::c_int;
}
pub type size_t = libc::c_ulong;
pub type uint8_t = libc::c_uchar;
pub type uint16_t = libc::c_ushort;
pub type uint32_t = libc::c_uint;
pub type __int64_t = libc::c_longlong;
pub type __darwin_off_t = __int64_t;
pub type fpos_t = __darwin_off_t;
#[derive(Copy, Clone)]
#[repr(C)]
pub struct __sbuf {
pub _base: *mut libc::c_uchar,
pub _size: libc::c_int,
}
#[derive(Copy, Clone)]
#[repr(C)]
pub struct __sFILE {
pub _p: *mut libc::c_uchar,
pub _r: libc::c_int,
pub _w: libc::c_int,
pub _flags: libc::c_short,
pub _file: libc::c_short,
pub _bf: __sbuf,
pub _lbfsize: libc::c_int,
pub _cookie: *mut libc::c_void,
pub _close: Option<unsafe extern "C" fn(_: *mut libc::c_void) -> libc::c_int>,
pub _read: Option<
unsafe extern "C" fn(_: *mut libc::c_void, _: *mut libc::c_char, _: libc::c_int)
-> libc::c_int,
>,
pub _seek:
Option<unsafe extern "C" fn(_: *mut libc::c_void, _: fpos_t, _: libc::c_int) -> fpos_t>,
pub _write: Option<
unsafe extern "C" fn(_: *mut libc::c_void, _: *const libc::c_char, _: libc::c_int)
-> libc::c_int,
>,
pub _ub: __sbuf,
pub _extra: *mut __sFILEX,
pub _ur: libc::c_int,
pub _ubuf: [libc::c_uchar; 3],
pub _nbuf: [libc::c_uchar; 1],
pub _lb: __sbuf,
pub _blksize: libc::c_int,
pub _offset: fpos_t,
}
pub type FILE = __sFILE;
/* #define the constants so we can check with #ifdef */
/* Error API */
pub type CborError = libc::c_int;
/* INT_MAX on two's complement machines */
pub const CborErrorInternalError: CborError = 2147483647;
pub const CborErrorOutOfMemory: CborError = -2147483648;
pub const CborErrorJsonNotImplemented: CborError = 1282;
pub const CborErrorJsonObjectKeyNotString: CborError = 1281;
/* errors in converting to JSON */
pub const CborErrorJsonObjectKeyIsAggregate: CborError = 1280;
pub const CborErrorUnsupportedType: CborError = 1026;
pub const CborErrorNestingTooDeep: CborError = 1025;
/* internal implementation errors */
pub const CborErrorDataTooLarge: CborError = 1024;
pub const CborErrorTooFewItems: CborError = 769;
/* encoder errors */
pub const CborErrorTooManyItems: CborError = 768;
pub const CborErrorMapKeysNotUnique: CborError = 523;
pub const CborErrorMapNotSorted: CborError = 522;
pub const CborErrorMapKeyNotString: CborError = 521;
pub const CborErrorOverlongEncoding: CborError = 520;
pub const CborErrorImproperValue: CborError = 519;
pub const CborErrorExcludedValue: CborError = 518;
pub const CborErrorExcludedType: CborError = 517;
pub const CborErrorInvalidUtf8TextString: CborError = 516;
pub const CborErrorDuplicateObjectKeys: CborError = 515;
pub const CborErrorInappropriateTagForType: CborError = 514;
pub const CborErrorUnknownTag: CborError = 513;
/* parser errors in strict mode parsing only */
pub const CborErrorUnknownSimpleType: CborError = 512;
/* types of value less than 32 encoded in two bytes */
pub const CborErrorIllegalSimpleType: CborError = 262;
pub const CborErrorIllegalNumber: CborError = 261;
/* type not allowed here */
pub const CborErrorIllegalType: CborError = 260;
/* can only happen in major type 7 */
pub const CborErrorUnknownType: CborError = 259;
pub const CborErrorUnexpectedBreak: CborError = 258;
pub const CborErrorUnexpectedEOF: CborError = 257;
/* parser errors streaming errors */
pub const CborErrorGarbageAtEnd: CborError = 256;
pub const CborErrorIO: CborError = 4;
pub const CborErrorAdvancePastEOF: CborError = 3;
/* request for length in array, map, or string with indeterminate length */
pub const CborErrorUnknownLength: CborError = 2;
/* errors in all modes */
pub const CborUnknownError: CborError = 1;
pub const CborNoError: CborError = 0;
pub type CborError_0 = CborError;
#[derive(Copy, Clone)]
#[repr(C)]
pub struct CborParser {
pub end: *const uint8_t,
pub flags: uint32_t,
}
pub type CborParser_0 = CborParser;
#[derive(Copy, Clone)]
#[repr(C)]
pub struct CborValue {
pub parser: *const CborParser_0,
pub ptr: *const uint8_t,
pub remaining: uint32_t,
pub extra: uint16_t,
pub type_0: uint8_t,
pub flags: uint8_t,
}
pub type CborValue_0 = CborValue;
/* Human-readable (dump) API */
pub type CborPrettyFlags = libc::c_uint;
pub const CborPrettyDefaultFlags: CborPrettyFlags = 2;
pub const CborPrettyMergeStringFragments: CborPrettyFlags = 0;
pub const CborPrettyShowStringFragments: CborPrettyFlags = 256;
pub const CborPrettyIndicateOverlongNumbers: CborPrettyFlags = 4;
/* deprecated */
pub const CborPrettyIndicateIndetermineLength: CborPrettyFlags = 2;
pub const CborPrettyIndicateIndeterminateLength: CborPrettyFlags = 2;
pub const CborPrettyTextualEncodingIndicators: CborPrettyFlags = 0;
pub const CborPrettyNumericEncodingIndicators: CborPrettyFlags = 1;
/* ***************************************************************************
**
** Copyright (C) 2015 Intel Corporation
**
** Permission is hereby granted, free of charge, to any person obtaining a copy
** of this software and associated documentation files (the "Software"), to deal
** in the Software without restriction, including without limitation the rights
** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
** copies of the Software, and to permit persons to whom the Software is
** furnished to do so, subject to the following conditions:
**
** The above copyright notice and this permission notice shall be included in
** all copies or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
** THE SOFTWARE.
**
****************************************************************************/
/* Conversion to JSON */
pub type CborToJsonFlags = libc::c_uint;
pub const CborConvertDefaultFlags: CborToJsonFlags = 0;
pub const CborConvertStringifyMapKeys: CborToJsonFlags = 8;
pub const CborConvertRequireMapStringKeys: CborToJsonFlags = 0;
pub const CborConvertByteStringsToBase64Url: CborToJsonFlags = 4;
pub const CborConvertObeyByteStringTags: CborToJsonFlags = 0;
pub const CborConvertIgnoreTags: CborToJsonFlags = 0;
pub const CborConvertTagsToObjects: CborToJsonFlags = 2;
pub const CborConvertAddMetadata: CborToJsonFlags = 1;
/* ***************************************************************************
**
** Copyright (C) 2015 Intel Corporation
**
** Permission is hereby granted, free of charge, to any person obtaining a copy
** of this software and associated documentation files (the "Software"), to deal
** in the Software without restriction, including without limitation the rights
** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
** copies of the Software, and to permit persons to whom the Software is
** furnished to do so, subject to the following conditions:
**
** The above copyright notice and this permission notice shall be included in
** all copies or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
** THE SOFTWARE.
**
****************************************************************************/
#[no_mangle]
pub unsafe extern "C" fn xrealloc(
mut old: *mut libc::c_void,
mut size: size_t,
mut fname: *const libc::c_char,
) -> *mut libc::c_void {
old = realloc(old, size);
if old.is_null() {
fprintf(
__stderrp,
b"%s: %s\n\x00" as *const u8 as *const libc::c_char,
fname,
strerror(*__error()),
);
exit(1i32);
} else {
return old;
};
}
#[no_mangle]
pub unsafe extern "C" fn printerror(mut err: CborError_0, mut fname: *const libc::c_char) -> () {
fprintf(
__stderrp,
b"%s: %s\n\x00" as *const u8 as *const libc::c_char,
fname,
cbor_error_string(err),
);
exit(1i32);
}
#[no_mangle]
pub unsafe extern "C" fn dumpFile(
mut in_0: *mut FILE,
mut fname: *const libc::c_char,
mut printJosn: bool,
mut flags: libc::c_int,
) -> () {
static mut chunklen: size_t = (16i32 * 1024i32) as size_t;
static mut bufsize: size_t = 0i32 as size_t;
static mut buffer: *mut uint8_t = 0 as *const uint8_t as *mut uint8_t;
let mut buflen: size_t = 0i32 as size_t;
loop {
if bufsize == buflen {
bufsize = (bufsize as libc::c_ulong).wrapping_add(chunklen) as size_t as size_t;
buffer = xrealloc(buffer as *mut libc::c_void, bufsize, fname) as *mut uint8_t
}
let mut n: size_t = fread(
buffer.offset(buflen as isize) as *mut libc::c_void,
1i32 as size_t,
bufsize.wrapping_sub(buflen),
in_0,
);
buflen = (buflen as libc::c_ulong).wrapping_add(n) as size_t as size_t;
if n == 0i32 as libc::c_ulong {
if !(0 == ferror(in_0)) {
fprintf(
__stderrp,
b"%s: %s\n\x00" as *const u8 as *const libc::c_char,
fname,
strerror(*__error()),
);
exit(1i32);
}
}
if !(0 == feof(in_0)) {
break;
}
}
let mut parser: CborParser_0 = CborParser {
end: 0 as *const uint8_t,
flags: 0,
};
let mut value: CborValue_0 = CborValue {
parser: 0 as *const CborParser_0,
ptr: 0 as *const uint8_t,
remaining: 0,
extra: 0,
type_0: 0,
flags: 0,
};
let mut err: CborError_0 =
cbor_parser_init(buffer, buflen, 0i32 as uint32_t, &mut parser, &mut value);
if 0 == err as u64 {
if printJosn {
err = cbor_value_to_json_advance(__stdoutp, &mut value, flags)
} else {
err = cbor_value_to_pretty_advance_flags(__stdoutp, &mut value, flags)
}
if 0 == err as u64 {
puts(b"\x00" as *const u8 as *const libc::c_char);
}
}
if 0 == err as u64 && value.ptr != buffer.offset(buflen as isize) {
err = CborErrorGarbageAtEnd
}
if 0 != err as u64 {
printerror(err, fname);
};
}
unsafe fn main_0(mut argc: libc::c_int, mut argv: *mut *mut libc::c_char) -> libc::c_int {
let mut printJson: bool = 0 != 0i32;
let mut json_flags: libc::c_int = CborConvertDefaultFlags as libc::c_int;
let mut cbor_flags: libc::c_int = CborPrettyDefaultFlags as libc::c_int;
let mut c: libc::c_int = 0;
loop {
c = getopt(
argc,
argv as *const *mut libc::c_char,
b"MOSUcjhfn\x00" as *const u8 as *const libc::c_char,
);
if !(c != -1i32) {
break;
}
match c {
99 => {
printJson = 0 != 0i32;
continue;
}
106 => {
printJson = 0 != 1i32;
continue;
}
102 => {
cbor_flags |= CborPrettyShowStringFragments as libc::c_int;
continue;
}
110 => {
cbor_flags |= CborPrettyIndicateIndeterminateLength as libc::c_int
| CborPrettyNumericEncodingIndicators as libc::c_int;
continue;
}
77 => {
json_flags |= CborConvertAddMetadata as libc::c_int;
continue;
}
79 => {
json_flags |= CborConvertTagsToObjects as libc::c_int;
continue;
}
83 => {
json_flags |= CborConvertStringifyMapKeys as libc::c_int;
continue;
}
85 => {
json_flags |= CborConvertByteStringsToBase64Url as libc::c_int;
continue;
}
63 => {
fprintf(
__stderrp,
b"Unknown option -%c.\n\x00" as *const u8 as *const libc::c_char,
optopt,
);
}
104 => {}
_ => {
/* fall through */
continue;
}
}
puts(b"Usage: cbordump [OPTION]... [FILE]...\nInterprets FILEs as CBOR binary data and dumps the content to stdout.\n\nOptions:\n -c Print a CBOR dump (see RFC 7049) (default)\n -j Print a JSON equivalent version\n -h Print this help output and exit\nWhen JSON output is active, the following options are recognized:\n -M Add metadata so converting back to CBOR is possible\n -O Convert CBOR tags to JSON objects\n -S Stringify non-text string map keys\n -U Convert all CBOR byte strings to Base64url regardless of tags\nWhen CBOR dump is active, the following options are recognized:\n -f Show text and byte string fragments\n -n Show overlong encoding of CBOR numbers and length\x00"
as *const u8 as *const libc::c_char);
return if c == '?' as i32 { 1i32 } else { 0i32 };
}
let mut fname: *mut *mut libc::c_char = argv.offset(optind as isize);
if (*fname).is_null() {
dumpFile(
__stdinp,
b"-\x00" as *const u8 as *const libc::c_char,
printJson,
if 0 != printJson as libc::c_int {
json_flags
} else {
cbor_flags
},
);
} else {
while !(*fname).is_null() {
let mut in_0: *mut FILE = fopen(*fname, b"rb\x00" as *const u8 as *const libc::c_char);
if in_0.is_null() {
perror(b"open\x00" as *const u8 as *const libc::c_char);
return 1i32;
} else {
dumpFile(
in_0,
*fname,
printJson,
if 0 != printJson as libc::c_int {
json_flags
} else {
cbor_flags
},
);
fclose(in_0);
fname = fname.offset(1isize)
}
}
}
return 0i32;
}
pub fn main() -> () {
let mut args: Vec<*mut libc::c_char> = Vec::new();
for arg in ::std::env::args() {
args.push(
::std::ffi::CString::new(arg)
.expect("Failed to convert argument into CString.")
.into_raw(),
);
}
args.push(::std::ptr::null_mut());
unsafe {
::std::process::exit(main_0(
(args.len() - 1) as libc::c_int,
args.as_mut_ptr() as *mut *mut libc::c_char,
) as i32)
}
}
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use async_channel::Receiver;
use async_channel::Sender;
use common_exception::Result;
use crate::runtime::Thread;
// Simple thread pool implementation,
// which can run more tasks on limited threads and wait for all tasks to finished.
pub struct ThreadPool {
tx: Sender<Box<dyn FnOnce() + Send + 'static>>,
}
pub struct TaskJoinHandler<T: Send> {
rx: Receiver<T>,
}
impl<T: Send> TaskJoinHandler<T> {
pub fn create(rx: Receiver<T>) -> TaskJoinHandler<T> {
TaskJoinHandler::<T> { rx }
}
pub fn join(&self) -> T {
self.rx.recv_blocking().unwrap()
}
}
impl ThreadPool {
pub fn create(threads: usize) -> Result<ThreadPool> {
let (tx, rx) = async_channel::unbounded::<Box<dyn FnOnce() + Send + 'static>>();
for _index in 0..threads {
let thread_rx = rx.clone();
Thread::spawn(move || {
while let Ok(task) = thread_rx.recv_blocking() {
task();
}
});
}
Ok(ThreadPool { tx })
}
pub fn execute<F, R>(&self, f: F) -> TaskJoinHandler<R>
where
F: FnOnce() -> R + Send + 'static,
R: Send + 'static,
{
let (tx, rx) = async_channel::bounded(1);
let _ = self.tx.send_blocking(Box::new(move || {
let _ = tx.send_blocking(f());
}));
TaskJoinHandler::create(rx)
}
}
|
//! File holding the FormHashMap type accepting variable parameters from a Rocket request
//! exposing a simplified Map type interface to access them
//!
//! Author: [Boris](mailto:boris@humanenginuity.com)
//! Version: 2.0
//!
//! ## Release notes
//! - v2.0 : refactored using serde_json Map & Value
//! - v1.1 : implemented Index trait, renamed old `new()` method into `from_application_data`, added method `from_json_data`
//! - v1.0 : creation
// =======================================================================
// ATTRIBUTES
// =======================================================================
#![allow(dead_code)]
// =======================================================================
// LIBRARY IMPORTS
// =======================================================================
use std::convert::AsRef;
use std::error::Error;
use std::fmt::Debug;
use std::marker::PhantomData;
use std::io::Read;
use std::ops::Index;
use rocket;
use rocket::{ Request, Data };
use rocket::data::FromData;
use rocket::http::Status;
use rocket::outcome::IntoOutcome;
use rocket::request::{ FromForm, FromFormValue, FormItems };
use serde_json;
use serde_json::Value;
use serde_json::map::Map;
use error::GenericError;
use traits::Pushable;
// =======================================================================
// STRUCT & TRAIT DEFINITION
// =======================================================================
/// A `FromData` type that creates a map of the key/value pairs from a
/// `x-www-form-urlencoded` or `json` form string
pub struct FormHashMap<'s> {
form_string: String,
map: Map<String, Value>,
_phantom: PhantomData<&'s str>,
}
// =======================================================================
// IMPLEMENTATION
// =======================================================================
impl<'s> FormHashMap<'s> {
/// Get a reference for the value (or values) associated with `key`.
pub fn get<T: AsRef<str>>(&self, key: T) -> Option<&Value> {
self.map.get(key.as_ref())
}
/// Returns the raw form string that was used to parse the encapsulated
/// object.
pub fn raw_form_string(&self) -> &str {
&self.form_string
}
/// Build a FormHashMap from application data (i.e. content type application/x-www-form-urlencoded)
/// Uses Rocket's `FormItems::from<'f>(&'f str)` to parse the form's String
fn from_application_data(form_string: String) -> Result<Self, GenericError> {
let long_lived_string: &'s str = unsafe {
::std::mem::transmute(form_string.as_str())
};
let mut items = FormItems::from(long_lived_string);
// Handle parsing or decode errors
let parsing_errors: Vec<_> = items.by_ref()
.map(|(key, value)| (key, String::from_form_value(value)))
.filter(|&(_, ref decoded_value)| decoded_value.is_err())
.collect();
if !parsing_errors.is_empty() {
return amiwo_error!( format!("::AMIWO::CONTRIB::ROCKET::FORM_HASHMAP::FROM_APPLICATION_DATA::WARNING Unable to parse form string {} [parsing errors = {:?}]", form_string, parsing_errors) );
}
if !items.completed() {
warn!("::AMIWO::CONTRIB::ROCKET::FORM_HASHMAP::FROM_APPLICATION_DATA::WARNING Form string {} couldn't be completely parsed", form_string);
}
Ok(FormHashMap {
form_string: form_string,
map: FormItems::from(long_lived_string)
.map(|(key, value)| (key, String::from_form_value(value)))
.filter(|&(_, ref decoded_value)| decoded_value.is_ok())
.fold(
Map::new(),
|mut map, (key, decoded_value)| {
map.entry(key).or_insert(Value::Null).push(Value::String(decoded_value.unwrap()));
map
}
),
_phantom: PhantomData,
})
}
/// Build a FormHashMap from JSON data (i.e. content type application/json)
/// Uses serde_json's `serde_json::from_str<'a, T>(&'a str)` to parse the form's String
fn from_json_data(form_string: String) -> Result<Self, GenericError> {
let long_lived_string: &'s str = unsafe {
::std::mem::transmute(form_string.as_str())
};
serde_json::from_str(long_lived_string)
.or_else(|err| amiwo_error!(
format!("::AMIWO::CONTRIB::ROCKET::FORM_HASHMAP::FROM_JSON_DATA::ERROR Error parsing string {} > {}", form_string, &err.description()),
GenericError::Serde(err)
)).and_then(|value : Value| {
if value.is_object() {
Ok(FormHashMap {
form_string: form_string,
map: value.as_object().unwrap().clone(),
_phantom: PhantomData,
})
} else {
amiwo_error!(format!(":AMIWO::CONTRIB::ROCKET::FORM_HASHMAP::FROM_JSON_DATA::ERROR Invalid JSON data {}", form_string))
}
})
}
// We'd like to have form objects have pointers directly to the form string.
// This means that the form string has to live at least as long as the form object. So,
// to enforce this, we store the form_string along with the form object.
//
// So far so good. Now, this means that the form_string can never be
// deallocated while the object is alive. That implies that the
// `form_string` value should never be moved away. We can enforce that
// easily by 1) not making `form_string` public, and 2) not exposing any
// `&mut self` methods that could modify `form_string`.
fn new(content_type: &str, form_string: String) -> Result<Self, GenericError> {
match content_type {
"application" => FormHashMap::from_application_data(form_string),
"json" => FormHashMap::from_json_data(form_string),
_ => amiwo_error!(format!("::AMIWO::CONTRIB::ROCKET::FORM_HASHMAP::NEW::ERROR Unsupported content type {}", content_type)),
}
}
}
// =======================================================================
// EXTERNAL TRAITS IMPLEMENTATION
// =======================================================================
/// Parses a `FormHashMap` from incoming POST/... form data.
///
/// - If the content type of the request data is not
/// `application/x-www-form-urlencoded` or `application/json`, `Forward`s the request.
/// - If the form string is malformed, a `Failure` with status code
/// `BadRequest` is returned.
/// - Finally, if reading the incoming stream fails, returns a `Failure` with status code
/// `InternalServerError`.
/// In all failure cases, the raw form string is returned if it was able to be retrieved from the incoming stream.
///
/// All relevant warnings and errors are written to the console
impl<'f> FromData for FormHashMap<'f> {
type Error = GenericError;
fn from_data(request: &Request, data: Data) -> rocket::data::Outcome<Self, Self::Error> {
if !request.content_type().map_or(false, |ct| ct.is_form() || ct.is_json()) {
error!("::AMIWO::CONTRIB::ROCKET::FORM_HASHMAP::FROM_DATA::WARNING Form data does not have application/x-www-form-urlencoded or application/json content type.");
return rocket::Outcome::Forward(data);
}
let content_type = request.content_type().map_or("unsupported content type", |ct| if ct.is_form() { "application" } else { "json" });
let size_limit = rocket::config::active()
.and_then(|c| c.extras.get(&("limits.".to_string() + content_type))) // TODO: remove placeholder when upgrading to rocket version > 0.2.6
// .and_then(|c| c.limits.get("application") // In next version
.and_then(|limit| limit.as_integer())
.unwrap_or_else(|| if content_type == "json" { 1<<20 } else { 32768 }) as u64;
let mut buffer = String::new();
data.open()
.take(size_limit)
.read_to_string(&mut buffer)
.or_else(|err| amiwo_error!(format!("::AMIWO::CONTRIB::ROCKET::FORM_HASHMAP::FROM_DATA::ERROR IO Error: {}", err.description())) )
.and_then(|_| FormHashMap::new(content_type, buffer))
.or_else(|error_message| {
error!("{}", error_message);
Err(error_message)
}).into_outcome() // Note: trait implemented by Rocket FromData for Result<S,E> `fn into_outcome(self, status: Status) -> Outcome<S, E>`
}
}
/// Parses a `FormHashMap` from incoming GET query strings.
///
/// - If the form string is malformed, a `Failure` with status code
/// `BadRequest` is returned.
/// - Finally, if reading the incoming stream fails, returns a `Failure` with status code
/// `InternalServerError`.
/// In all failure cases, the raw form string is returned if it was able to be retrieved from the incoming stream.
///
/// All relevant warnings and errors are written to the console
impl<'f> FromForm<'f> for FormHashMap<'f> {
/// The raw form string, if it was able to be retrieved from the request.
type Error = (Status, Option<GenericError>);
fn from_form_items(items: &mut FormItems<'f>) -> Result<Self, Self::Error> {
FormHashMap::from_application_data(items.inner_str().to_string())
.map(|map| {
info!("::AMIWO::CONTRIB::ROCKET::FORM_HASHMAP::FROM_FORM_ITEMS::INFO Successfully parsed input data => {:?}", map);
map
}).map_err(|invalid_string| {
error!("::AMIWO::CONTRIB::ROCKET::FORM_HASHMAP::FROM_FORM_ITEMS::ERROR The request's form string '{}' was malformed.", invalid_string);
( Status::BadRequest, Some(GenericError::Basic(format!("::AMIWO::CONTRIB::ROCKET::FORM_HASHMAP::FROM_FORM_ITEMS::ERROR The request's form string '{}' was malformed.", invalid_string))) )
})
}
}
/// Implement Debug displaying '<internal data holding structure>' from string: <parsed string>'
impl<'f> Debug for FormHashMap<'f> {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(f, "{:?} from string: {:?}", self.map, self.form_string)
}
}
/// Access an element of this type. Panics if the key is not defined
impl<'a, I: AsRef<str>> Index<I> for FormHashMap<'a> {
type Output = Value;
fn index(&self, index: I) -> &Self::Output {
&self.map[index.as_ref()]
}
}
// =======================================================================
// UNIT TESTS
// =======================================================================
#[cfg(test)]
mod tests {
#![allow(unmounted_route)]
#![allow(non_snake_case)]
use super::FormHashMap;
use rocket;
use rocket::testing::MockRequest;
use rocket::http::{ ContentType, Method, Status };
#[test]
fn FormHashMap_test_new() {
let form_string = "a=b1&a=b2&b=c";
match FormHashMap::from_application_data(form_string.to_string()) {
Ok(map) => {
assert_eq!(map.get("a"), Some(&json!(["b1", "b2"])));
assert_eq!(map.get("b"), Some(&json!("c")));
assert_eq!(map["b"], json!("c"));
assert_eq!(map["b".to_string()], json!("c"));
},
Err(invalid_string) => {
panic!("Unable to parse {}", invalid_string);
}
}
}
#[test]
fn FormHashMap_test_post_route() {
#[post("/test", data= "<params>")]
fn test_route(params: FormHashMap) -> &'static str {
assert_eq!(params.get("a"), Some(&json!(["b1", "b2"])));
assert_eq!(params.get("b"), Some(&json!("c")));
"It's working !"
}
let rocket = rocket::ignite()
.mount("/post", routes![test_route]);
let mut req = MockRequest::new(Method::Post, "/post/test")
.header(ContentType::Form)
.body("a=b1&a=b2&b=c");
let mut response = req.dispatch_with(&rocket);
let body_str = response.body().and_then(|b| b.into_string());
assert_eq!(response.status(), Status::Ok);
assert_eq!(body_str, Some("It's working !".to_string()));
}
#[test]
fn FormHashMap_test_get_route() {
#[get("/test?<params>")]
fn test_route(params: FormHashMap) -> &'static str {
assert_eq!(params.get("a"), Some(&json!(["b1", "b2"])));
assert_eq!(params.get("b"), Some(&json!("c")));
"It's working !"
}
let rocket = rocket::ignite()
.mount("/get", routes![test_route]);
let mut req = MockRequest::new(Method::Get, "/get/test?a=b1&a=b2&b=c");
let mut response = req.dispatch_with(&rocket);
let body_str = response.body().and_then(|b| b.into_string());
assert_eq!(response.status(), Status::Ok);
assert_eq!(body_str, Some("It's working !".to_string()));
}
#[test]
fn FormHashMap_test_get_qs_with_dot() {
#[get("/test?<params>")]
fn test_route(params: FormHashMap) -> &'static str {
assert_eq!(params.get("v"), Some(&json!("4.7.0")));
"It's working !"
}
let rocket = rocket::ignite()
.mount("/get", routes![test_route]);
let mut req = MockRequest::new(Method::Get, "/get/test?v=4.7.0");
let mut response = req.dispatch_with(&rocket);
let body_str = response.body().and_then(|b| b.into_string());
assert_eq!(response.status(), Status::Ok);
assert_eq!(body_str, Some("It's working !".to_string()));
}
// TODO: add test lifetime
} |
//! Intrinsics are instructions Falcon cannot model.
use crate::il::*;
use serde::{Deserialize, Serialize};
use std::fmt;
/// An Instrinsic is a lifted instruction Falcon cannot model.
#[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub struct Intrinsic {
mnemonic: String,
instruction_str: String,
arguments: Vec<Expression>,
written_expressions: Option<Vec<Expression>>,
read_expressions: Option<Vec<Expression>>,
bytes: Vec<u8>,
}
impl Intrinsic {
/// Create a new intrinsic instruction.
pub fn new<S: Into<String>, SS: Into<String>>(
mnemonic: S,
instruction_str: SS,
arguments: Vec<Expression>,
written_expressions: Option<Vec<Expression>>,
read_expressions: Option<Vec<Expression>>,
bytes: Vec<u8>,
) -> Intrinsic {
Intrinsic {
mnemonic: mnemonic.into(),
instruction_str: instruction_str.into(),
arguments,
written_expressions,
read_expressions,
bytes,
}
}
/// Get the mnemonic for the instruction this intrinsic represents.
pub fn mnemonic(&self) -> &str {
&self.mnemonic
}
/// Get the full disassembly string, mnemonic and operands, for the
/// instruction this intrinsic represents.
pub fn instruction_str(&self) -> &str {
&self.instruction_str
}
/// Get the arguments for the intrinsic. Intrinsic-dependent.
pub fn arguments(&self) -> &[Expression] {
&self.arguments
}
/// Get the expressions which are written by this intrinsic.
///
/// If this is None, the expressions written by this intrinsic are
/// undefined, and for soundness you should assume the intrinsic does
/// anything.
pub fn written_expressions(&self) -> Option<&[Expression]> {
self.written_expressions.as_deref()
}
/// Get a mutable reference to the expressions which are written by this
/// intrinsic.
///
/// Caveats for `written_expressions` apply here.
pub fn written_expressions_mut(&mut self) -> Option<&mut [Expression]> {
self.written_expressions.as_deref_mut()
}
/// Get the expressions which are read by this intrinsic.
///
/// If this is None, the expressions read by this intrinsic are
/// undefined, and for soundness you should assume the intrinsic reads
/// any expression.
pub fn read_expressions(&self) -> Option<&[Expression]> {
self.read_expressions.as_deref()
}
/// Get a mutable reference to the expressions which are read by this
/// intrinsic.
///
/// Caveats for `read_expressions` apply here.
pub fn read_expressions_mut(&mut self) -> Option<&mut [Expression]> {
self.read_expressions.as_deref_mut()
}
/// Get the scalars which are written by this intrinsic.
///
/// These are the scalars contained in the written expressions. Caveats for
/// `written_expressions` apply here.
pub fn scalars_written(&self) -> Option<Vec<&Scalar>> {
self.written_expressions().map(|written_expressions| {
written_expressions
.iter()
.flat_map(|expression| expression.scalars())
.collect::<Vec<&Scalar>>()
})
}
/// Get a mutable reference to the scalars written by this intrinsic.
///
/// This is a mutable reference to the scalars contained in the written
/// expressions. Caveats for `written_expressions` apply here.
pub fn scalars_written_mut(&mut self) -> Option<Vec<&mut Scalar>> {
self.written_expressions_mut().map(|written_expressions| {
written_expressions
.iter_mut()
.flat_map(|expression| expression.scalars_mut())
.collect::<Vec<&mut Scalar>>()
})
}
/// Get the scalared read by this intrinsic.
///
/// These are the scalars in the expressions read by this intrinsic.
/// Caveats for `read_expressions` apply here.
pub fn scalars_read(&self) -> Option<Vec<&Scalar>> {
self.read_expressions().map(|read_expressions| {
read_expressions
.iter()
.flat_map(|expression| expression.scalars())
.collect::<Vec<&Scalar>>()
})
}
/// Get a mutable reference to the scalars written by this inrinsic.
///
/// These are the scalars in the expression written by this intrinsic.
/// Caveats for `read_expressions` apply here.
pub fn scalars_read_mut(&mut self) -> Option<Vec<&mut Scalar>> {
self.read_expressions_mut().map(|read_expressions| {
read_expressions
.iter_mut()
.flat_map(|expression| expression.scalars_mut())
.collect::<Vec<&mut Scalar>>()
})
}
/// Get the bytes which make up this instruction.
///
/// These are the undisassembled bytes, as found in the lifted binary.
pub fn bytes(&self) -> &[u8] {
&self.bytes
}
}
impl fmt::Display for Intrinsic {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let bytes = self
.bytes()
.iter()
.map(|byte| format!("{:02x}", byte))
.collect::<Vec<String>>()
.join("");
write!(f, "{} {}", bytes, self.instruction_str())
}
}
|
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtWidgets/qcolumnview.h
// dst-file: /src/widgets/qcolumnview.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block begin =>
// <= main block end
// use block begin =>
use super::qabstractitemview::*; // 773
use std::ops::Deref;
use super::qwidget::*; // 773
use super::super::core::qpoint::*; // 771
use super::super::core::qabstractitemmodel::*; // 771
use super::super::core::qobjectdefs::*; // 771
use super::super::core::qsize::*; // 771
// use super::qlist::*; // 775
use super::super::core::qitemselectionmodel::*; // 771
use super::super::core::qrect::*; // 771
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QColumnView_Class_Size() -> c_int;
// proto: void QColumnView::QColumnView(QWidget * parent);
fn C_ZN11QColumnViewC2EP7QWidget(arg0: *mut c_void) -> u64;
// proto: void QColumnView::selectAll();
fn C_ZN11QColumnView9selectAllEv(qthis: u64 /* *mut c_void*/);
// proto: void QColumnView::setPreviewWidget(QWidget * widget);
fn C_ZN11QColumnView16setPreviewWidgetEP7QWidget(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QModelIndex QColumnView::indexAt(const QPoint & point);
fn C_ZNK11QColumnView7indexAtERK6QPoint(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void;
// proto: const QMetaObject * QColumnView::metaObject();
fn C_ZNK11QColumnView10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QSize QColumnView::sizeHint();
fn C_ZNK11QColumnView8sizeHintEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QList<int> QColumnView::columnWidths();
fn C_ZNK11QColumnView12columnWidthsEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QColumnView::setResizeGripsVisible(bool visible);
fn C_ZN11QColumnView21setResizeGripsVisibleEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: bool QColumnView::resizeGripsVisible();
fn C_ZNK11QColumnView18resizeGripsVisibleEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QColumnView::setModel(QAbstractItemModel * model);
fn C_ZN11QColumnView8setModelEP18QAbstractItemModel(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QColumnView::setRootIndex(const QModelIndex & index);
fn C_ZN11QColumnView12setRootIndexERK11QModelIndex(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QWidget * QColumnView::previewWidget();
fn C_ZNK11QColumnView13previewWidgetEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QColumnView::setSelectionModel(QItemSelectionModel * selectionModel);
fn C_ZN11QColumnView17setSelectionModelEP19QItemSelectionModel(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QRect QColumnView::visualRect(const QModelIndex & index);
fn C_ZNK11QColumnView10visualRectERK11QModelIndex(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void;
// proto: void QColumnView::~QColumnView();
fn C_ZN11QColumnViewD2Ev(qthis: u64 /* *mut c_void*/);
fn QColumnView_SlotProxy_connect__ZN11QColumnView19updatePreviewWidgetERK11QModelIndex(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
} // <= ext block end
// body block begin =>
// class sizeof(QColumnView)=1
#[derive(Default)]
pub struct QColumnView {
qbase: QAbstractItemView,
pub qclsinst: u64 /* *mut c_void*/,
pub _updatePreviewWidget: QColumnView_updatePreviewWidget_signal,
}
impl /*struct*/ QColumnView {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QColumnView {
return QColumnView{qbase: QAbstractItemView::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
}
}
impl Deref for QColumnView {
type Target = QAbstractItemView;
fn deref(&self) -> &QAbstractItemView {
return & self.qbase;
}
}
impl AsRef<QAbstractItemView> for QColumnView {
fn as_ref(& self) -> & QAbstractItemView {
return & self.qbase;
}
}
// proto: void QColumnView::QColumnView(QWidget * parent);
impl /*struct*/ QColumnView {
pub fn new<T: QColumnView_new>(value: T) -> QColumnView {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QColumnView_new {
fn new(self) -> QColumnView;
}
// proto: void QColumnView::QColumnView(QWidget * parent);
impl<'a> /*trait*/ QColumnView_new for (Option<&'a QWidget>) {
fn new(self) -> QColumnView {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QColumnViewC2EP7QWidget()};
let ctysz: c_int = unsafe{QColumnView_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = (if self.is_none() {0} else {self.unwrap().qclsinst}) as *mut c_void;
let qthis: u64 = unsafe {C_ZN11QColumnViewC2EP7QWidget(arg0)};
let rsthis = QColumnView{qbase: QAbstractItemView::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: void QColumnView::selectAll();
impl /*struct*/ QColumnView {
pub fn selectAll<RetType, T: QColumnView_selectAll<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.selectAll(self);
// return 1;
}
}
pub trait QColumnView_selectAll<RetType> {
fn selectAll(self , rsthis: & QColumnView) -> RetType;
}
// proto: void QColumnView::selectAll();
impl<'a> /*trait*/ QColumnView_selectAll<()> for () {
fn selectAll(self , rsthis: & QColumnView) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QColumnView9selectAllEv()};
unsafe {C_ZN11QColumnView9selectAllEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QColumnView::setPreviewWidget(QWidget * widget);
impl /*struct*/ QColumnView {
pub fn setPreviewWidget<RetType, T: QColumnView_setPreviewWidget<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setPreviewWidget(self);
// return 1;
}
}
pub trait QColumnView_setPreviewWidget<RetType> {
fn setPreviewWidget(self , rsthis: & QColumnView) -> RetType;
}
// proto: void QColumnView::setPreviewWidget(QWidget * widget);
impl<'a> /*trait*/ QColumnView_setPreviewWidget<()> for (&'a QWidget) {
fn setPreviewWidget(self , rsthis: & QColumnView) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QColumnView16setPreviewWidgetEP7QWidget()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN11QColumnView16setPreviewWidgetEP7QWidget(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QModelIndex QColumnView::indexAt(const QPoint & point);
impl /*struct*/ QColumnView {
pub fn indexAt<RetType, T: QColumnView_indexAt<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.indexAt(self);
// return 1;
}
}
pub trait QColumnView_indexAt<RetType> {
fn indexAt(self , rsthis: & QColumnView) -> RetType;
}
// proto: QModelIndex QColumnView::indexAt(const QPoint & point);
impl<'a> /*trait*/ QColumnView_indexAt<QModelIndex> for (&'a QPoint) {
fn indexAt(self , rsthis: & QColumnView) -> QModelIndex {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QColumnView7indexAtERK6QPoint()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZNK11QColumnView7indexAtERK6QPoint(rsthis.qclsinst, arg0)};
let mut ret1 = QModelIndex::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: const QMetaObject * QColumnView::metaObject();
impl /*struct*/ QColumnView {
pub fn metaObject<RetType, T: QColumnView_metaObject<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.metaObject(self);
// return 1;
}
}
pub trait QColumnView_metaObject<RetType> {
fn metaObject(self , rsthis: & QColumnView) -> RetType;
}
// proto: const QMetaObject * QColumnView::metaObject();
impl<'a> /*trait*/ QColumnView_metaObject<QMetaObject> for () {
fn metaObject(self , rsthis: & QColumnView) -> QMetaObject {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QColumnView10metaObjectEv()};
let mut ret = unsafe {C_ZNK11QColumnView10metaObjectEv(rsthis.qclsinst)};
let mut ret1 = QMetaObject::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QSize QColumnView::sizeHint();
impl /*struct*/ QColumnView {
pub fn sizeHint<RetType, T: QColumnView_sizeHint<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.sizeHint(self);
// return 1;
}
}
pub trait QColumnView_sizeHint<RetType> {
fn sizeHint(self , rsthis: & QColumnView) -> RetType;
}
// proto: QSize QColumnView::sizeHint();
impl<'a> /*trait*/ QColumnView_sizeHint<QSize> for () {
fn sizeHint(self , rsthis: & QColumnView) -> QSize {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QColumnView8sizeHintEv()};
let mut ret = unsafe {C_ZNK11QColumnView8sizeHintEv(rsthis.qclsinst)};
let mut ret1 = QSize::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QList<int> QColumnView::columnWidths();
impl /*struct*/ QColumnView {
pub fn columnWidths<RetType, T: QColumnView_columnWidths<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.columnWidths(self);
// return 1;
}
}
pub trait QColumnView_columnWidths<RetType> {
fn columnWidths(self , rsthis: & QColumnView) -> RetType;
}
// proto: QList<int> QColumnView::columnWidths();
impl<'a> /*trait*/ QColumnView_columnWidths<u64> for () {
fn columnWidths(self , rsthis: & QColumnView) -> u64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QColumnView12columnWidthsEv()};
let mut ret = unsafe {C_ZNK11QColumnView12columnWidthsEv(rsthis.qclsinst)};
return ret as u64; // 5
// return 1;
}
}
// proto: void QColumnView::setResizeGripsVisible(bool visible);
impl /*struct*/ QColumnView {
pub fn setResizeGripsVisible<RetType, T: QColumnView_setResizeGripsVisible<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setResizeGripsVisible(self);
// return 1;
}
}
pub trait QColumnView_setResizeGripsVisible<RetType> {
fn setResizeGripsVisible(self , rsthis: & QColumnView) -> RetType;
}
// proto: void QColumnView::setResizeGripsVisible(bool visible);
impl<'a> /*trait*/ QColumnView_setResizeGripsVisible<()> for (i8) {
fn setResizeGripsVisible(self , rsthis: & QColumnView) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QColumnView21setResizeGripsVisibleEb()};
let arg0 = self as c_char;
unsafe {C_ZN11QColumnView21setResizeGripsVisibleEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: bool QColumnView::resizeGripsVisible();
impl /*struct*/ QColumnView {
pub fn resizeGripsVisible<RetType, T: QColumnView_resizeGripsVisible<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.resizeGripsVisible(self);
// return 1;
}
}
pub trait QColumnView_resizeGripsVisible<RetType> {
fn resizeGripsVisible(self , rsthis: & QColumnView) -> RetType;
}
// proto: bool QColumnView::resizeGripsVisible();
impl<'a> /*trait*/ QColumnView_resizeGripsVisible<i8> for () {
fn resizeGripsVisible(self , rsthis: & QColumnView) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QColumnView18resizeGripsVisibleEv()};
let mut ret = unsafe {C_ZNK11QColumnView18resizeGripsVisibleEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QColumnView::setModel(QAbstractItemModel * model);
impl /*struct*/ QColumnView {
pub fn setModel<RetType, T: QColumnView_setModel<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setModel(self);
// return 1;
}
}
pub trait QColumnView_setModel<RetType> {
fn setModel(self , rsthis: & QColumnView) -> RetType;
}
// proto: void QColumnView::setModel(QAbstractItemModel * model);
impl<'a> /*trait*/ QColumnView_setModel<()> for (&'a QAbstractItemModel) {
fn setModel(self , rsthis: & QColumnView) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QColumnView8setModelEP18QAbstractItemModel()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN11QColumnView8setModelEP18QAbstractItemModel(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QColumnView::setRootIndex(const QModelIndex & index);
impl /*struct*/ QColumnView {
pub fn setRootIndex<RetType, T: QColumnView_setRootIndex<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setRootIndex(self);
// return 1;
}
}
pub trait QColumnView_setRootIndex<RetType> {
fn setRootIndex(self , rsthis: & QColumnView) -> RetType;
}
// proto: void QColumnView::setRootIndex(const QModelIndex & index);
impl<'a> /*trait*/ QColumnView_setRootIndex<()> for (&'a QModelIndex) {
fn setRootIndex(self , rsthis: & QColumnView) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QColumnView12setRootIndexERK11QModelIndex()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN11QColumnView12setRootIndexERK11QModelIndex(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QWidget * QColumnView::previewWidget();
impl /*struct*/ QColumnView {
pub fn previewWidget<RetType, T: QColumnView_previewWidget<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.previewWidget(self);
// return 1;
}
}
pub trait QColumnView_previewWidget<RetType> {
fn previewWidget(self , rsthis: & QColumnView) -> RetType;
}
// proto: QWidget * QColumnView::previewWidget();
impl<'a> /*trait*/ QColumnView_previewWidget<QWidget> for () {
fn previewWidget(self , rsthis: & QColumnView) -> QWidget {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QColumnView13previewWidgetEv()};
let mut ret = unsafe {C_ZNK11QColumnView13previewWidgetEv(rsthis.qclsinst)};
let mut ret1 = QWidget::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QColumnView::setSelectionModel(QItemSelectionModel * selectionModel);
impl /*struct*/ QColumnView {
pub fn setSelectionModel<RetType, T: QColumnView_setSelectionModel<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setSelectionModel(self);
// return 1;
}
}
pub trait QColumnView_setSelectionModel<RetType> {
fn setSelectionModel(self , rsthis: & QColumnView) -> RetType;
}
// proto: void QColumnView::setSelectionModel(QItemSelectionModel * selectionModel);
impl<'a> /*trait*/ QColumnView_setSelectionModel<()> for (&'a QItemSelectionModel) {
fn setSelectionModel(self , rsthis: & QColumnView) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QColumnView17setSelectionModelEP19QItemSelectionModel()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN11QColumnView17setSelectionModelEP19QItemSelectionModel(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QRect QColumnView::visualRect(const QModelIndex & index);
impl /*struct*/ QColumnView {
pub fn visualRect<RetType, T: QColumnView_visualRect<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.visualRect(self);
// return 1;
}
}
pub trait QColumnView_visualRect<RetType> {
fn visualRect(self , rsthis: & QColumnView) -> RetType;
}
// proto: QRect QColumnView::visualRect(const QModelIndex & index);
impl<'a> /*trait*/ QColumnView_visualRect<QRect> for (&'a QModelIndex) {
fn visualRect(self , rsthis: & QColumnView) -> QRect {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QColumnView10visualRectERK11QModelIndex()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZNK11QColumnView10visualRectERK11QModelIndex(rsthis.qclsinst, arg0)};
let mut ret1 = QRect::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QColumnView::~QColumnView();
impl /*struct*/ QColumnView {
pub fn free<RetType, T: QColumnView_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QColumnView_free<RetType> {
fn free(self , rsthis: & QColumnView) -> RetType;
}
// proto: void QColumnView::~QColumnView();
impl<'a> /*trait*/ QColumnView_free<()> for () {
fn free(self , rsthis: & QColumnView) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QColumnViewD2Ev()};
unsafe {C_ZN11QColumnViewD2Ev(rsthis.qclsinst)};
// return 1;
}
}
#[derive(Default)] // for QColumnView_updatePreviewWidget
pub struct QColumnView_updatePreviewWidget_signal{poi:u64}
impl /* struct */ QColumnView {
pub fn updatePreviewWidget(&self) -> QColumnView_updatePreviewWidget_signal {
return QColumnView_updatePreviewWidget_signal{poi:self.qclsinst};
}
}
impl /* struct */ QColumnView_updatePreviewWidget_signal {
pub fn connect<T: QColumnView_updatePreviewWidget_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QColumnView_updatePreviewWidget_signal_connect {
fn connect(self, sigthis: QColumnView_updatePreviewWidget_signal);
}
// updatePreviewWidget(const class QModelIndex &)
extern fn QColumnView_updatePreviewWidget_signal_connect_cb_0(rsfptr:fn(QModelIndex), arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsarg0 = QModelIndex::inheritFrom(arg0 as u64);
rsfptr(rsarg0);
}
extern fn QColumnView_updatePreviewWidget_signal_connect_cb_box_0(rsfptr_raw:*mut Box<Fn(QModelIndex)>, arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = QModelIndex::inheritFrom(arg0 as u64);
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QColumnView_updatePreviewWidget_signal_connect for fn(QModelIndex) {
fn connect(self, sigthis: QColumnView_updatePreviewWidget_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QColumnView_updatePreviewWidget_signal_connect_cb_0 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QColumnView_SlotProxy_connect__ZN11QColumnView19updatePreviewWidgetERK11QModelIndex(arg0, arg1, arg2)};
}
}
impl /* trait */ QColumnView_updatePreviewWidget_signal_connect for Box<Fn(QModelIndex)> {
fn connect(self, sigthis: QColumnView_updatePreviewWidget_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QColumnView_updatePreviewWidget_signal_connect_cb_box_0 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QColumnView_SlotProxy_connect__ZN11QColumnView19updatePreviewWidgetERK11QModelIndex(arg0, arg1, arg2)};
}
}
// <= body block end
|
use std::{unimplemented, vec};
use utils::Vector2;
// #[test]
pub fn run() {
let input = read_input(include_str!("input/day12.txt"));
// println!("{:?}", input);
println!("{}", exercise_1(&input));
println!("{}", exercise_2(&input));
}
pub fn read_input(input: &str) -> Vec<(char, isize)> {
input
.lines()
.map(|x| (x[0..1].chars().next().unwrap(), x[1..].parse().unwrap()))
.collect::<Vec<_>>()
}
fn exercise_1(input: &Vec<(char, isize)>) -> isize {
let ship = input
.iter()
.fold((Vector2(0, 0), 0isize), |(ship, dir), (c, val)| match c {
'N' => (ship + Vector2(0, -val), dir),
'S' => (ship + Vector2(0, *val), dir),
'E' => (ship + Vector2(*val, 0), dir),
'W' => (ship + Vector2(-val, 0), dir),
'L' => (ship, dir - *val),
'R' => (ship, dir + *val),
'F' => match dir.rem_euclid(360) {
0 => (ship + Vector2(*val, 0), dir),
90 => (ship + Vector2(0, *val), dir),
180 => (ship + Vector2(-val, 0), dir),
270 => (ship + Vector2(0, -val), dir),
_ => unreachable!(dir.rem_euclid(360)),
},
_ => unreachable!(),
})
.0;
println!("{:?}", ship);
ship.0.abs() + ship.1.abs()
}
fn exercise_2(input: &Vec<(char, isize)>) -> isize {
let rotate_90 = [[0, -1], [1, 0]];
let rotate_180 = [[-1, 0], [0, -1]];
let rotate_270 = [[0, 1], [-1, 0]];
let waypoint = input
.iter()
.fold(
(Vector2(0, 0), Vector2(10, -1)),
|(ship, waypoint), (c, val)| match (c, val) {
('N', _) => (ship, waypoint + Vector2(0, -val)),
('S', _) => (ship, waypoint + Vector2(0, *val)),
('E', _) => (ship, waypoint + Vector2(*val, 0)),
('W', _) => (ship, waypoint + Vector2(-val, 0)),
('L', 90) => (ship, waypoint * rotate_90),
('L', 180) => (ship, waypoint * rotate_180),
('L', 270) => (ship, waypoint * rotate_270),
('R', 90) => (ship, waypoint * rotate_270),
('R', 180) => (ship, waypoint * rotate_180),
('R', 270) => (ship, waypoint * rotate_90),
('F', _) => (ship + waypoint * *val, waypoint),
_ => unreachable!(),
},
)
.0;
println!("{:?}", waypoint);
waypoint.0.abs() + waypoint.1.abs()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test::Bencher;
#[test]
fn d12p1_test() {
let input = read_input(include_str!("input/day12.txt"));
assert_eq!(1007, exercise_1(&input));
}
#[test]
fn d12p2_test() {
let input = read_input(include_str!("input/day12.txt"));
assert_eq!(41212, exercise_2(&input));
}
#[bench]
fn d12_bench_parse(b: &mut Bencher) {
b.iter(|| read_input(include_str!("input/day12.txt")));
}
#[bench]
fn d12_bench_ex1(b: &mut Bencher) {
let input = read_input(include_str!("input/day12.txt"));
b.iter(|| exercise_1(&input));
}
#[bench]
fn d12_bench_ex2(b: &mut Bencher) {
let input = read_input(include_str!("input/day12.txt"));
b.iter(|| exercise_2(&input));
}
}
|
use super::{Fence, Op, Pctr, RawProgram, ValueDecoder};
use crate::index::*;
use crate::memory::{Loc, LocArray, Val};
use std::hash::Hash;
pub enum Step<P: State> {
Return {
val: P::Value,
},
Ignore,
Fence {
kind: Fence,
next: P,
},
Read {
loc: Loc,
is_acquire: bool,
is_update: bool,
next: P::Read,
},
Write {
loc: Loc,
val: P::Value,
is_release: bool,
is_update: bool,
next: P,
},
CancelUpdate {
loc: Loc,
next: P,
},
}
pub trait State: Sized + Clone + Eq + Hash {
type Value: Clone + Eq + Ord + Hash;
type Read: ReadStep<Self>;
fn next(&self) -> Step<Self>;
}
pub trait ReadStep<P: State> {
fn reads(&self, v: &P::Value) -> P;
}
pub struct Compiler<P: State> {
states: ISet<Pctr, P>,
ops: Vec<Step<P>>,
}
impl<P: State> Compiler<P> {
pub fn new() -> Self {
Self {
states: ISet::new(),
ops: Vec::new(),
}
}
pub fn state(&mut self, q: P) -> Pctr {
match self.states.entry(&q) {
ISetEntry::Occupied(e) => e.index(),
ISetEntry::Vacant(e) => {
let step = q.next();
self.ops.push(step);
e.insert(q).index()
}
}
}
fn new_value(&mut self, opn: usize, loc: Loc, vals: &mut ISet<Val, P::Value>, val: P::Value) {
let mut vali = vals.len();
if vals.check_insert(val).is_err() {
return;
}
let ops: Vec<&P::Read> = self.ops[0..opn]
.iter()
.filter_map(|op| {
if let Step::Read {
loc: loc2, next, ..
} = op
{
if *loc2 != loc {
return None;
}
Some(next)
} else {
None
}
})
.collect();
let mut states = Vec::new();
while vali < vals.len() {
let i = vali.grow();
let val = vals.at(i).clone();
for next in ops.iter() {
states.push(next.reads(&val));
}
}
for st in states {
self.state(st);
}
}
pub fn compile(
mut self,
locs: Array<Loc, (String, P::Value)>,
) -> (RawProgram, ValueDecoder<P::Value>) {
let mut ret_vals = ISet::<Val, P::Value>::new();
let mut loc_vals = locs.map(|_, (_, v)| {
let mut r = ISet::<Val, P::Value>::new();
let ins = r.insert(v.clone());
assert!(ins == Val::ZERO);
r
});
let loc_names = locs.map_into(|_, (n, _)| n);
let mut opi = 0;
while opi < self.ops.len() {
match &self.ops[opi] {
Step::Return { .. } => {}
Step::Ignore => {}
Step::Fence { next, .. } | Step::CancelUpdate { next, .. } => {
let next = P::clone(next);
self.state(next);
}
Step::Read { loc, next, .. } => {
let loc = *loc;
for next in loc_vals[loc].values().map(|_, val| next.reads(val)) {
self.state(next);
}
}
Step::Write { loc, val, next, .. } => {
let loc = *loc;
let val = val.clone();
let next = P::clone(next);
let _ = self.state(next);
self.new_value(opi, loc, &mut loc_vals[loc], val);
}
}
opi += 1;
}
let Self { ops, states } = self;
let code: Vec<_> = ops
.into_iter()
.map(|op| match op {
Step::Return { val } => Op::Return {
val: ret_vals.insert(val),
},
Step::Ignore => Op::Ignore,
Step::Fence { kind, next } => Op::Fence {
kind,
next: states.get(&next).unwrap(),
},
Step::Read {
loc,
is_acquire,
is_update,
next,
} => {
let vals = loc_vals[loc].values();
Op::Read {
loc,
is_acquire,
is_update,
next: vals.map(|_, v| states.get(&next.reads(v)).unwrap()),
}
}
Step::Write {
loc,
is_update,
is_release,
val,
next,
} => {
let next = states.get(&next).unwrap();
let val = loc_vals[loc].get(&val).unwrap();
Op::Write {
loc,
is_update,
is_release,
val,
next,
}
}
Step::CancelUpdate { loc, next } => {
let next = states.get(&next).unwrap();
Op::CancelUpdate { loc, next }
}
})
.collect();
let prog = RawProgram {
code: Array::new_vec(code),
loc_range: LocArray::new(|i| {
if loc_vals.len() > i {
loc_vals[i].len()
} else {
Length::ZERO
}
}),
};
let dec = ValueDecoder {
ret: ret_vals.into_values(),
loc_names,
loc: loc_vals.map_into(|_, v| v.into_values()),
};
(prog, dec)
}
}
|
use std::ops;
/// A bounded integer.
///
/// This has two value parameter, respectively representing an upper and a lower bound.
pub struct BoundedInt<const lower: usize, const upper: usize>
// Compile time constraints.
where lower <= upper {
/// The inner runtime value.
n: usize,
}
// To see how this holds the `where` clause above, see the section on `identities`.
impl<const n: usize> BoundedInt<n, n> {
fn new() -> Self {
BoundedInt {
n: n,
}
}
}
/// Addition of two `BoundedInt` will simply add their bounds.
///
/// We check for overflow making it statically overflow-free calculations.
impl<const upper_a: usize,
const lower_a: usize,
const upper_b: usize,
const lower_b: usize> ops::Add<BoundedInt<lower_b, upper_b>> for BoundedInt<lower_a, upper_a>
// We have to satisfy the constraints set out in the struct definition.
where lower_a <= upper_a,
lower_b <= upper_b,
// Check for overflow by some `const fn`.
is_overflow_safe(upper_a, upper_b) {
// These parameters are constant expression.
type Output = BoundedInt<lower_a + lower_b, upper_a + upper_b>;
fn add(self, rhs: BoundedInt<lower_b, upper_b>) -> Self::Output {
BoundedInt {
n: self.n + rhs.n,
}
}
}
/// Multiplication of two `BoundedInt` will simply multiply their bounds.
///
/// We check for overflow making it statically overflow-free calculations.
impl<const upper_a: usize,
const lower_a: usize,
const upper_b: usize,
const lower_b: usize> ops::Mul<BoundedInt<lower_b, upper_b>> for BoundedInt<lower_a, upper_a>
// We have to satisfy the constraints set out in the struct definition.
where lower_a <= upper_a,
lower_b <= upper_b,
// Check for overflow by some `const fn`.
is_overflow_safe_mul(upper_a, upper_b) {
// These parameters are constant expression.
type Output = BoundedInt<lower_a * lower_b, upper_a * upper_b>;
fn mul(self, rhs: BoundedInt<lower_b, upper_b>) -> Self::Output {
BoundedInt {
n: self.n * rhs.n,
}
}
}
impl<const upper_a: usize,
const lower_a: usize,
const upper_b: usize,
const lower_b: usize> From<BoundedInt<lower_b, upper_b>> for BoundedInt<lower_a, upper_a>
where lower_a <= upper_a,
lower_b <= upper_b,
// We will only extend the bound, never shrink it without runtime
// checks, thus we add this clause:
lower_b <= lower_a && upper_b >= upper_a {
fn from(from: BoundedInt<lower_b, upper_b>) -> Self {
BoundedInt {
n: from.n,
}
}
}
|
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn hello() -> String {
"Hello wasm".to_owned()
}
|
use crate::utils::*;
// choose
#[inline(always)]
fn ch(x: u32, y: u32, z: u32) -> u32 {
((x) & (y)) ^ (!(x) & (z))
}
// majority
#[inline(always)]
fn maj(x: u32, y: u32, z: u32) -> u32 {
((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z))
}
#[inline(always)]
fn ep0(x: u32) -> u32 {
u32::rotate_right(u32::rotate_right(u32::rotate_right(x, 9) ^ x, 11) ^ x, 2)
}
#[inline(always)]
fn ep1(x: u32) -> u32 {
u32::rotate_right(u32::rotate_right(u32::rotate_right(x, 14) ^ x, 5) ^ x, 6)
}
#[inline(always)]
fn sig0(x: i32) -> i32 {
i32::rotate_right(x, 7) ^ i32::rotate_right(x, 18) ^ (((x as u32) >> 3) as i32)
}
#[inline(always)]
fn sig1(x: i32) -> i32 {
i32::rotate_right(x, 17) ^ i32::rotate_right(x, 19) ^ (((x as u32) >> 10) as i32)
}
/// This struct represents a SHA256 state, which includes the result.
pub struct Sha256 {
// This field will have the hashing result.
pub hash: [u8; 32],
data: [u8; 64],
state: [u32; 8],
len: u32,
nbits: u32,
}
macro_rules! SHA256_W_ASSIGN {
($self:ident,$i:expr,$w:expr) => {
// NOTE: better performance!
$w = u32::from_be_bytes(unsafe { *(&$self.data[$i] as *const u8 as *const [u8; 4]) });
};
}
macro_rules! SHA256_FUNCTION_16 {
($self:ident,$a:expr,$b:expr,$c:expr,$d:expr,$e:expr,$f:expr,$g:expr,$h:expr,$i:expr,$w:expr,$j:expr) => {
let temp1 = $h
.wrapping_add(ep1($e))
.wrapping_add(ch($e, $f, $g))
.wrapping_add(K[$i])
.wrapping_add($w);
let temp2 = ep0($a).wrapping_add(maj($a, $b, $c));
$h = $g;
$g = $f;
$f = $e;
$e = $d.wrapping_add(temp1);
$d = $c;
$c = $b;
$b = $a;
$a = temp1.wrapping_add(temp2);
};
}
macro_rules! SHA256_FUNCTION_48 {
($a:expr,$b:expr,$c:expr,$d:expr,$e:expr,$f:expr,$g:expr,$h:expr,$w1:expr,$w2:expr,$w3:expr,$w4:expr,$i:expr) => {
$w1 = sig1($w2 as i32)
.wrapping_add($w3 as i32)
.wrapping_add(sig0($w4 as i32))
.wrapping_add($w1 as i32) as u32;
let temp1 = $h
.wrapping_add(ep1($e))
.wrapping_add(ch($e, $f, $g))
.wrapping_add(K[$i])
.wrapping_add($w1);
let temp2 = ep0($a).wrapping_add(maj($a, $b, $c));
$h = $g;
$g = $f;
$f = $e;
$e = $d.wrapping_add(temp1);
$d = $c;
$c = $b;
$b = $a;
$a = temp1.wrapping_add(temp2);
};
}
impl Sha256 {
fn transform(&mut self) {
let mut w0: u32;
let mut w1: u32;
let mut w2: u32;
let mut w3: u32;
let mut w4: u32;
let mut w5: u32;
let mut w6: u32;
let mut w7: u32;
let mut w8: u32;
let mut w9: u32;
let mut w10: u32;
let mut w11: u32;
let mut w12: u32;
let mut w13: u32;
let mut w14: u32;
let mut w15: u32;
let mut a: u32 = self.state[0];
let mut b: u32 = self.state[1];
let mut c: u32 = self.state[2];
let mut d: u32 = self.state[3];
let mut e: u32 = self.state[4];
let mut f: u32 = self.state[5];
let mut g: u32 = self.state[6];
let mut h: u32 = self.state[7];
SHA256_W_ASSIGN!(self, 0, w0);
SHA256_W_ASSIGN!(self, 4, w1);
SHA256_W_ASSIGN!(self, 8, w2);
SHA256_W_ASSIGN!(self, 12, w3);
SHA256_W_ASSIGN!(self, 16, w4);
SHA256_W_ASSIGN!(self, 20, w5);
SHA256_W_ASSIGN!(self, 24, w6);
SHA256_W_ASSIGN!(self, 28, w7);
SHA256_W_ASSIGN!(self, 32, w8);
SHA256_W_ASSIGN!(self, 36, w9);
SHA256_W_ASSIGN!(self, 40, w10);
SHA256_W_ASSIGN!(self, 44, w11);
SHA256_W_ASSIGN!(self, 48, w12);
SHA256_W_ASSIGN!(self, 52, w13);
SHA256_W_ASSIGN!(self, 56, w14);
SHA256_W_ASSIGN!(self, 60, w15);
SHA256_FUNCTION_16!(self, a, b, c, d, e, f, g, h, 0, w0, 0);
SHA256_FUNCTION_16!(self, a, b, c, d, e, f, g, h, 1, w1, 4);
SHA256_FUNCTION_16!(self, a, b, c, d, e, f, g, h, 2, w2, 8);
SHA256_FUNCTION_16!(self, a, b, c, d, e, f, g, h, 3, w3, 12);
SHA256_FUNCTION_16!(self, a, b, c, d, e, f, g, h, 4, w4, 16);
SHA256_FUNCTION_16!(self, a, b, c, d, e, f, g, h, 5, w5, 20);
SHA256_FUNCTION_16!(self, a, b, c, d, e, f, g, h, 6, w6, 24);
SHA256_FUNCTION_16!(self, a, b, c, d, e, f, g, h, 7, w7, 28);
SHA256_FUNCTION_16!(self, a, b, c, d, e, f, g, h, 8, w8, 32);
SHA256_FUNCTION_16!(self, a, b, c, d, e, f, g, h, 9, w9, 36);
SHA256_FUNCTION_16!(self, a, b, c, d, e, f, g, h, 10, w10, 40);
SHA256_FUNCTION_16!(self, a, b, c, d, e, f, g, h, 11, w11, 44);
SHA256_FUNCTION_16!(self, a, b, c, d, e, f, g, h, 12, w12, 48);
SHA256_FUNCTION_16!(self, a, b, c, d, e, f, g, h, 13, w13, 52);
SHA256_FUNCTION_16!(self, a, b, c, d, e, f, g, h, 14, w14, 56);
SHA256_FUNCTION_16!(self, a, b, c, d, e, f, g, h, 15, w15, 60);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w0, w14, w9, w1, 16);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w1, w15, w10, w2, 17);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w2, w0, w11, w3, 18);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w3, w1, w12, w4, 19);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w4, w2, w13, w5, 20);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w5, w3, w14, w6, 21);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w6, w4, w15, w7, 22);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w7, w5, w0, w8, 23);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w8, w6, w1, w9, 24);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w9, w7, w2, w10, 25);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w10, w8, w3, w11, 26);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w11, w9, w4, w12, 27);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w12, w10, w5, w13, 28);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w13, w11, w6, w14, 29);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w14, w12, w7, w15, 30);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w15, w13, w8, w0, 31);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w0, w14, w9, w1, 32);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w1, w15, w10, w2, 33);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w2, w0, w11, w3, 34);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w3, w1, w12, w4, 35);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w4, w2, w13, w5, 36);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w5, w3, w14, w6, 37);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w6, w4, w15, w7, 38);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w7, w5, w0, w8, 39);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w8, w6, w1, w9, 40);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w9, w7, w2, w10, 41);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w10, w8, w3, w11, 42);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w11, w9, w4, w12, 43);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w12, w10, w5, w13, 44);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w13, w11, w6, w14, 45);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w14, w12, w7, w15, 46);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w15, w13, w8, w0, 47);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w0, w14, w9, w1, 48);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w1, w15, w10, w2, 49);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w2, w0, w11, w3, 50);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w3, w1, w12, w4, 51);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w4, w2, w13, w5, 52);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w5, w3, w14, w6, 53);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w6, w4, w15, w7, 54);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w7, w5, w0, w8, 55);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w8, w6, w1, w9, 56);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w9, w7, w2, w10, 57);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w10, w8, w3, w11, 58);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w11, w9, w4, w12, 59);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w12, w10, w5, w13, 60);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w13, w11, w6, w14, 61);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w14, w12, w7, w15, 62);
SHA256_FUNCTION_48!(a, b, c, d, e, f, g, h, w15, w13, w8, w0, 63);
self.state[0] = self.state[0].wrapping_add(a);
self.state[1] = self.state[1].wrapping_add(b);
self.state[2] = self.state[2].wrapping_add(c);
self.state[3] = self.state[3].wrapping_add(d);
self.state[4] = self.state[4].wrapping_add(e);
self.state[5] = self.state[5].wrapping_add(f);
self.state[6] = self.state[6].wrapping_add(g);
self.state[7] = self.state[7].wrapping_add(h);
}
///
/// Updates hash with new value
///
/// # Arguments
///
/// * `data` - Data as *[u8]
///
pub fn update(&mut self, data: &[u8]) {
let len = data.len();
for index in 0..len {
self.data[self.len as usize] = data[index];
self.len += 1;
if self.len == 64 {
self.transform();
self.nbits += 512;
self.len = 0;
}
}
}
///
/// Generates final hash
///
pub fn finalize(&mut self) {
let mut current_length: usize = self.len as usize;
self.data[current_length] = 0x80;
current_length += 1;
if self.len < 56 {
while current_length < 56 {
self.data[current_length] = 0x00;
current_length += 1;
}
} else {
while current_length < 64 {
self.data[current_length] = 0x00;
current_length += 1;
}
self.transform();
}
self.nbits += self.len * 8;
self.data[63] = self.nbits as u8;
self.data[62] = self.nbits.checked_shr(8).unwrap_or(0) as u8;
self.data[61] = self.nbits.checked_shr(16).unwrap_or(0) as u8;
self.data[60] = self.nbits.checked_shr(24).unwrap_or(0) as u8;
self.data[59] = self.nbits.checked_shr(32).unwrap_or(0) as u8;
self.data[58] = self.nbits.checked_shr(40).unwrap_or(0) as u8;
self.data[57] = self.nbits.checked_shr(48).unwrap_or(0) as u8;
self.data[56] = self.nbits.checked_shr(56).unwrap_or(0) as u8;
self.transform();
self.hash[0] = (self.state[0] >> 24) as u8;
self.hash[1] = (self.state[0] >> 16) as u8;
self.hash[2] = (self.state[0] >> 8) as u8;
self.hash[3] = (self.state[0]) as u8;
self.hash[4] = (self.state[1] >> 24) as u8;
self.hash[5] = (self.state[1] >> 16) as u8;
self.hash[6] = (self.state[1] >> 8) as u8;
self.hash[7] = (self.state[1]) as u8;
self.hash[8] = (self.state[2] >> 24) as u8;
self.hash[9] = (self.state[2] >> 16) as u8;
self.hash[10] = (self.state[2] >> 8) as u8;
self.hash[11] = (self.state[2]) as u8;
self.hash[12] = (self.state[3] >> 24) as u8;
self.hash[13] = (self.state[3] >> 16) as u8;
self.hash[14] = (self.state[3] >> 8) as u8;
self.hash[15] = (self.state[3]) as u8;
self.hash[16] = (self.state[4] >> 24) as u8;
self.hash[17] = (self.state[4] >> 16) as u8;
self.hash[18] = (self.state[4] >> 8) as u8;
self.hash[19] = (self.state[4]) as u8;
self.hash[20] = (self.state[5] >> 24) as u8;
self.hash[21] = (self.state[5] >> 16) as u8;
self.hash[22] = (self.state[5] >> 8) as u8;
self.hash[23] = (self.state[5]) as u8;
self.hash[24] = (self.state[6] >> 24) as u8;
self.hash[25] = (self.state[6] >> 16) as u8;
self.hash[26] = (self.state[6] >> 8) as u8;
self.hash[27] = (self.state[6]) as u8;
self.hash[28] = (self.state[7] >> 24) as u8;
self.hash[29] = (self.state[7] >> 16) as u8;
self.hash[30] = (self.state[7] >> 8) as u8;
self.hash[31] = (self.state[7]) as u8;
}
///
/// Receives string as array of bytes.
/// Returns [u8; 32]
///
/// # Arguments
///
/// * `data` - Data as &[u8]
///
pub fn digest(input: &[u8]) -> [u8; 32] {
let mut sha256 = Self::default();
sha256.update(input);
sha256.finalize();
sha256.hash
}
}
impl Default for Sha256 {
fn default() -> Self {
Self {
data: [0; 64],
state: [I[0], I[1], I[2], I[3], I[4], I[5], I[6], I[7]],
hash: [0; 32],
len: 0,
nbits: 0,
}
}
}
|
#![no_std]
extern crate alloc;
use alloc::{borrow::ToOwned, string::String};
use hgg::HggLite;
use space::{Knn, MetricPoint, Neighbor};
pub struct Dictionary {
hgg: HggLite<Word, ()>,
lookup_quality: usize,
}
impl Dictionary {
pub fn new() -> Self {
Self {
hgg: HggLite::new().exclude_all_searched(true),
lookup_quality: 8,
}
}
/// Default: `8`
pub fn lookup_quality(self, lookup_quality: usize) -> Self {
Self {
lookup_quality,
..self
}
}
/// Default: `64`
pub fn insert_quality(self, insert_quality: usize) -> Self {
Self {
hgg: self.hgg.insert_knn(insert_quality),
..self
}
}
pub fn add_word(&mut self, word: impl Into<String>) {
self.hgg.insert(Word(word.into()), ());
}
pub fn correct(&self, word: &str) -> Option<String> {
self.hgg
.knn(&Word(word.to_owned()), self.lookup_quality)
.into_iter()
.next()
.map(|Neighbor { index, .. }| self.hgg.get_key(index).unwrap().0.clone())
}
pub fn get_word(&self, word: usize) -> &str {
&self.hgg.get_key(word).unwrap().0
}
pub fn len(&self) -> usize {
self.hgg.len()
}
pub fn is_empty(&self) -> bool {
self.hgg.is_empty()
}
}
impl Default for Dictionary {
fn default() -> Self {
Self::new()
}
}
pub struct Word(pub String);
impl MetricPoint for Word {
type Metric = u32;
fn distance(&self, other: &Self) -> Self::Metric {
triple_accel::levenshtein_exp(self.0.as_bytes(), other.0.as_bytes())
}
}
|
use byteorder::{ByteOrder, LittleEndian as LE};
use custom_error::custom_error;
custom_error!{pub Error
IncompleteCode{index: usize} = "premature end of code stream at {index}",
IncompleteData{index: usize} = "premature end of data stream at {index}"
}
#[derive(Debug)]
pub enum Op {
Literal(u8),
CopyBytes { count: u8, offset: u16 },
Terminate(usize),
Noop
}
#[derive(Debug)]
pub struct Decompressor<'data> {
data: &'data[u8],
index: usize,
instructions: u16,
count: u8,
}
impl<'data> Decompressor<'data> {
pub fn new(data: &'data [u8]) -> Result<Decompressor, Error> {
let mut decompressor = Decompressor {
data,
index: 0,
instructions: 0,
count: 0,
};
decompressor.fetch_instructions()?;
Ok(decompressor)
}
#[inline]
fn fetch_instructions(&mut self) -> Result<(), Error> {
if self.data.len() < 2 {
return Err(Error::IncompleteCode{ index: self.index });
}
self.instructions = LE::read_u16(&self.data);
self.data = &self.data[2..];
self.index += 2;
self.count = 16;
Ok(())
}
#[inline]
fn read_bit(&mut self) -> Result<u8, Error> {
let (instructions, bit) = self.instructions.overflowing_add(self.instructions);
self.instructions = instructions;
self.count -= 1;
if self.count == 0 {
self.fetch_instructions()?;
}
Ok(bit as u8)
}
#[inline]
fn read_bits(&mut self, mut count: u8) -> Result<u8, Error> {
let mut value: u8 = self.read_bit()?;
count -= 1;
while count != 0 {
value = (value << 1) | self.read_bit()?;
count -= 1;
}
Ok(value)
}
#[inline]
fn read_byte(&mut self) -> Result<u8, Error> {
if self.data.is_empty() {
return Err(Error::IncompleteData{ index: self.index });
}
let byte = self.data[0];
self.data = &self.data[1..];
self.index += 1;
Ok(byte)
}
fn read_offset(&mut self) -> Result<u16, Error> {
Ok((u16::from(match self.read_bits(2)? {
0b00 => 0,
0b01 => match self.read_bit()? {
0 => 1,
1 => 2 + self.read_bit()?,
_ => unreachable!()
},
0b10 => match self.read_bit()? {
0 => 4 + self.read_bits(2)?,
1 => 8 + self.read_bits(3)?,
_ => unreachable!()
},
0b11 => match self.read_bit()? {
0 => 16 + self.read_bits(4)?,
1 => match self.read_bit()? {
0 => 32 + self.read_bits(4)?,
1 => match self.read_bit()? {
0 => 48 + self.read_bits(4)?,
1 => 64 + self.read_bits(6)?,
_ => unreachable!()
},
_ => unreachable!()
},
_ => unreachable!()
},
_ => unreachable!()
}) << 8) + u16::from(self.read_byte()?))
}
pub fn next_op(&mut self) -> Result<Op, Error> {
Ok(match self.read_bit()? {
0 => match self.read_bits(2)? {
0b00 => Op::CopyBytes{ count: 2, offset: u16::from(self.read_byte()?) },
0b01 => Op::CopyBytes{ count: 3, offset: self.read_offset()? },
0b10 => Op::CopyBytes{ count: 4 + self.read_bit()?, offset: self.read_offset()? },
0b11 => match self.read_bit()? {
0 => Op::CopyBytes{ count: 6 + self.read_bit()?, offset: self.read_offset()? },
1 => match self.read_bit()? {
0 => Op::CopyBytes{ count: 8 + self.read_bits(2)?, offset: self.read_offset()? },
1 => match self.read_bit()? {
0 => Op::CopyBytes{ count: 12 + self.read_bits(3)?, offset: self.read_offset()? },
1 => {
let count = self.read_byte()?;
if count < 0x81 {
return Ok(Op::CopyBytes{ count, offset: self.read_offset()? });
} else if count != 0x81 {
return Ok(Op::Terminate(self.index));
} else {
return Ok(Op::Noop);
}
},
_ => unreachable!()
},
_ => unreachable!()
},
_ => unreachable!()
},
_ => unreachable!()
},
1 => Op::Literal(self.read_byte()?),
_ => unreachable!()
})
}
}
|
extern crate rand;
use core::cmp;
use std::collections::HashMap;
use rand::Rng;
use rand::XorShiftRng;
use rand::SeedableRng;
use utils::ipoint::IPoint;
use utils::irange::IRange;
use utils::pointrng::PointRng;
use state::world::World;
use state::level::Level;
use objects::wall::Wall;
use objects::floor::Floor;
#[derive(Debug)]
pub enum Tile {
Room
}
pub type TileMap = HashMap<IPoint, Tile>;
pub trait Tiles {
fn build_room(&mut self, room: IRange);
fn build_xline(&mut self, x: i32, y1: i32, y2: i32);
fn build_yline(&mut self, x1: i32, x2: i32, y: i32);
}
impl Tiles for TileMap {
fn build_room(&mut self, room: IRange) {
for point in room.iter() {
self.insert(point, Tile::Room);
}
}
fn build_xline(&mut self, x: i32, y1: i32, y2: i32) {
let (oy1, oy2) = if y1 < y2 {(y1, y2)} else {(y2, y1)};
for y in oy1..oy2+1 {
self.insert(IPoint {x, y}, Tile::Room);
}
}
fn build_yline(&mut self, x1: i32, x2: i32, y: i32) {
let (ox1, ox2) = if x1 < x2 {(x1, x2)} else {(x2, x1)};
for x in ox1..ox2+1 {
self.insert(IPoint {x, y}, Tile::Room);
}
}
}
pub struct Blueprint {
pub size: IPoint,
pub rooms: Vec<IRange>,
pub tiles: TileMap,
pub random: XorShiftRng
}
impl Blueprint {
pub fn example(size: IPoint) -> Blueprint {
let mut bp = Blueprint::new(size);
for _ in 0..7 {
bp.try_add_room(IPoint { x: 3, y: 3 }.range(IPoint { x: 12, y: 12 }), 5);
}
for _ in 0..4 {
bp.try_add_room(IPoint { x: 1, y: 1 }.range(IPoint { x: 2, y: 2 }), 5);
}
bp.build_rooms();
bp.connect_tree();
bp
}
pub fn new(size: IPoint) -> Blueprint {
let seed: [u32; 4] = [2, 3, 6, 5];
Blueprint {
size,
rooms: Vec::new(),
tiles: HashMap::new(),
random: XorShiftRng::from_seed(seed),
}
}
pub fn build_rooms(&mut self) {
let rooms = &mut self.rooms;
let tiles = &mut self.tiles;
for room in rooms {
tiles.build_room(*room);
}
}
pub fn try_add_room(&mut self, size_range: IRange, mindist: i32) {
let mut room = None;
for _ in 1..100 {
let size = self.random.gen_in_range(size_range);
let end = self.random.gen_in_range(size.range(self.size));
let start = end - size;
let newroom = IRange {start, end};
let dist = self.rooms.iter().fold(
i32::max_value(),
|acc, x| cmp::min(acc, newroom.rdist(*x))
);
if dist >= mindist {
room = Some(newroom);
break;
}
}
if let Some(r) = room {
self.rooms.push(r);
}
}
pub fn connect_points(&mut self, p1: IPoint, p2: IPoint) {
let xeq = p1.x == p2.x;
let yeq = p1.y == p2.y;
if xeq && yeq {
self.tiles.insert(p1, Tile::Room);
} else if xeq {
self.tiles.build_xline(p1.x, p1.y, p2.y);
} else if yeq {
self.tiles.build_yline(p1.x, p2.x, p2.y);
} else {
let pi;
if self.random.gen_range(0, 2) == 1 {
pi = IPoint {x: p1.x, y: p2.y};
} else {
pi = IPoint {x: p2.x, y: p1.y};
}
self.connect_points(p1, pi);
self.connect_points(pi, p2);
}
}
pub fn connect_tree(&mut self) {
if self.rooms.len() == 0 {
return
}
let len = self.rooms.len();
let mut tree: Vec<usize> = self.rooms.iter().map(|_x| len).collect();
tree[0] = 0;
for _ in 1..len {
let mut best_dist: i32 = i32::max_value();
let mut best_child = 0;
let mut best_parent = 0;
for (parent, _) in tree.iter().enumerate().filter(|&(_i, &x)| x < len) {
for (child, _) in tree.iter().enumerate().filter(|&(_i, &x)| x == len) {
let dist = (&self.rooms[child]).rdist(self.rooms[parent]);
if dist < best_dist {
best_dist = dist;
best_parent = parent;
best_child = child;
}
}
}
tree[best_child] = best_parent;
}
for (child, &parent) in tree.iter().enumerate() {
let p1 = self.rooms[child].center().floor();
let p2 = self.rooms[parent].center().floor();
self.connect_points(p1, p2);
}
}
pub fn level_from_blueprint<'a>(&self, world: &'a mut World) -> &'a mut Level {
let mut level = Level::new(world.next_id(), self.size);
for point in self.size.zrange().iter() {
if self.tiles.get(&point).is_none() {
let object = Wall::new(world.next_id());
level.add_entity(Box::new(object), point);
} else {
let object = Floor::new(world.next_id());
level.add_entity(Box::new(object), point);
}
}
world.add_level(level)
}
}
|
use bound_int::*;
bound_int_types!(Foo, 1, 3);
fn main() {
println!("1 + 2 + 1 = {}", bound_int_eval!(Foo_1 + Foo_2 + Foo_1).value());
} |
use std::io;
use std::rand;
fn main() {
println!("Guess the number!");
let secret_number = (rand::random::<uint>() % 100u) + 1u;
loop {
print!("Please input your guess (1-100): ");
let input = io::stdin().read_line()
.ok()
.expect("Failed to read line");
let input_num: Option<uint> = from_str(input.as_slice().trim());
let num = match input_num {
Some(num) => num,
None => {
println!("Please input a number!");
continue;
}
};
match (num, secret_number) {
(x, y) if x > y => { println!("Too big!"); }
(x, y) if y > x => { println!("Too small!"); }
_ => { println!("You win!"); break;}
}
}
}
|
use error::Error;
use serde::{Serialize, Serializer, Deserialize, Deserializer};
use serde::de::{self, Visitor, MapAccess, IntoDeserializer};
use std::fmt::{self, Debug};
use std::str::FromStr;
pub const TOKEN: &'static str = "$serde_edn::private::SymbolHack";
pub const FIELD: &'static str = "$__serde_edn_private_symbol";
pub const NAME: &'static str = "$__serde_edn_private_Symbol";
#[derive(Clone, PartialEq,Hash)]
pub struct Symbol {
pub value: String,
}
impl Symbol {
#[inline]
pub fn from_str(s: &str) -> Result<Symbol, Error> {
Ok(Symbol { value: String::from(s) })
}
}
impl FromStr for Symbol {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Symbol { value: String::from(s) })
}
}
impl fmt::Display for Symbol {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
if let ref value = self.value {
write!(formatter, "{}", value)?;
}
Ok(())
}
}
impl Debug for Symbol {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.debug_tuple("Symbol").field(&self.value).finish()
}
}
impl Serialize for Symbol {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
use serde::ser::SerializeStruct;
let mut s = serializer.serialize_struct(TOKEN, 1)?;
s.serialize_field(TOKEN, &self.to_string())?;
s.end()
}
}
impl<'de> Deserialize<'de> for Symbol {
#[inline]
fn deserialize<D>(deserializer: D) -> Result<Symbol, D::Error>
where
D: Deserializer<'de>,
{
struct SymbolVisitor;
impl<'de> de::Visitor<'de> for SymbolVisitor {
type Value = Symbol;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("an edn symbol")
}
fn visit_map<V>(self, mut visitor: V) -> Result<Symbol, V::Error>
where
V: de::MapAccess<'de>,
{
let value = visitor.next_key::<SymbolKey>()?;
if value.is_none() {
return Err(de::Error::custom("symbol key not found"));
}
let v: SymbolFromString = visitor.next_value()?;
Ok(v.value)
}
}
static FIELDS: [&'static str; 1] = [FIELD];
deserializer.deserialize_struct(NAME, &FIELDS, SymbolVisitor)
}
}
struct SymbolKey;
impl<'de> de::Deserialize<'de> for SymbolKey {
fn deserialize<D>(deserializer: D) -> Result<SymbolKey, D::Error>
where
D: de::Deserializer<'de>,
{
struct FieldVisitor;
impl<'de> de::Visitor<'de> for FieldVisitor {
type Value = ();
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a valid symbol field")
}
fn visit_str<E>(self, s: &str) -> Result<(), E>
where
E: de::Error,
{
if s == FIELD {
Ok(())
} else {
Err(de::Error::custom("expected field with custom name"))
}
}
}
deserializer.deserialize_identifier(FieldVisitor)?;
Ok(SymbolKey)
}
}
// Not public API. Should be pub(crate).
#[doc(hidden)]
pub struct SymbolDeserializer<'de> {
pub value: &'de str,
// pub value: Option<String>,
}
impl<'de> MapAccess<'de> for SymbolDeserializer<'de> {
type Error = Error;
fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error>
where
K: de::DeserializeSeed<'de>,
{
// if self.value.is_none() {
// return Ok(None);
// }
seed.deserialize(SymbolFieldDeserializer).map(Some)
}
fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Error>
where
V: de::DeserializeSeed<'de>,
{
seed.deserialize(self.value.into_deserializer())
}
}
struct SymbolFieldDeserializer;
impl<'de> Deserializer<'de> for SymbolFieldDeserializer {
type Error = Error;
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error>
where
V: de::Visitor<'de>,
{
visitor.visit_borrowed_str(TOKEN)
}
forward_to_deserialize_any! {
bool u8 u16 u32 u64 u128 i8 i16 i32 i64 i128 f32 f64 char str string seq
bytes byte_buf map struct option unit newtype_struct ignored_any
unit_struct tuple_struct tuple enum identifier
}
}
pub struct SymbolFromString {
pub value: Symbol,
}
impl<'de> de::Deserialize<'de> for SymbolFromString {
fn deserialize<D>(deserializer: D) -> Result<SymbolFromString, D::Error>
where
D: de::Deserializer<'de>,
{
struct Visitor;
impl<'de> de::Visitor<'de> for Visitor {
type Value = SymbolFromString;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("string representing a symbol")
}
fn visit_str<E>(self, s: &str) -> Result<SymbolFromString, E>
where
E: de::Error,
{
match s.parse() {
Ok(x) => Ok(SymbolFromString { value: x }),
Err(e) => Err(de::Error::custom(e)),
}
}
}
deserializer.deserialize_str(Visitor)
}
}
|
fn main() {
use text_grid::*;
struct RowData {
a: f64,
b: f64,
}
impl CellsSource for RowData {
fn fmt(f: &mut CellsFormatter<&Self>) {
f.column("a", |&s| cell!("{:.2}", s.a).right());
f.column("b", |&s| cell!("{:.3}", s.b).right());
}
}
let mut g = Grid::new();
g.push(&RowData { a: 1.10, b: 1.11 });
g.push(&RowData { a: 1.00, b: 0.10 });
print!("{}", g);
panic!("failed");
}
|
use std::{
sync::{
atomic::{AtomicUsize, Ordering},
Arc,
},
time::Duration,
};
use metric::DurationCounter;
use observability_deps::tracing::*;
use parking_lot::Mutex;
use tokio::{
sync::Semaphore,
task::JoinHandle,
time::{Instant, Interval, MissedTickBehavior},
};
use crate::ingest_state::{
IngestState,
IngestStateError::{self, PersistSaturated},
};
/// The interval of time between evaluations of the state of the persist system
/// when saturated.
const EVALUATE_SATURATION_INTERVAL: Duration = Duration::from_secs(1);
/// A handle to evaluate the state of the persist system, propagating the state
/// to the [`IngestState`] instance provided by setting or clearing
/// [`IngestStateError::PersistSaturated`] as appropriate.
///
/// # Saturation Recovery
///
/// Once the persist system is marked as saturated, it remains in that state
/// until the following conditions are satisfied:
///
/// * There are no outstanding enqueue operations (no thread is blocked adding
/// an item to any work queue).
///
/// * The number of outstanding persist jobs is less than 50% of
/// `persist_queue_depth`
///
/// These conditions are evaluated periodically, at the interval specified in
/// [`EVALUATE_SATURATION_INTERVAL`].
#[derive(Debug)]
pub(super) struct PersistState {
/// The ingest state the persister configures.
ingest_state: Arc<IngestState>,
/// Tracks the number of [`WaitGuard`] instances, which in turn tracks the
/// number of async tasks waiting within `PersistHandle::enqueue()` to
/// obtain a semaphore permit and enqueue a persist job.
///
/// This is modified using [`Ordering::SeqCst`] as performance is not a
/// priority for code paths that modify it.
waiting_to_enqueue: Arc<AtomicUsize>,
/// The persist task semaphore with a maximum of `persist_queue_depth`
/// permits allocatable.
sem: Arc<Semaphore>,
persist_queue_depth: usize,
/// The handle to the current saturation evaluation/recovery task, if any.
recovery_handle: Mutex<Option<JoinHandle<()>>>,
/// A counter tracking the number of nanoseconds the state value is set to
/// saturated.
saturated_duration: DurationCounter,
}
impl PersistState {
/// Initialise a [`PersistState`], with a total number of tasks bounded to
/// `persist_queue_depth` and permits issued from `sem`.
pub(super) fn new(
ingest_state: Arc<IngestState>,
persist_queue_depth: usize,
sem: Arc<Semaphore>,
metrics: &metric::Registry,
) -> Self {
// The persist_queue_depth should be the maximum number of permits
// available in the semaphore.
assert!(persist_queue_depth >= sem.available_permits());
// This makes no sense and later we divide by this value.
assert!(
persist_queue_depth > 0,
"persist queue depth must be non-zero"
);
let saturated_duration = metrics
.register_metric::<DurationCounter>(
"ingester_persist_saturated_duration",
"the duration of time the persist system was marked as saturated",
)
.recorder(&[]);
Self {
ingest_state,
waiting_to_enqueue: Arc::new(AtomicUsize::new(0)),
recovery_handle: Default::default(),
persist_queue_depth,
sem,
saturated_duration,
}
}
/// Mark the persist system as saturated, returning a [`WaitGuard`] that
/// MUST be held during any subsequent async-blocking to acquire a permit
/// from the persist semaphore.
///
/// Holding the guard over the `acquire()` await allows the saturation
/// evaluation to track the number of threads with an ongoing enqueue wait.
pub(super) fn set_saturated(s: Arc<Self>) -> WaitGuard {
// Increment the number of tasks waiting to obtain a permit and push
// into any queue.
//
// INVARIANT: this increment MUST happen-before returning the guard, and
// waiting on the semaphore acquire(), and before starting the
// saturation monitor task so that it observes this waiter.
let _ = s.waiting_to_enqueue.fetch_add(1, Ordering::SeqCst);
// Attempt to set the system to "saturated".
let first = s.ingest_state.set(PersistSaturated);
if first {
// This is the first thread to mark the system as saturated.
warn!("persist queue saturated, blocking ingest");
// Always check the state of the system EVALUATE_SATURATION_INTERVAL
// duration of time after the last completed evaluation - do not
// attempt to check continuously should the check fall behind the
// ticker.
let mut interval = tokio::time::interval(EVALUATE_SATURATION_INTERVAL);
interval.set_missed_tick_behavior(MissedTickBehavior::Delay);
// Spawn a task that marks the system as not saturated after the
// workers have processed some of the backlog.
let h = tokio::spawn(saturation_monitor_task(
interval,
Arc::clone(&s),
s.persist_queue_depth,
Arc::clone(&s.sem),
));
// Retain the task handle to avoid leaking it if dropped.
*s.recovery_handle.lock() = Some(h);
}
WaitGuard(Arc::clone(&s.waiting_to_enqueue))
}
}
impl Drop for PersistState {
fn drop(&mut self) {
if let Some(h) = self.recovery_handle.lock().as_ref() {
h.abort();
}
}
}
/// A guard that decrements the number of writers waiting to obtain a permit
/// from the persistence semaphore.
///
/// This MUST be held whilst calling [`Semaphore::acquire()`].
#[must_use = "must hold wait guard while waiting for enqueue"]
pub(super) struct WaitGuard(Arc<AtomicUsize>);
impl Drop for WaitGuard {
fn drop(&mut self) {
let _ = self.0.fetch_sub(1, Ordering::SeqCst);
}
}
/// A task that monitors the `waiters` and `sem` to determine when the persist
/// system is no longer saturated.
///
/// Once the system is no longer saturated (as determined according to the
/// documentation for [`PersistState`]), the
/// [`IngestStateError::PersistSaturated`] error is cleared from the
/// [`IngestState`].
async fn saturation_monitor_task(
mut interval: Interval,
state: Arc<PersistState>,
persist_queue_depth: usize,
sem: Arc<Semaphore>,
) {
let mut last = Instant::now();
loop {
// Wait before evaluating the state of the system.
interval.tick().await;
// Update the saturation metric after the tick.
//
// For the first tick, this covers the tick wait itself. For subsequent
// ticks, this duration covers the evaluation time + tick wait.
let now = Instant::now();
state.saturated_duration.inc(now.duration_since(last));
last = now;
// INVARIANT: this task only ever runs when the system is saturated.
//
// Do not check for a specific "saturated" state here, as it may not
// take precedence over other error states.
assert!(state.ingest_state.read().is_err());
// First check if any tasks are waiting to obtain a permit and enqueue
// an item (an indication that one or more queues is full).
let n_waiting = state.waiting_to_enqueue.load(Ordering::SeqCst);
if n_waiting > 0 {
warn!(
n_waiting,
"waiting for outstanding persist jobs to be enqueued"
);
continue;
}
// No async task WAS currently waiting for a permit to enqueue a persist
// job when checking above, but one may want to immediately await one
// now (or later).
//
// In order to minimise health flip-flopping, only mark the persist
// system as healthy once there is some capacity in the semaphore to
// accept new persist jobs. This avoids the semaphore having 1 permit
// free, only to be immediately acquired and the system pause again.
//
// This check below ensures that the semaphore is at least half capacity
// before marking the system as recovered.
let available = sem.available_permits();
let outstanding = persist_queue_depth.checked_sub(available).unwrap();
if !has_sufficient_capacity(available, persist_queue_depth) {
warn!(
available,
outstanding, "waiting for outstanding persist jobs to reduce"
);
continue;
}
// There are no outstanding enqueue waiters, and all queues are at half
// capacity or better.
info!(
available,
outstanding, "persist queue saturation reduced, resuming ingest"
);
// INVARIANT: there is only ever one task that monitors the queue state
// and transitions the persist state to OK, therefore this task is
// always the first to set the state to OK.
assert!(state.ingest_state.unset(IngestStateError::PersistSaturated));
// The task MUST immediately stop so any subsequent saturation is
// handled by the newly spawned task, upholding the above invariant.
return;
}
}
/// Returns true if `capacity` is sufficient to be considered ready for more
/// requests to be enqueued.
fn has_sufficient_capacity(capacity: usize, max_capacity: usize) -> bool {
// Did this fire? You have your arguments the wrong way around.
assert!(capacity <= max_capacity);
let want_at_least = (max_capacity + 1) / 2;
capacity >= want_at_least
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use assert_matches::assert_matches;
use metric::Metric;
use test_helpers::timeout::FutureTimeout;
use super::*;
const QUEUE_DEPTH: usize = 42;
const POLL_INTERVAL: Duration = Duration::from_millis(5);
/// Execute `f` with the current value of the
/// "ingester_persist_saturated_duration" metric.
#[track_caller]
fn assert_saturation_time<F>(metrics: &metric::Registry, f: F)
where
F: FnOnce(Duration) -> bool,
{
// Get the saturated duration counter that tracks the time spent in the
// "saturated" state.
let duration_counter = metrics
.get_instrument::<Metric<DurationCounter>>("ingester_persist_saturated_duration")
.expect("constructor did not create required duration metric")
.recorder(&[]);
// Call the assert closure
assert!(f(duration_counter.fetch()));
}
#[test]
fn test_has_sufficient_capacity() {
// A queue of minimal depth (1).
//
// Validates there are no off-by-one errors.
assert!(!has_sufficient_capacity(0, 1));
assert!(has_sufficient_capacity(1, 1));
// Even queues
assert!(!has_sufficient_capacity(0, 2));
assert!(has_sufficient_capacity(1, 2));
assert!(has_sufficient_capacity(2, 2));
// Odd queues
assert!(!has_sufficient_capacity(0, 3));
assert!(!has_sufficient_capacity(1, 3));
assert!(has_sufficient_capacity(2, 3));
assert!(has_sufficient_capacity(3, 3));
}
/// Ensure that the saturation evaluation checks for outstanding enqueue
/// waiters (as tracked by the [`WaitGuard`]).
#[tokio::test]
async fn test_saturation_recovery_enqueue_waiters() {
let metrics = metric::Registry::default();
let sem = Arc::new(Semaphore::new(QUEUE_DEPTH));
let ingest_state = Arc::new(IngestState::default());
let s = Arc::new(PersistState::new(
Arc::clone(&ingest_state),
QUEUE_DEPTH,
Arc::clone(&sem),
&metrics,
));
// Use no queues to ensure only the waiters are blocking recovery.
assert_matches!(ingest_state.read(), Ok(()));
assert_saturation_time(&metrics, |d| d == Duration::ZERO);
// Obtain the current timestamp, and use it as an upper-bound on the
// duration of saturation.
let duration_upper_bound = Instant::now();
let w1 = PersistState::set_saturated(Arc::clone(&s));
let w2 = PersistState::set_saturated(Arc::clone(&s));
assert_matches!(ingest_state.read(), Err(IngestStateError::PersistSaturated));
// Kill the actual recovery task (there must be one running at this
// point).
s.recovery_handle.lock().take().unwrap().abort();
// Spawn a replacement that ticks way more often to speed up the test.
let h = tokio::spawn(saturation_monitor_task(
tokio::time::interval(POLL_INTERVAL),
Arc::clone(&s),
QUEUE_DEPTH,
sem,
));
// Drop a waiter and ensure the system is still saturated.
drop(w1);
assert_matches!(ingest_state.read(), Err(IngestStateError::PersistSaturated));
// Sleep a little to ensure it remains saturated with 1 outstanding
// waiter.
//
// This is false-negative racy - if this assert fires, there is a
// legitimate problem - one outstanding waiter should prevent the system
// from ever transitioning to a healthy state.
tokio::time::sleep(POLL_INTERVAL * 4).await;
assert_matches!(ingest_state.read(), Err(IngestStateError::PersistSaturated));
assert_saturation_time(&metrics, |d| d > Duration::ZERO);
// Drop the other waiter.
drop(w2);
// Wait up to 5 seconds to observe the system recovery.
async {
loop {
if ingest_state.read().is_ok() {
return;
}
tokio::time::sleep(POLL_INTERVAL).await;
}
}
.with_timeout_panic(Duration::from_secs(5))
.await;
// Assert the saturation metric reports a duration of at least 1 poll
// interval (the lower bound necessary for the above recovery to occur)
// and the maximum bound (the time since the system entered the
// saturated state).
assert_saturation_time(&metrics, |d| d >= POLL_INTERVAL);
assert_saturation_time(&metrics, |d| {
d < Instant::now().duration_since(duration_upper_bound)
});
// Wait up to 60 seconds to observe the recovery task finish.
//
// The recovery task sets the system state as healthy, and THEN exits,
// so there exists a window of time where the system has passed the
// saturation check above, but the recovery task MAY still be running.
//
// By waiting an excessive duration of time, we ensure the task does
// indeed finish.
async {
loop {
if h.is_finished() {
return;
}
tokio::time::sleep(POLL_INTERVAL).await;
}
}
.with_timeout_panic(Duration::from_secs(60))
.await;
// No task panic occurred.
assert!(h.with_timeout_panic(Duration::from_secs(5)).await.is_ok());
assert_matches!(ingest_state.read(), Ok(()));
}
/// Ensure that the saturation evaluation checks for free queue slots before
/// marking the system as healthy.
#[tokio::test]
async fn test_saturation_recovery_queue_capacity() {
let metrics = metric::Registry::default();
let sem = Arc::new(Semaphore::new(QUEUE_DEPTH));
let ingest_state = Arc::new(IngestState::default());
let s = Arc::new(PersistState::new(
Arc::clone(&ingest_state),
QUEUE_DEPTH,
Arc::clone(&sem),
&metrics,
));
// Use no waiters to ensure only the queue slots are blocking recovery.
assert_matches!(ingest_state.read(), Ok(()));
assert_saturation_time(&metrics, |d| d == Duration::ZERO);
// Obtain the current timestamp, and use it as an upper-bound on the
// duration of saturation.
let duration_upper_bound = Instant::now();
// Take half the permits. Holding this number of permits should allow
// the state to transition to healthy.
let _half_the_permits = sem.acquire_many(QUEUE_DEPTH as u32 / 2).await.unwrap();
// Obtain a permit, pushing it over the "healthy" limit.
let permit = sem.acquire().await.unwrap();
assert_matches!(ingest_state.read(), Ok(()));
assert!(ingest_state.set(IngestStateError::PersistSaturated));
assert_matches!(ingest_state.read(), Err(IngestStateError::PersistSaturated));
// Spawn the recovery task directly, not via set_saturated() for
// simplicity - the test above asserts the task is started by a call to
// set_saturated().
let h = tokio::spawn(saturation_monitor_task(
tokio::time::interval(POLL_INTERVAL),
Arc::clone(&s),
QUEUE_DEPTH,
Arc::clone(&sem),
));
// Wait a little and ensure the state hasn't changed.
//
// While this could be a false negative, if this assert fires there is a
// legitimate problem.
tokio::time::sleep(POLL_INTERVAL * 4).await;
assert_matches!(ingest_state.read(), Err(IngestStateError::PersistSaturated));
// Drop the permit so that the outstanding permits drops below the threshold for recovery.
drop(permit);
// Wait up to 5 seconds to observe the system recovery.
async {
loop {
if ingest_state.read().is_ok() {
return;
}
tokio::time::sleep(POLL_INTERVAL).await;
}
}
.with_timeout_panic(Duration::from_secs(5))
.await;
// Assert the saturation metric reports a duration of at least 1 poll
// interval (the lower bound necessary for the above recovery to occur)
// and the maximum bound (the time since the system entered the
// saturated state).
assert_saturation_time(&metrics, |d| d >= POLL_INTERVAL);
assert_saturation_time(&metrics, |d| {
d < Instant::now().duration_since(duration_upper_bound)
});
// Wait up to 60 seconds to observe the recovery task finish.
//
// The recovery task sets the system state as healthy, and THEN exits,
// so there exists a window of time where the system has passed the
// saturation check above, but the recovery task MAY still be running.
//
// By waiting an excessive duration of time, we ensure the task does
// indeed finish.
async {
loop {
if h.is_finished() {
return;
}
tokio::time::sleep(POLL_INTERVAL).await;
}
}
.with_timeout_panic(Duration::from_secs(60))
.await;
// No task panic occurred.
assert!(h.with_timeout_panic(Duration::from_secs(5)).await.is_ok());
assert_matches!(ingest_state.read(), Ok(()));
}
}
|
use crate::buf::Buf;
use crate::sample::Sample;
/// Trait implemented for buffers that can be resized.
pub trait ResizableBuf: Buf {
/// Resize the number of per-channel frames in the buffer.
///
/// # Examples
///
/// ```rust
/// use audio::{ResizableBuf, ExactSizeBuf as _, Channels as _};
///
/// fn test<B>(mut buffer: B) where B: ResizableBuf {
/// buffer.resize(4);
/// }
///
/// let mut buffer = audio::interleaved![[0; 0]; 2];
///
/// assert_eq!(buffer.channels(), 2);
/// assert_eq!(buffer.frames(), 0);
///
/// test(&mut buffer);
///
/// assert_eq!(buffer.channels(), 2);
/// assert_eq!(buffer.frames(), 4);
/// ```
fn resize(&mut self, frames: usize);
/// Resize the buffer to match the given topology.
///
/// # Examples
///
/// ```rust
/// use audio::{ResizableBuf, ExactSizeBuf as _, Channels as _};
///
/// fn test<B>(mut buffer: B) where B: ResizableBuf {
/// buffer.resize_topology(2, 4);
/// }
///
/// let mut buffer = audio::interleaved![[0; 0]; 4];
///
/// test(&mut buffer);
///
/// assert_eq!(buffer.channels(), 2);
/// assert_eq!(buffer.frames(), 4);
/// ```
fn resize_topology(&mut self, channels: usize, frames: usize);
}
impl<B> ResizableBuf for &mut B
where
B: ?Sized + ResizableBuf,
{
fn resize(&mut self, frames: usize) {
(**self).resize(frames);
}
fn resize_topology(&mut self, channels: usize, frames: usize) {
(**self).resize_topology(channels, frames);
}
}
impl<T> ResizableBuf for Vec<Vec<T>>
where
T: Sample,
{
fn resize(&mut self, frames: usize) {
for buf in self.iter_mut() {
buf.resize(frames, T::ZERO);
}
}
fn resize_topology(&mut self, channels: usize, frames: usize) {
for buf in self.iter_mut() {
buf.resize(frames, T::ZERO);
}
for _ in self.len()..channels {
self.push(vec![T::ZERO; frames]);
}
}
}
|
macro_rules! binary_op {
( $inst:ident, $op:tt ) => {{
let a = &$inst.pop();
let b = &$inst.pop();
&$inst.push(b $op a);
}}
}
const STACK_SIZE: usize = 1000;
enum Opcode {
LITERAL,
ADD,
SUBSTRACT,
MULTIPLY,
DIVIDE,
PRINT,
}
impl Opcode {
fn from_byte(byte: &u8) -> Option<Opcode> {
match *byte {
0x00 => Some(Opcode::LITERAL),
0x10 => Some(Opcode::ADD),
0x11 => Some(Opcode::SUBSTRACT),
0x12 => Some(Opcode::MULTIPLY),
0x13 => Some(Opcode::DIVIDE),
0x40 => Some(Opcode::PRINT),
_ => None
}
}
}
pub struct VM {
bytecode: Vec<u8>,
index: usize,
stack: [Option<i8>; STACK_SIZE],
stack_size: usize
}
impl VM {
pub fn run(bytecode: Vec<u8>) {
let mut vm = VM {
bytecode: bytecode.clone(),
index: 0,
stack: [None; STACK_SIZE],
stack_size: 0
};
while vm.index < bytecode.len() {
let opcode = vm.read();
vm.execute(opcode);
vm.next();
}
}
fn execute(&mut self, opcode: Opcode) {
match opcode {
Opcode::LITERAL => {
let literal = self.next().read_literal();
self.push(literal);
},
Opcode::ADD => { binary_op!(self, +) },
Opcode::SUBSTRACT => { binary_op!(self, -) },
Opcode::MULTIPLY => { binary_op!(self, *) },
Opcode::DIVIDE => { binary_op!(self, /) },
Opcode::PRINT => { println!("{}", self.pop()) },
}
}
fn read(&self) -> Opcode {
Opcode::from_byte(&self.bytecode[self.index]).unwrap()
}
fn read_literal(&self) -> i8 {
self.bytecode[self.index] as i8
}
fn next(&mut self) -> &Self {
self.index += 1;
self
}
fn push(&mut self, value: i8) {
assert!(self.stack_size < STACK_SIZE);
self.stack[self.stack_size] = Some(value);
self.stack_size += 1;
}
fn pop(&mut self) -> i8 {
assert!(self.stack_size > 0);
self.stack_size -= 1;
let value = self.stack[self.stack_size].unwrap();
self.stack[self.stack_size] = None;
value
}
}
|
use std::io;
use std::process::{Command, Child};
use x86::cpuid::VendorInfo;
use x86::msr::MSR_PKG_POWER_LIMIT;
use crate::bitfields::TurboRatioLimitsBitfield;
use crate::structures::TurboRatioLimits;
use crate::util::byte_slice_to_u64;
pub mod util;
pub mod structures;
pub mod ffi;
pub mod bitfields;
fn rdmsr(register: u32) -> Result<u64, io::Error> {
Command::new("rdmsr")
.arg("-r")
.arg(format!("0x{:x}", register))
.output()
.and_then(|output| {
if !output.status.success() {
return Result::Err(io::Error::new(io::ErrorKind::Other, String::from_utf8(output.stderr).unwrap()));
}
Ok(byte_slice_to_u64(&output.stdout))
})
}
fn wrmsr(register: u32, value: u64) {
dbg!(register, value);
Command::new("wrmsr")
.arg(format!("0x{:x}", register))
.arg(format!("0x{:x}", value))
.spawn();
}
#[cfg(target_os = "linux")]
fn get_sensors() -> io::Result<String> {
Command::new("sensors")
.arg("-j")
.output()
.and_then(|output| {
String::from_utf8(output.stdout)
.map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))
})
}
fn get_vendor() -> Option<VendorInfo> {
let cpuid = x86::cpuid::CpuId::new();
cpuid.get_vendor_info()
}
fn get_turbo_ratio_limits() -> io::Result<TurboRatioLimits> {
let bitfield = rdmsr(x86::msr::MSR_TURBO_RATIO_LIMIT)?;
let bitfield = TurboRatioLimitsBitfield(bitfield);
Ok(TurboRatioLimits {
ratio_1_cores_active: bitfield.ratio_1_active_cores() as u8,
ratio_2_cores_active: bitfield.ratio_2_active_cores() as u8,
ratio_3_cores_active: bitfield.ratio_3_active_cores() as u8,
ratio_4_cores_active: bitfield.ratio_4_active_cores() as u8,
})
}
fn set_turbo_ratio_limits(turbo_ratio_limits: &TurboRatioLimits) {
let mut bitfield = TurboRatioLimitsBitfield(0);
bitfield.set_ratio_1_active_cores(turbo_ratio_limits.ratio_1_cores_active as u64);
bitfield.set_ratio_2_active_cores(turbo_ratio_limits.ratio_2_cores_active as u64);
bitfield.set_ratio_3_active_cores(turbo_ratio_limits.ratio_3_cores_active as u64);
bitfield.set_ratio_4_active_cores(turbo_ratio_limits.ratio_4_cores_active as u64);
wrmsr(x86::msr::MSR_TURBO_RATIO_LIMIT, bitfield.0);
}
|
use af;
use af::Array;
use utils;
use error::HALError;
/// Return a vector form of the l2 error
/// (y - x) * (y - x)
pub fn l2_vec(pred: &Array, target: &Array) -> Array{
let diff = af::sub(pred, target, false);
af::mul(&diff, &diff, false)
}
/// Return a vector form of the mean squared error
/// 0.5 * (y - x) * (y - x)
pub fn mse_vec(pred: &Array, target: &Array) -> Array {
af::mul(&l2_vec(pred, target), &0.5f32, false)
}
/// Return a vector form of cross entropy
/// -ylnx - [1-y]ln[1-x]
pub fn cross_entropy_vec(pred: &Array, target: &Array) -> Array {
// -yln x
let pos = af::mul(&af::mul(&-1.0f32, target, false)
, &af::log(&utils::clip_by_value(pred, 1e-10, 1.0)), false);
//[1-y]ln[1-x]
let neg = af::mul(&af::sub(&1.0f32, target, false)
, &af::log(&utils::clip_by_value(&af::sub(&1.0f32
, pred
, false)
, 1e-10, 1.0)), false);
af::sub(&pos, &neg, false)
}
/// Provide a reduced form the L2 loss (single scalar)
pub fn l2(pred: &Array, target: &Array) -> f32 {
af::sum_all(&l2_vec(pred, target)).0 as f32
}
/// Provide a reduced form the mean squared error loss (single scalar)
pub fn mse(pred: &Array, target: &Array) -> f32 {
0.5f32 * af::mean_all(&l2_vec(pred, target)).0 as f32
}
/// Provide a reduced form the cross-entropy loss (single scalar)
pub fn cross_entropy(pred: &Array, target: &Array) -> f32 {
// y: true target, x: prediction
// E = sum(-ylnx - [1-y]ln[1-x])
af::sum_all(&cross_entropy_vec(pred, target)).0 as f32
}
/// Provides the vector derivative of the mean squared error
pub fn mse_derivative(pred: &Array, target: &Array) -> Array {
af::sub(pred, target, false)
}
/// Provides the vector derivative of the l2 error
pub fn l2_derivative(pred: &Array, target: &Array) -> Array {
af::mul(&mse_derivative(pred, target), &2.0f32, false)
}
/// Provides the vector derivative of the cross-entropy error
pub fn cross_entropy_derivative(pred: &Array, target: &Array) -> Array {
mse_derivative(pred, target)
}
/// Helper to provide a loss from a string
pub fn get_loss(name: &str, pred: &Array, target: &Array) -> Result<f32, HALError> {
match name {
"l2" => Ok(l2(pred, target)),
"mse" => Ok(mse(pred, target)),
"cross_entropy" => Ok(cross_entropy(pred, target)),
_ => Err(HALError::UNKNOWN),
}
}
/// Helper to provide a loss vector from a string
pub fn get_loss_vec(name: &str, pred: &Array, target: &Array) -> Result<Array, HALError> {
match name {
"l2" => Ok(l2_vec(pred, target)),
"mse" => Ok(mse_vec(pred, target)),
"cross_entropy" => Ok(cross_entropy_vec(pred, target)),
_ => Err(HALError::UNKNOWN),
}
}
/// Helper to provide a loss derivative from a string
pub fn get_loss_derivative(name: &str, pred: &Array, target: &Array) -> Result<Array, HALError> {
match name {
"l2" => Ok(l2_derivative(pred, target)),
"mse" => Ok(mse_derivative(pred, target)),
"cross_entropy" => Ok(cross_entropy_derivative(pred, target)),
_ => Err(HALError::UNKNOWN),
}
}
|
use std::process;
use std::env;
use std::path::{PathBuf};
use clap::{Arg, App, ArgMatches};
use fstree::Options;
/* This is a simple command line tool to print the content of a directory as a
* string.
* arguments:
* dir : The name of the dir to tree-ify;
*
* TODO:
*** Print nodes as a tree (This is the goal);
*** Refactor code to make it modular;
*** Add tests
*** Add "No argument show current dir tree" feature;
*** Add flag for hidden files
*** Add count of files and subfolders
* - Add colours based on the kind of node; (Optional)
* - Add proper error handling
*/
fn get_options(args : ArgMatches) -> Options{
let mut path = PathBuf::new();
path.push(args.value_of("dir").unwrap());
Options{
dir: path,
all: args.is_present("all"),
count: args.is_present("count"),
files: args.is_present("file"),
}
}
fn main(){
let default_path = env::current_dir().unwrap();
let matches = App::new("treers")
.version("0.1")
.author("Sténio J. <stexor12@gmail.com>")
.about("A simple command line program for showing directory paths and (optionally) the file in each subdirectory")
.arg(Arg::with_name("dir")
.required(true)
.value_name("DIR")
.default_value(default_path.to_str().unwrap())
.help("Path of directory to 'tree-ify'.")
)
.arg(Arg::with_name("file")
.short("f")
.help("Show the files in each subdirectory.")
)
.arg(Arg::with_name("all")
.short("a")
.help("Show all subdirectories and (optionally) files in DIR.")
)
.arg(Arg::with_name("count")
.short("c")
.help("Show number of subdirectories and (optionally) files in DIR.")
)
.get_matches();
let options = get_options(matches);
//Check if file is a directory
if !options.dir.is_dir(){
eprintln!("{:?} is not a directory.", options.dir);
process::exit(1);
}
match fstree::run(&options){
Ok(result) => {
println!("{}", result.tree);
if options.count{
if options.files{
println!("Found {} Subdirectories and {} files",
result.subdirs,
result.files
);
}else{
println!("Found {} Subdirectories",result.subdirs);
}
}
},
Err(error) => {
eprintln!("{:?}", error.kind());
panic!("Some error that i do not care about for now has happened");
}
};
}
|
//! Contains connection components.
//!
//! # Example
//!
//! ```
//! use dbus_tokio::connection;
//! use dbus::nonblock::Proxy;
//! use std::time::Duration;
//!
//! #[tokio::main]
//! pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!
//! // Connect to the D-Bus session bus (this is blocking, unfortunately).
//! let (resource, conn) = connection::new_session_sync()?;
//!
//! // The resource is a task that should be spawned onto a tokio compatible
//! // reactor ASAP. If the resource ever finishes, you lost connection to D-Bus.
//! tokio::spawn(async {
//! let err = resource.await;
//! panic!("Lost connection to D-Bus: {}", err);
//! });
//!
//! // Make a "proxy object" that contains the destination and path of our method call.
//! let proxy = Proxy::new("org.freedesktop.DBus", "/", Duration::from_secs(5), conn);
//!
//! // Call the method and await a response. See the argument guide for details about
//! // how to send and receive arguments to the method.
//! let (names,): (Vec<String>,) = proxy.method_call("org.freedesktop.DBus", "ListNames", ()).await?;
//!
//! // Print all the names.
//! for name in names { println!("{}", name); }
//!
//! Ok(())
//! }
//! ```
use dbus::channel::{Channel, BusType};
use dbus::nonblock::{LocalConnection, SyncConnection, Process, NonblockReply};
use dbus::Error;
use std::{future, task, pin};
use std::sync::Arc;
use std::time::Instant;
use tokio::io::Registration;
struct IOResourceUnregistered {
watch_fd: std::os::unix::io::RawFd,
waker_resource: mio::Registration,
}
struct IOResourceRegistered {
watch_fd: std::os::unix::io::RawFd,
watch_reg: Registration,
waker_reg: Registration,
}
enum IOResourceRegistration {
Unregistered(IOResourceUnregistered),
Registered(IOResourceRegistered),
}
/// The I/O Resource should be spawned onto a Tokio compatible reactor.
///
/// If you need to ever cancel this resource (i e disconnect from D-Bus),
/// you need to make this future abortable. If it finishes, you probably lost
/// contact with the D-Bus server.
pub struct IOResource<C> {
connection: Arc<C>,
registration: IOResourceRegistration,
write_pending: bool,
}
fn is_poll_ready(i: task::Poll<mio::Ready>) -> bool {
match i {
task::Poll::Ready(r) => !r.is_empty(),
task::Poll::Pending => false,
}
}
impl<C: AsRef<Channel> + Process> IOResource<C> {
fn poll_internal(&mut self, ctx: &mut task::Context<'_>) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let c: &Channel = (*self.connection).as_ref();
// Register all wake-up events in reactor
let IOResourceRegistered{watch_fd, watch_reg, waker_reg} = match &self.registration {
IOResourceRegistration::Unregistered(IOResourceUnregistered{watch_fd, waker_resource}) => {
let watch_fd = *watch_fd;
let watch_reg = Registration::new(&mio::unix::EventedFd(&watch_fd))?;
let waker_reg = Registration::new(waker_resource)?;
self.registration = IOResourceRegistration::Registered(IOResourceRegistered{watch_fd, watch_reg, waker_reg});
match &self.registration {
IOResourceRegistration::Registered(res) => res,
_ => unreachable!(),
}
},
IOResourceRegistration::Registered(res) => res,
};
// Make a promise that we process all events recieved before this moment
// If new event arrives after calls to poll_*_ready, tokio will wake us up.
let read_ready = is_poll_ready(watch_reg.poll_read_ready(ctx)?);
let send_ready = is_poll_ready(waker_reg.poll_read_ready(ctx)?);
// If we were woken up by write ready - reset it
let write_ready = watch_reg.take_write_ready()?.map(|r| r.is_writable()).unwrap_or(false);
if read_ready || send_ready || (self.write_pending && write_ready) {
loop {
self.write_pending = false;
c.read_write(Some(Default::default())).map_err(|_| Error::new_failed("Read/write failed"))?;
self.connection.process_all();
if c.has_messages_to_send() {
self.write_pending = true;
// DBus has unsent messages
// Assume it's because a write to fd would block
// Ask tokio to notify us when fd will became writable
if is_poll_ready(watch_reg.poll_write_ready(ctx)?) {
// try again immediately
continue
}
}
// Because libdbus is level-triggered and tokio is edge-triggered, we need to do read again
// in case libdbus did not read all available data. Maybe there is a better way to see if there
// is more incoming data than calling libc::recv?
// https://github.com/diwic/dbus-rs/issues/254
let mut x = 0u8;
let r = unsafe {
libc::recv(*watch_fd, &mut x as *mut _ as *mut libc::c_void, 1, libc::MSG_DONTWAIT | libc::MSG_PEEK)
};
if r != 1 { break; }
}
}
Ok(())
}
}
impl<C: AsRef<Channel> + Process> future::Future for IOResource<C> {
fn poll(mut self: pin::Pin<&mut Self>, ctx: &mut task::Context<'_>) -> task::Poll<Self::Output> {
match self.poll_internal(ctx) {
Ok(_) => {
task::Poll::Pending
},
Err(e) => task::Poll::Ready(e),
}
}
type Output = Box<dyn std::error::Error + Send + Sync>;
}
fn make_timeout(timeout: Instant) -> pin::Pin<Box<dyn future::Future<Output=()> + Send + Sync + 'static>> {
let t = tokio::time::delay_until(timeout.into());
Box::pin(t)
}
/// Generic connection creator, you might want to use e g `new_session_local`, `new_system_sync` etc for convenience.
pub fn new<C: From<Channel> + NonblockReply>(b: BusType) -> Result<(IOResource<C>, Arc<C>), Error> {
let mut channel = Channel::get_private(b)?;
channel.set_watch_enabled(true);
let watch = channel.watch();
let watch_fd = watch.fd;
let mut conn = C::from(channel);
conn.set_timeout_maker(Some(make_timeout));
// When we send async messages from other tasks we must wake up this one to do the flush
let (waker_resource, waker) = mio::Registration::new2();
conn.set_waker({ Some(Box::new(
move || waker.set_readiness(mio::Ready::readable()).map_err(|_| ())
))});
let conn = Arc::new(conn);
let res = IOResource {
connection: conn.clone(),
registration: IOResourceRegistration::Unregistered(IOResourceUnregistered{watch_fd, waker_resource}),
write_pending: false,
};
Ok((res, conn))
}
/// Creates a connection to the session bus, to use with Tokio's basic (single-thread) scheduler.
///
/// Note: This function blocks until the connection is set up.
pub fn new_session_local() -> Result<(IOResource<LocalConnection>, Arc<LocalConnection>), Error> { new(BusType::Session) }
/// Creates a connection to the system bus, to use with Tokio's basic (single-thread) scheduler.
///
/// Note: This function blocks until the connection is set up.
pub fn new_system_local() -> Result<(IOResource<LocalConnection>, Arc<LocalConnection>), Error> { new(BusType::System) }
/// Creates a connection to the session bus, to use with Tokio's default (multi-thread) scheduler.
///
/// Note: This function blocks until the connection is set up.
pub fn new_session_sync() -> Result<(IOResource<SyncConnection>, Arc<SyncConnection>), Error> { new(BusType::Session) }
/// Creates a connection to the system bus, to use with Tokio's default (multi-thread) scheduler.
///
/// Note: This function blocks until the connection is set up.
pub fn new_system_sync() -> Result<(IOResource<SyncConnection>, Arc<SyncConnection>), Error> { new(BusType::System) }
/* Let's skip these for now, not sure if they are useful?
pub fn new_session() -> Result<(IOResource<Connection>, Arc<Connection>), Error> { new(BusType::Session) }
pub fn new_system() -> Result<(IOResource<Connection>, Arc<Connection>), Error> { new(BusType::System) }
*/
#[test]
fn method_call_local() {
use tokio::task;
use std::time::Duration;
let mut rt = tokio::runtime::Builder::new()
.basic_scheduler()
.enable_io()
.enable_time()
.build()
.unwrap();
let local = task::LocalSet::new();
let (res, conn) = new_session_local().unwrap();
local.spawn_local(async move { panic!(res.await);});
let proxy = dbus::nonblock::Proxy::new("org.freedesktop.DBus", "/", Duration::from_secs(2), conn);
let fut = proxy.method_call("org.freedesktop.DBus", "NameHasOwner", ("dummy.name.without.owner",));
let (has_owner,): (bool,) = local.block_on(&mut rt, fut).unwrap();
assert_eq!(has_owner, false);
}
#[tokio::test]
async fn timeout() {
use std::time::Duration;
let (ress, conns) = new_session_sync().unwrap();
tokio::spawn(async move { panic!(ress.await);});
conns.request_name("com.example.dbusrs.tokiotest", true, true, true).await.unwrap();
use dbus::channel::MatchingReceiver;
conns.start_receive(dbus::message::MatchRule::new_method_call(), Box::new(|_,_| true));
let (res, conn) = new_session_sync().unwrap();
tokio::spawn(async move { panic!(res.await);});
let proxy = dbus::nonblock::Proxy::new("com.example.dbusrs.tokiotest", "/", Duration::from_millis(150), conn);
let e: Result<(), _> = proxy.method_call("com.example.dbusrs.tokiotest", "Whatever", ()).await;
let e = e.unwrap_err();
assert_eq!(e.name(), Some("org.freedesktop.DBus.Error.Timeout"));
}
#[tokio::test]
async fn large_message() -> Result<(), Box<dyn std::error::Error>> {
use dbus::arg::Variant;
use dbus_tree::Factory;
use futures::StreamExt;
use std::{
collections::HashMap,
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
time::Duration,
};
type BigProps<'a> = Vec<(dbus::Path<'a>, HashMap<String, Variant<Box<i32>>>)>;
// Simulate a big property list that something like connman would return.
fn make_big_reply<'a>() -> Result<BigProps<'a>, String> {
let prop_map: HashMap<String, Variant<Box<i32>>> = (0..500).map(|i| (format!("key {}", i), Variant(Box::new(i)))).collect();
(0..30u8).map(|i| Ok((dbus::strings::Path::new(format!("/{}", i))?, prop_map.clone()))).collect()
}
let server_conn = dbus::blocking::SyncConnection::new_session()?;
server_conn.request_name("com.example.dbusrs.tokiobigtest", false, true, false)?;
let f = Factory::new_sync::<()>();
let tree =
f.tree(()).add(f.object_path("/", ()).add(f.interface("com.example.dbusrs.tokiobigtest", ()).add_m(f.method("Ping", (), |m| {
// println!("received ping!");
Ok(vec![m.msg.method_return().append1(make_big_reply().map_err(|err| dbus::MethodErr::failed(&err))?)])
}))));
tree.start_receive_sync(&server_conn);
let done = Arc::new(AtomicBool::new(false));
let done2 = done.clone();
tokio::task::spawn_blocking(move || {
while !done2.load(Ordering::Acquire) {
server_conn.process(Duration::from_millis(100)).unwrap();
}
});
let (resource, client_conn) = new_session_sync()?;
tokio::spawn(async {
let err = resource.await;
panic!("Lost connection to D-Bus: {}", err);
});
let client_interval = tokio::time::interval(Duration::from_millis(10));
let proxy = dbus::nonblock::Proxy::new("com.example.dbusrs.tokiobigtest", "/", Duration::from_secs(1), client_conn);
client_interval
.take(10)
.for_each(|_| async {
println!("sending ping");
proxy.method_call::<(BigProps,), _, _, _>("com.example.dbusrs.tokiobigtest", "Ping", ()).await.unwrap();
println!("received prop list!");
})
.await;
done.store(true, Ordering::Release);
Ok(())
}
|
use crate::config::Config;
use crate::errors::*;
use crate::messages::*;
use crate::pool::*;
use crate::stream::*;
use crate::types::*;
use std::sync::Arc;
use tokio::sync::Mutex;
/// Abstracts a cypher query that is sent to neo4j server.
#[derive(Clone)]
pub struct Query {
query: String,
params: BoltMap,
}
impl Query {
pub fn new(query: String) -> Self {
Query {
query,
params: BoltMap::default(),
}
}
pub fn param<T: std::convert::Into<BoltType>>(mut self, key: &str, value: T) -> Self {
self.params.put(key.into(), value.into());
self
}
pub(crate) async fn run(
self,
config: &Config,
connection: Arc<Mutex<ManagedConnection>>,
) -> Result<()> {
let run = BoltRequest::run(&config.db, &self.query, self.params.clone());
let mut connection = connection.lock().await;
match connection.send_recv(run).await? {
BoltResponse::SuccessMessage(_) => {
match connection.send_recv(BoltRequest::discard()).await? {
BoltResponse::SuccessMessage(_) => Ok(()),
msg => Err(unexpected(msg, "DISCARD")),
}
}
msg => Err(unexpected(msg, "RUN")),
}
}
pub(crate) async fn execute(
self,
config: &Config,
connection: Arc<Mutex<ManagedConnection>>,
) -> Result<RowStream> {
let run = BoltRequest::run(&config.db, &self.query, self.params);
match connection.lock().await.send_recv(run).await {
Ok(BoltResponse::SuccessMessage(success)) => {
let fields: BoltList = success.get("fields").unwrap_or_else(BoltList::new);
let qid: i64 = success.get("qid").unwrap_or(-1);
Ok(RowStream::new(
qid,
fields,
config.fetch_size,
connection.clone(),
))
}
msg => Err(unexpected(msg, "RUN")),
}
}
}
|
use pyo3::prelude::*;
mod pa {
pub use pathfinder_canvas::{
Canvas, CanvasRenderingContext2D, Path2D,
FillStyle, FillRule, CanvasFontContext,
TextAlign, TextBaseline,
};
pub use pathfinder_geometry::{
vector::Vector2F,
rect::RectF,
transform2d::Transform2F
};
pub use pathfinder_content::{
outline::ArcDirection,
};
}
use crate::{Rect, Vector, Path, AutoScale, AutoVector, Transform, Color};
use std::sync::Arc;
#[pyclass]
pub struct Canvas {
inner: pa::CanvasRenderingContext2D
}
#[pymethods]
impl Canvas {
#[new]
pub fn new(size: AutoVector) -> Canvas {
Canvas {
inner: pa::Canvas::new(*size).get_context_2d(pa::CanvasFontContext::from_system_source())
}
}
pub fn save(&mut self) {
self.inner.save();
}
pub fn restore(&mut self) {
self.inner.restore();
}
pub fn fill_rect(&mut self, rect: Rect) {
self.inner.fill_rect(*rect);
}
pub fn stroke_rect(&mut self, rect: Rect) {
self.inner.stroke_rect(*rect);
}
pub fn clear_rect(&mut self, rect: Rect) {
self.inner.clear_rect(*rect);
}
pub fn fill_path(&mut self, path: Path, fill_rule: AutoFillRule) {
self.inner.fill_path(path.into_inner(), *fill_rule);
}
pub fn stroke_path(&mut self, path: Path) {
self.inner.stroke_path(path.into_inner());
}
pub fn clip_path(&mut self, path: Path, fill_rule: AutoFillRule) {
self.inner.clip_path(path.into_inner(), *fill_rule);
}
pub fn rotate(&mut self, angle: f32) {
self.inner.rotate(angle);
}
pub fn scale(&mut self, scale: AutoScale) {
self.inner.scale(*scale);
}
pub fn translate(&mut self, offset: AutoVector) {
self.inner.translate(*offset);
}
#[getter]
pub fn get_transform(&self) -> Transform {
Transform::from(self.inner.transform())
}
#[setter]
pub fn set_transform(&mut self, transform: Transform) {
self.inner.set_transform(&*transform);
}
pub fn reset_transform(&mut self) {
self.inner.reset_transform();
}
#[getter]
pub fn get_line_width(&self) -> f32 {
self.inner.line_width()
}
#[setter]
pub fn set_line_width(&mut self, new_line_width: f32) {
self.inner.set_line_width(new_line_width);
}
/*
#[getter]
pub fn get_line_cap(&self) -> PyResult<LineCap> {
Ok(self.inner
.line_cap())
}
#[setter]
pub fn set_line_cap(&mut self, new_line_cap: LineCap) -> PyResult<()> {
self.inner
.set_line_cap(new_line_cap);
Ok(())
}
#[getter]
pub fn get_line_join(&self) -> PyResult<LineJoin> {
Ok(self.inner
.line_join())
}
#[setter]
pub fn set_line_join(&mut self, new_line_join: LineJoin) -> PyResult<()> {
self.inner
.set_line_join(new_line_join);
Ok(())
}
*/
#[getter]
pub fn get_miter_limit(&self) -> f32 {
self.inner.miter_limit()
}
#[setter]
pub fn set_miter_limit(&mut self, new_miter_limit: f32) {
self.inner.set_miter_limit(new_miter_limit);
}
#[getter]
pub fn get_line_dash(&self) -> Vec<f32> {
self.inner.line_dash().to_owned()
}
#[setter]
pub fn set_line_dash(&mut self, new_line_dash: Vec<f32>) {
self.inner.set_line_dash(new_line_dash);
}
#[getter]
pub fn get_line_dash_offset(&self) -> f32 {
self.inner.line_dash_offset()
}
#[setter]
pub fn set_line_dash_offset(&mut self, new_line_dash_offset: f32) {
self.inner.set_line_dash_offset(new_line_dash_offset);
}
#[setter]
pub fn set_fill_style(&mut self, new_fill_style: AutoFillStyle) {
self.inner.set_fill_style(new_fill_style.0);
}
#[setter]
pub fn set_stroke_style(&mut self, new_stroke_style: AutoFillStyle) {
self.inner.set_stroke_style(new_stroke_style.0);
}
#[getter]
pub fn get_shadow_blur(&self) -> f32 {
self.inner.shadow_blur()
}
#[setter]
pub fn set_shadow_blur(&mut self, new_shadow_blur: f32) {
self.inner.set_shadow_blur(new_shadow_blur);
}
#[getter]
pub fn get_shadow_colort(&self) -> Color {
Color::from(self.inner.shadow_color())
}
#[setter]
pub fn set_shadow_color(&mut self, new_shadow_color: Color) {
self.inner.set_shadow_color(new_shadow_color.color_u());
}
#[getter]
pub fn get_shadow_offset(&self) -> Vector {
Vector::from(self.inner.shadow_offset())
}
#[setter]
pub fn set_shadow_offset(&mut self, new_shadow_offset: AutoVector) {
self.inner.set_shadow_offset(*new_shadow_offset);
}
}
/*
// Text
#[pymethods]
impl Canvas {
pub fn fill_text(&mut self, string: &str, position: AutoVector) {
self.inner.fill_text(string, *position);
}
pub fn stroke_text(&mut self, string: &str, position: AutoVector) {
self.inner.stroke_text(string, *position);
}
#[getter]
pub fn get_font_size(&self) -> f32 {
self.inner.font_size()
}
#[setter]
pub fn set_font_size(&mut self, font_size: f32) {
self.inner.set_font_size(font_size)
}
#[getter]
pub fn get_font(&self) -> FontCollection {
(*self.inner.font()).clone().into()
}
#[setter]
pub fn set_font(&mut self, font_collection: AutoFontCollection) {
self.inner.set_font(font_collection.into_inner());
}
#[setter]
pub fn set_text_align(&mut self, align: &str) -> PyResult<()> {
let align = match align {
"left" => pa::TextAlign::Left,
"center"=> pa::TextAlign::Center,
"right" => pa::TextAlign::Right,
_ => return Err(value_error!("('left' | 'center' | 'right')")),
};
self.inner.set_text_align(align);
Ok(())
}
}
*/
auto!(AutoFillStyle(pa::FillStyle));
impl<'s> FromPyObject<'s> for AutoFillStyle {
fn extract(ob: &'s PyAny) -> PyResult<Self> {
if let Ok(color) = Color::extract(ob) {
Ok(AutoFillStyle(pa::FillStyle::from(color.color_u())))
} else {
Err(value_error!("not a Color"))
}
}
}
auto!(AutoFillRule(pa::FillRule));
impl<'s> FromPyObject<'s> for AutoFillRule {
fn extract(ob: &'s PyAny) -> PyResult<Self> {
if let Ok(s) = <&str>::extract(ob) {
match s {
"even-odd" => Ok(AutoFillRule(pa::FillRule::EvenOdd)),
"nonzero" | "winding" => Ok(AutoFillRule(pa::FillRule::Winding)),
_ => Err(value_error!("valid are: 'even-odd' 'nonzero' or 'winding'"))
}
} else {
Err(value_error!("valid are: 'even-odd' 'nonzero' or 'winding'"))
}
}
}
|
use std::collections::BTreeMap;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use anyhow::anyhow;
use firefly_diagnostics::*;
use firefly_syntax_base::*;
use firefly_util::emit::Emit;
use super::*;
/// Represents expressions valid at the top level of a module body
#[derive(Debug, Clone, PartialEq, Spanned)]
pub enum TopLevel {
Module(Ident),
Attribute(Attribute),
Record(Record),
Function(Function),
}
impl TopLevel {
pub fn module_name(&self) -> Option<Ident> {
match self {
Self::Module(name) => Some(*name),
_ => None,
}
}
pub fn is_attribute(&self) -> bool {
match self {
Self::Attribute(_) => true,
_ => false,
}
}
pub fn is_record(&self) -> bool {
match self {
Self::Record(_) => true,
_ => false,
}
}
pub fn is_function(&self) -> bool {
match self {
Self::Function(_) => true,
_ => false,
}
}
}
/// Represents a complete module, broken down into its constituent parts
///
/// Creating a module via `Module::new` ensures that each field is correctly
/// populated, that sanity checking of the top-level constructs is performed,
/// and that a module is ready for semantic analysis and lowering to IR
///
/// A key step performed by `Module::new` is decorating `FunctionVar`
/// structs with the current module where appropriate (as this is currently not
/// done during parsing, as the module is constructed last). This means that once
/// constructed, one can use `FunctionVar` equality in sets/maps, which
/// allows us to easily check definitions, usages, and more.
#[derive(Debug, Clone, Spanned)]
pub struct Module {
#[span]
pub span: SourceSpan,
pub name: Ident,
pub vsn: Option<Expr>,
pub author: Option<Expr>,
pub compile: Option<CompileOptions>,
pub on_load: Option<Span<FunctionName>>,
pub nifs: HashSet<Span<FunctionName>>,
pub imports: HashMap<FunctionName, Span<Signature>>,
pub exports: HashSet<Span<FunctionName>>,
pub removed: HashMap<FunctionName, (SourceSpan, Ident)>,
pub types: HashMap<FunctionName, TypeDef>,
pub exported_types: HashSet<Span<FunctionName>>,
pub specs: HashMap<FunctionName, TypeSpec>,
pub behaviours: HashSet<Ident>,
pub callbacks: HashMap<FunctionName, Callback>,
pub records: HashMap<Symbol, Record>,
pub attributes: HashMap<Ident, UserAttribute>,
pub functions: BTreeMap<FunctionName, Function>,
// Used for module-level deprecation
pub deprecation: Option<Deprecation>,
// Used for function-level deprecation
pub deprecations: HashSet<Deprecation>,
}
impl Emit for Module {
fn file_type(&self) -> Option<&'static str> {
Some("ast")
}
fn emit(&self, f: &mut std::fs::File) -> anyhow::Result<()> {
use std::io::Write;
write!(f, "{:#?}", self)?;
Ok(())
}
}
impl Module {
pub fn name(&self) -> Symbol {
self.name.name
}
pub fn record(&self, name: Symbol) -> Option<&Record> {
self.records.get(&name)
}
pub fn is_local(&self, name: &FunctionName) -> bool {
let local_name = name.to_local();
self.functions.contains_key(&local_name)
}
pub fn is_import(&self, name: &FunctionName) -> bool {
let local_name = name.to_local();
!self.is_local(&local_name) && self.imports.contains_key(&local_name)
}
/// Creates a new, empty module with the given name and span
pub fn new(name: Ident, span: SourceSpan) -> Self {
Self {
span,
name,
vsn: None,
author: None,
on_load: None,
nifs: HashSet::new(),
compile: None,
imports: HashMap::new(),
exports: HashSet::new(),
removed: HashMap::new(),
types: HashMap::new(),
exported_types: HashSet::new(),
specs: HashMap::new(),
behaviours: HashSet::new(),
callbacks: HashMap::new(),
records: HashMap::new(),
attributes: HashMap::new(),
functions: BTreeMap::new(),
deprecation: None,
deprecations: HashSet::new(),
}
}
/// Called by the parser for Erlang Abstract Format, which relies on us detecting the module name in the given forms
pub fn new_from_pp(
reporter: &Reporter,
codemap: Arc<CodeMap>,
span: SourceSpan,
body: Vec<TopLevel>,
) -> anyhow::Result<Self> {
let name = body.iter().find_map(|t| t.module_name()).ok_or_else(|| {
anyhow!("invalid module, no module declaration present in given forms")
})?;
Ok(Self::new_with_forms(reporter, codemap, span, name, body))
}
/// Called by the parser to create the module once all of the top-level expressions have been
/// parsed, in other words this is the last function called when parsing a module.
///
/// As a result, this function performs initial semantic analysis of the module.
///
pub fn new_with_forms(
reporter: &Reporter,
_codemap: Arc<CodeMap>,
span: SourceSpan,
name: Ident,
mut forms: Vec<TopLevel>,
) -> Self {
use crate::passes::sema;
let mut module = Self {
span,
name,
vsn: None,
author: None,
on_load: None,
nifs: HashSet::new(),
compile: None,
imports: HashMap::new(),
exports: HashSet::new(),
removed: HashMap::new(),
types: HashMap::new(),
exported_types: HashSet::new(),
specs: HashMap::new(),
behaviours: HashSet::new(),
callbacks: HashMap::new(),
records: HashMap::new(),
attributes: HashMap::new(),
functions: BTreeMap::new(),
deprecation: None,
deprecations: HashSet::new(),
};
for form in forms.drain(0..) {
match form {
TopLevel::Attribute(attr) => sema::analyze_attribute(reporter, &mut module, attr),
TopLevel::Record(record) => sema::analyze_record(reporter, &mut module, record),
TopLevel::Function(function) => {
sema::analyze_function(reporter, &mut module, function)
}
_ => panic!("unexpected top-level form: {:?}", &form),
}
}
module
}
}
impl Eq for Module {}
impl PartialEq for Module {
fn eq(&self, other: &Module) -> bool {
if self.name != other.name {
return false;
}
if self.vsn != other.vsn {
return false;
}
if self.on_load != other.on_load {
return false;
}
if self.nifs != other.nifs {
return false;
}
if self.imports != other.imports {
return false;
}
if self.exports != other.exports {
return false;
}
if self.types != other.types {
return false;
}
if self.exported_types != other.exported_types {
return false;
}
if self.behaviours != other.behaviours {
return false;
}
if self.callbacks != other.callbacks {
return false;
}
if self.records != other.records {
return false;
}
if self.attributes != other.attributes {
return false;
}
if self.functions != other.functions {
return false;
}
true
}
}
|
#![allow(dead_code)]
use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::panic;
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};
use std::str;
use tempdir::TempDir;
pub fn test_write_file(path: &Path, content: &[u8], file_name: &str) -> PathBuf {
let mut file = File::create(path.join(file_name)).expect("failed to create file");
file.write_all(content).expect("failed to write to file");
path.join(file_name)
}
pub fn abuse_git_log_to_get_data(cwd: &Path, format: &str) -> String {
str::from_utf8(
git_log(
cwd,
&[format!("--format={}", format).as_str(), "--date=raw"],
)
.stdout
.as_slice(),
)
.unwrap()
.trim()
.to_owned()
}
pub fn git_log(cwd: &Path, args: &[&str]) -> Output {
let output = Command::new("git")
.current_dir(cwd)
.arg("log")
.args(args)
.output()
.unwrap();
assert!(output.status.success());
output
}
pub fn git_branch(cwd: &Path, name: &str) {
assert!(Command::new("git")
.current_dir(cwd)
.arg("branch")
.arg(name)
.status()
.unwrap()
.success())
}
pub fn git_commit(cwd: &Path, message: &str) {
assert!(Command::new("git")
.stderr(Stdio::null())
.stdout(Stdio::null())
.current_dir(cwd)
.arg("-c")
.arg("user.name=test")
.arg("commit")
.arg("--message")
.arg(message)
.status()
.unwrap()
.success())
}
pub fn git_tag(cwd: &Path, name: &str, message: Option<&str>) {
let mut cmd = Command::new("git");
cmd.stderr(Stdio::null());
cmd.stdout(Stdio::null());
cmd.arg("-c");
cmd.arg("user.name=test");
cmd.current_dir(cwd).arg("tag").arg(name);
if let Some(message) = message {
cmd.arg("--annotate");
cmd.arg("--message");
cmd.arg(message);
}
assert!(cmd.status().unwrap().success());
}
pub fn git_add_file(cwd: &Path, file: &Path) {
assert!(Command::new("git")
.current_dir(cwd)
.arg("add")
.arg(file)
.status()
.unwrap()
.success());
}
pub fn git_get_objects(cwd: &Path) -> Vec<String> {
let output = Command::new("git")
.current_dir(cwd)
.arg("cat-file")
.arg("--batch-check")
.arg("--batch-all-objects")
.output()
.expect("failed to read git objects using cat-file");
let text =
str::from_utf8(output.stdout.as_slice()).expect("failed to parse output from git cat-file");
text.split('\n')
.map(|line| line.split(' ').collect::<Vec<&str>>()[0])
.map(String::from)
.collect()
}
pub fn git_init(cwd: &Path) -> Result<Output, io::Error> {
Command::new("git").current_dir(cwd).arg("init").output()
}
pub fn git_clone(cwd: &Path, src: &str) {
assert!(Command::new("git")
.current_dir(cwd)
.arg("clone")
.arg(src)
.arg(cwd)
.output()
.unwrap()
.status
.success());
}
pub fn run_test<T>(test: T)
where
T: FnOnce(&Path) + panic::UnwindSafe,
{
let directory = setup();
let result = panic::catch_unwind(|| test(directory.path()));
teardown(directory);
assert!(result.is_ok());
}
pub fn run_test_in_new_repo<T>(test: T)
where
T: FnOnce(&Path) + panic::UnwindSafe,
{
run_test(|path| {
git_init(path).expect("failed to initialize git repository");
let test_file = test_write_file(path, b"Hello world!", "hello_world.txt");
git_add_file(path, test_file.as_path());
git_commit(path, "Initial commit.");
test(path)
})
}
pub fn run_test_in_repo<T>(repo: &str, test: T)
where
T: FnOnce(&Path) + panic::UnwindSafe,
{
run_test(|path| {
let repo_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(repo);
git_clone(path, repo_path.as_os_str().to_str().unwrap());
test(path)
})
}
pub fn setup() -> TempDir {
let temp = TempDir::new("test-").expect("failed to create test directory");
println!("path: {}", temp.path().display());
temp
}
pub fn teardown(temp: TempDir) {
let path = temp.path().to_owned();
temp.close()
.unwrap_or_else(|_| panic!("failed to clean up test directory: {}", path.display()));
}
|
pub enum Error {
Codegen(cranelift_module::ModuleError),
}
impl From<cranelift_module::ModuleError> for Error {
fn from(src: cranelift_module::ModuleError) -> Error {
Error::Codegen(src)
}
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Error::Codegen(e) => match e {
cranelift_module::ModuleError::Compilation(e2) => {
write!(f, "Compilation error: ")?;
match e2 {
cranelift_codegen::CodegenError::Verifier(e) => write!(f, "\n{}", e),
_ => write!(f, "{}", e),
}
},
_ => write!(f, "{}", e),
},
}
}
}
|
use crate::bulb::LB110;
use crate::error::Result;
use crate::plug::HS100;
use crate::{proto, Bulb, Plug};
use serde_json::{json, Value};
use std::collections::HashMap;
use std::net::IpAddr;
use std::time::Duration;
/// Types of TP-Link Wi-Fi Smart Home Devices.
pub enum DeviceKind {
/// TP-Link Smart Wi-Fi Plug.
Plug(Box<Plug<HS100>>),
/// TP-Link Smart Wi-Fi Bulb.
Bulb(Box<Bulb<LB110>>),
/// TP-Link Smart Wi-Fi Power Strip
Strip,
/// Encompasses any other TP-Link devices that
/// are not recognised by the library.
Unknown,
}
/// Discover existing TP-Link Smart Home devices on the network.
///
/// # Examples
///
/// ```no_run
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
/// for (ip, device) in tplink::discover()? {
/// match device {
/// tplink::DeviceKind::Plug(mut plug) => {
/// // .. do something with the plug
/// },
/// tplink::DeviceKind::Bulb(mut bulb) => {
/// // .. do something with the bulb
/// },
/// _ => println!("unrecognised device on the network: {}", ip),
/// }
/// }
/// Ok(())
/// }
/// ```
pub fn discover() -> Result<HashMap<IpAddr, DeviceKind>> {
let query = json!({
"system": {"get_sysinfo": {}},
"emeter": {"get_realtime": {}},
"smartlife.iot.dimmer": {"get_dimmer_parameters": {}},
"smartlife.iot.common.emeter": {"get_realtime": {}},
"smartlife.iot.smartbulb.lightingservice": {"get_light_state": {}},
});
let request = serde_json::to_vec(&query).unwrap();
let proto = proto::Builder::new(([255, 255, 255, 255], 9999))
.broadcast(true)
.read_timeout(Duration::from_secs(3))
.write_timeout(Duration::from_secs(3))
.tolerance(3)
.build();
let responses = proto.discover(&request)?;
let mut devices = HashMap::new();
for (ip, response) in responses {
let value = serde_json::from_slice::<Value>(&response).unwrap();
let device = device_from(ip, &value)?;
devices.entry(ip).or_insert(device);
}
Ok(devices)
}
fn device_from(host: IpAddr, value: &Value) -> Result<DeviceKind> {
let (device_type, sysinfo) = {
if value.get("system").is_some() && value["system"].get("get_sysinfo").is_some() {
let sysinfo = &value["system"]["get_sysinfo"];
if sysinfo.get("type").is_some() {
(sysinfo["type"].to_string().to_lowercase(), sysinfo)
} else if sysinfo.get("mic_type").is_some() {
(sysinfo["mic_type"].to_string().to_lowercase(), sysinfo)
} else {
panic!("invalid discovery response received")
}
} else {
panic!("invalid discovery response received")
}
};
if device_type.contains("plug") && sysinfo.get("children").is_some() {
Ok(DeviceKind::Strip)
} else if device_type.contains("plug") {
Ok(DeviceKind::Plug(Box::from(Plug::new(host))))
} else if device_type.contains("bulb") {
Ok(DeviceKind::Bulb(Box::from(Bulb::new(host))))
} else {
Ok(DeviceKind::Unknown)
}
}
|
#![allow(warnings)]
use crate::target::{Concrete, Endpoint, EndpointFromMetadata};
use futures::{future, prelude::*, stream};
use linkerd_app_core::{
discovery_rejected, is_discovery_rejected,
proxy::{
api_resolve::Metadata,
core::{Resolve, ResolveService, Update},
discover::{self, Buffer, FromResolve, MakeEndpoint},
resolve::map_endpoint,
},
svc::{
layer,
stack::{Filter, Param, Predicate},
NewService,
},
Addr, Error,
};
use std::{
future::Future,
pin::Pin,
task::{Context, Poll},
time::Duration,
};
type Stack<P, R, N> =
Buffer<discover::Stack<N, map_endpoint::Resolve<EndpointFromMetadata, R>, Endpoint<P>>>;
pub fn layer<P, R, N>(
resolve: R,
watchdog: Duration,
) -> impl layer::Layer<N, Service = Stack<P, R, N>> + Clone
where
P: Copy + Send + std::fmt::Debug,
R: Resolve<Concrete<P>, Endpoint = Metadata> + Clone,
R::Resolution: Send,
R::Future: Send,
N: NewService<Endpoint<P>>,
{
const ENDPOINT_BUFFER_CAPACITY: usize = 1_000;
let to_endpoint = EndpointFromMetadata;
layer::mk(move |new_endpoint| {
let endpoints = discover::resolve(
new_endpoint,
map_endpoint::Resolve::new(to_endpoint, resolve.clone()),
);
Buffer::new(ENDPOINT_BUFFER_CAPACITY, watchdog, endpoints)
})
}
|
/// A 2D compositor
pub struct Compositor2D {}
|
use num_enum::{IntoPrimitive, TryFromPrimitive};
/// A network domain.
#[derive(Clone, Copy, Debug, Eq, PartialEq, IntoPrimitive, TryFromPrimitive)]
#[repr(i32)]
pub enum Domain {
Ipv4 = libc::AF_INET,
Unix = libc::AF_LOCAL,
}
#[cfg(test)]
mod tests {
use super::*;
use std::convert::TryFrom;
#[test]
fn from_i32() {
// Positive cases
assert!(Domain::try_from(libc::AF_INET).unwrap() == Domain::Ipv4);
assert!(Domain::try_from(libc::AF_LOCAL).unwrap() == Domain::Unix);
// Negative cases
assert!(Domain::try_from(-1).is_err());
}
}
|
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
impl Point {
fn new(x_t: i32, y_t: i32) -> Self {
Point { x: x_t, y: y_t }
}
fn double(&mut self) {
self.x *= 2;
self.y *= 2;
}
fn len(x_pos: Point, y_pos: Point) -> f64 {
let x_bet = (x_pos.x - y_pos.x) as f64;
let y_bet = (x_pos.y - y_pos.y) as f64;
(x_bet * x_bet + y_bet * y_bet).sqrt()
}
}
struct Nope;
fn main() {
let x_point = Point { x: 20, y: 90 };
let y_point = Point { x: 10, ..x_point };
println!("{:?}", x_point);
println!("{:?}", y_point);
let nope = Nope;
let mut x_new = Point::new(2, 3);
let mut y_new = Point::new(10, -2);
x_new.double();
y_new.double();
println!("length is {}", Point::len(x_new, y_new));
}
|
/* origin: FreeBSD /usr/src/lib/msun/src/s_fmaf.c */
/*-
* Copyright (c) 2005-2011 David Schultz <das@FreeBSD.ORG>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
use core::f32;
use core::ptr::read_volatile;
use super::fenv::{
feclearexcept, fegetround, feraiseexcept, fetestexcept, FE_INEXACT, FE_TONEAREST, FE_UNDERFLOW,
};
/*
* Fused multiply-add: Compute x * y + z with a single rounding error.
*
* A double has more than twice as much precision than a float, so
* direct double-precision arithmetic suffices, except where double
* rounding occurs.
*/
/// Floating multiply add (f32)
///
/// Computes `(x*y)+z`, rounded as one ternary operation:
/// Computes the value (as if) to infinite precision and rounds once to the result format,
/// according to the rounding mode characterized by the value of FLT_ROUNDS.
#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)]
pub fn fmaf(x: f32, y: f32, mut z: f32) -> f32 {
let xy: f64;
let mut result: f64;
let mut ui: u64;
let e: i32;
xy = x as f64 * y as f64;
result = xy + z as f64;
ui = result.to_bits();
e = (ui >> 52) as i32 & 0x7ff;
/* Common case: The double precision result is fine. */
if (
/* not a halfway case */
ui & 0x1fffffff) != 0x10000000 ||
/* NaN */
e == 0x7ff ||
/* exact */
(result - xy == z as f64 && result - z as f64 == xy) ||
/* not round-to-nearest */
fegetround() != FE_TONEAREST
{
/*
underflow may not be raised correctly, example:
fmaf(0x1p-120f, 0x1p-120f, 0x1p-149f)
*/
if e < 0x3ff - 126 && e >= 0x3ff - 149 && fetestexcept(FE_INEXACT) != 0 {
feclearexcept(FE_INEXACT);
// prevent `xy + vz` from being CSE'd with `xy + z` above
let vz: f32 = unsafe { read_volatile(&z) };
result = xy + vz as f64;
if fetestexcept(FE_INEXACT) != 0 {
feraiseexcept(FE_UNDERFLOW);
} else {
feraiseexcept(FE_INEXACT);
}
}
z = result as f32;
return z;
}
/*
* If result is inexact, and exactly halfway between two float values,
* we need to adjust the low-order bit in the direction of the error.
*/
let neg = ui >> 63 != 0;
let err = if neg == (z as f64 > xy) {
xy - result + z as f64
} else {
z as f64 - result + xy
};
if neg == (err < 0.0) {
ui += 1;
} else {
ui -= 1;
}
f64::from_bits(ui) as f32
}
#[cfg(test)]
mod tests {
#[test]
fn issue_263() {
let a = f32::from_bits(1266679807);
let b = f32::from_bits(1300234242);
let c = f32::from_bits(1115553792);
let expected = f32::from_bits(1501560833);
assert_eq!(super::fmaf(a, b, c), expected);
}
}
|
/*
* hurl (https://hurl.dev)
* Copyright (C) 2020 Orange
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
use std::process;
// objectives
// get version
// get git commit
// get build date
// => hard-code into your binaries
fn main() {
// Make the current git hash available to the build.
if let Some(rev) = git_revision_hash() {
println!("cargo:rustc-env=HURL_BUILD_GIT_HASH={}", rev);
}
}
fn git_revision_hash() -> Option<String> {
let result = process::Command::new("git")
.args(&["rev-parse", "--short=10", "HEAD"])
.output();
result.ok().and_then(|output| {
let v = String::from_utf8_lossy(&output.stdout).trim().to_string();
if v.is_empty() {
None
} else {
Some(v)
}
})
}
|
use std::env;
use std::str;
mod puzzle_logic;
mod error;
fn parse_input(args: Vec<String>) -> [[u32; 9]; 9]
{
let mut puzzle: [[u32; 9]; 9] = [[0; 9]; 9];
let mut x: usize;
for y in 1..10
{
x = 0;
if args[y].len() != 9
{
error::print_usage_error(2);
}
for c in args[y].chars()
{
if c == '.'
{
puzzle[(y - 1) as usize][x] = 0;
}
else
{
//Also handles safe error checking, no problem converting normal chars to int
let temp = (c as u32) - ('0' as u32);
if temp > 0 && temp < 10
{
puzzle[(y - 1) as usize][x] = temp;
}
else
{
println!("ERROR::USAGE:: Invalid character in row {}", y);
error::print_usage_error(3);
}
}
x += 1;
}
}
puzzle
}
fn main()
{
let args: Vec<String> = env::args().collect();
if args.len() - 1 == 0 || args.len() - 1 != 9
{
error::print_usage_error(1);
}
let mut puzzle = parse_input(args);
puzzle_logic::solve_puzzle(&mut puzzle);
}
|
use std::collections::HashSet;
use std::io::{self, BufRead};
fn get_input() -> Vec<String> {
let stdin = io::stdin();
let stdin = stdin.lock();
let result = stdin.lines().collect::<Result<_, _>>().expect("Could not read input");
result
}
struct Passphrase<'a> {
words: Vec<&'a str>,
}
impl <'a> Passphrase<'a> {
fn from(s: &'a str) -> Self {
Passphrase { words: s.split_whitespace().collect() }
}
fn is_valid(&self) -> bool {
self.words.len() == self.words.iter().collect::<HashSet<_>>().len()
}
fn is_strictly_valid(&self) -> bool {
self.words.len() == self.words.iter().map(|w| {
let mut v = w.chars().collect::<Vec<_>>();
v.sort();
v
}).collect::<HashSet<_>>().len()
}
}
fn solve1(data: &[String]) -> usize {
data.into_iter().map(|s| Passphrase::from(s)).filter(|p| p.is_valid()).count()
}
fn solve2(data: &[String]) -> usize {
data.into_iter().map(|s| Passphrase::from(s)).filter(|p| p.is_strictly_valid()).count()
}
fn main() {
let data = get_input();
let result1 = solve1(&data);
println!("Solution 1: {}", result1);
let result2 = solve2(&data);
println!("Solution 2: {}", result2);
}
|
use log::{error};
use quantum_core::*;
fn main() {
simple_logger::init().unwrap();
let mut core = Quantum::new();
match core.load_plugin("plugin") {
Ok(name) => println!("{}", name),
Err(err) => error!("{}", err),
}
}
|
//!
//! The layer map tracks what layers exist for all the relishes in a timeline.
//!
//! When the timeline is first accessed, the server lists of all layer files
//! in the timelines/<timelineid> directory, and populates this map with
//! ImageLayer and DeltaLayer structs corresponding to each file. When new WAL
//! is received, we create InMemoryLayers to hold the incoming records. Now and
//! then, in the checkpoint() function, the in-memory layers are frozen, forming
//! new image and delta layers and corresponding files are written to disk.
//!
use crate::layered_repository::interval_tree::{IntervalItem, IntervalIter, IntervalTree};
use crate::layered_repository::storage_layer::{Layer, SegmentTag};
use crate::layered_repository::InMemoryLayer;
use crate::relish::*;
use anyhow::Result;
use lazy_static::lazy_static;
use std::cmp::Ordering;
use std::collections::{BinaryHeap, HashMap};
use std::sync::Arc;
use zenith_metrics::{register_int_gauge, IntGauge};
use zenith_utils::lsn::Lsn;
lazy_static! {
static ref NUM_INMEMORY_LAYERS: IntGauge =
register_int_gauge!("pageserver_inmemory_layers", "Number of layers in memory")
.expect("failed to define a metric");
static ref NUM_ONDISK_LAYERS: IntGauge =
register_int_gauge!("pageserver_ondisk_layers", "Number of layers on-disk")
.expect("failed to define a metric");
}
///
/// LayerMap tracks what layers exist on a timeline.
///
#[derive(Default)]
pub struct LayerMap {
/// All the layers keyed by segment tag
segs: HashMap<SegmentTag, SegEntry>,
/// All in-memory layers, ordered by 'oldest_pending_lsn' and generation
/// of each layer. This allows easy access to the in-memory layer that
/// contains the oldest WAL record.
open_layers: BinaryHeap<OpenLayerEntry>,
/// Generation number, used to distinguish newly inserted entries in the
/// binary heap from older entries during checkpoint.
current_generation: u64,
}
impl LayerMap {
///
/// Look up a layer using the given segment tag and LSN. This differs from a
/// plain key-value lookup in that if there is any layer that covers the
/// given LSN, or precedes the given LSN, it is returned. In other words,
/// you don't need to know the exact start LSN of the layer.
///
pub fn get(&self, tag: &SegmentTag, lsn: Lsn) -> Option<Arc<dyn Layer>> {
let segentry = self.segs.get(tag)?;
segentry.get(lsn)
}
///
/// Get the open layer for given segment for writing. Or None if no open
/// layer exists.
///
pub fn get_open(&self, tag: &SegmentTag) -> Option<Arc<InMemoryLayer>> {
let segentry = self.segs.get(tag)?;
segentry.open.as_ref().map(Arc::clone)
}
///
/// Insert an open in-memory layer
///
pub fn insert_open(&mut self, layer: Arc<InMemoryLayer>) {
let segentry = self.segs.entry(layer.get_seg_tag()).or_default();
segentry.update_open(Arc::clone(&layer));
let oldest_pending_lsn = layer.get_oldest_pending_lsn();
// After a crash and restart, 'oldest_pending_lsn' of the oldest in-memory
// layer becomes the WAL streaming starting point, so it better not point
// in the middle of a WAL record.
assert!(oldest_pending_lsn.is_aligned());
// Also add it to the binary heap
let open_layer_entry = OpenLayerEntry {
oldest_pending_lsn: layer.get_oldest_pending_lsn(),
layer,
generation: self.current_generation,
};
self.open_layers.push(open_layer_entry);
NUM_INMEMORY_LAYERS.inc();
}
/// Remove the oldest in-memory layer
pub fn pop_oldest_open(&mut self) {
// Pop it from the binary heap
let oldest_entry = self.open_layers.pop().unwrap();
let segtag = oldest_entry.layer.get_seg_tag();
// Also remove it from the SegEntry of this segment
let mut segentry = self.segs.get_mut(&segtag).unwrap();
if Arc::ptr_eq(segentry.open.as_ref().unwrap(), &oldest_entry.layer) {
segentry.open = None;
} else {
// We could have already updated segentry.open for
// dropped (non-writeable) layer. This is fine.
assert!(!oldest_entry.layer.is_writeable());
assert!(oldest_entry.layer.is_dropped());
}
NUM_INMEMORY_LAYERS.dec();
}
///
/// Insert an on-disk layer
///
pub fn insert_historic(&mut self, layer: Arc<dyn Layer>) {
let segentry = self.segs.entry(layer.get_seg_tag()).or_default();
segentry.insert_historic(layer);
NUM_ONDISK_LAYERS.inc();
}
///
/// Remove an on-disk layer from the map.
///
/// This should be called when the corresponding file on disk has been deleted.
///
pub fn remove_historic(&mut self, layer: Arc<dyn Layer>) {
let tag = layer.get_seg_tag();
if let Some(segentry) = self.segs.get_mut(&tag) {
segentry.historic.remove(&layer);
}
NUM_ONDISK_LAYERS.dec();
}
// List relations along with a flag that marks if they exist at the given lsn.
// spcnode 0 and dbnode 0 have special meanings and mean all tabespaces/databases.
// Pass Tag if we're only interested in some relations.
pub fn list_relishes(&self, tag: Option<RelTag>, lsn: Lsn) -> Result<HashMap<RelishTag, bool>> {
let mut rels: HashMap<RelishTag, bool> = HashMap::new();
for (seg, segentry) in self.segs.iter() {
match seg.rel {
RelishTag::Relation(reltag) => {
if let Some(request_rel) = tag {
if (request_rel.spcnode == 0 || reltag.spcnode == request_rel.spcnode)
&& (request_rel.dbnode == 0 || reltag.dbnode == request_rel.dbnode)
{
if let Some(exists) = segentry.exists_at_lsn(lsn)? {
rels.insert(seg.rel, exists);
}
}
}
}
_ => {
if tag == None {
if let Some(exists) = segentry.exists_at_lsn(lsn)? {
rels.insert(seg.rel, exists);
}
}
}
}
}
Ok(rels)
}
/// Is there a newer image layer for given segment?
///
/// This is used for garbage collection, to determine if an old layer can
/// be deleted.
pub fn newer_image_layer_exists(&self, seg: SegmentTag, lsn: Lsn) -> bool {
if let Some(segentry) = self.segs.get(&seg) {
segentry.newer_image_layer_exists(lsn)
} else {
false
}
}
/// Is there any layer for given segment that is alive at the lsn?
///
/// This is a public wrapper for SegEntry fucntion,
/// used for garbage collection, to determine if some alive layer
/// exists at the lsn. If so, we shouldn't delete a newer dropped layer
/// to avoid incorrectly making it visible.
pub fn layer_exists_at_lsn(&self, seg: SegmentTag, lsn: Lsn) -> Result<bool> {
Ok(if let Some(segentry) = self.segs.get(&seg) {
segentry.exists_at_lsn(lsn)?.unwrap_or(false)
} else {
false
})
}
/// Return the oldest in-memory layer, along with its generation number.
pub fn peek_oldest_open(&self) -> Option<(Arc<InMemoryLayer>, u64)> {
self.open_layers
.peek()
.map(|oldest_entry| (Arc::clone(&oldest_entry.layer), oldest_entry.generation))
}
/// Increment the generation number used to stamp open in-memory layers. Layers
/// added with `insert_open` after this call will be associated with the new
/// generation. Returns the new generation number.
pub fn increment_generation(&mut self) -> u64 {
self.current_generation += 1;
self.current_generation
}
pub fn iter_historic_layers(&self) -> HistoricLayerIter {
HistoricLayerIter {
seg_iter: self.segs.iter(),
iter: None,
}
}
/// debugging function to print out the contents of the layer map
#[allow(unused)]
pub fn dump(&self) -> Result<()> {
println!("Begin dump LayerMap");
for (seg, segentry) in self.segs.iter() {
if let Some(open) = &segentry.open {
open.dump()?;
}
for layer in segentry.historic.iter() {
layer.dump()?;
}
}
println!("End dump LayerMap");
Ok(())
}
}
impl IntervalItem for dyn Layer {
type Key = Lsn;
fn start_key(&self) -> Lsn {
self.get_start_lsn()
}
fn end_key(&self) -> Lsn {
self.get_end_lsn()
}
}
///
/// Per-segment entry in the LayerMap::segs hash map. Holds all the layers
/// associated with the segment.
///
/// The last layer that is open for writes is always an InMemoryLayer,
/// and is kept in a separate field, because there can be only one for
/// each segment. The older layers, stored on disk, are kept in an
/// IntervalTree.
#[derive(Default)]
struct SegEntry {
open: Option<Arc<InMemoryLayer>>,
historic: IntervalTree<dyn Layer>,
}
impl SegEntry {
/// Does the segment exist at given LSN?
/// Return None if object is not found in this SegEntry.
fn exists_at_lsn(&self, lsn: Lsn) -> Result<Option<bool>> {
if let Some(layer) = self.get(lsn) {
Ok(Some(layer.get_seg_exists(lsn)?))
} else {
Ok(None)
}
}
pub fn get(&self, lsn: Lsn) -> Option<Arc<dyn Layer>> {
if let Some(open) = &self.open {
if open.get_start_lsn() <= lsn {
let x: Arc<dyn Layer> = Arc::clone(open) as _;
return Some(x);
}
}
self.historic.search(lsn)
}
pub fn newer_image_layer_exists(&self, lsn: Lsn) -> bool {
// We only check on-disk layers, because
// in-memory layers are not durable
self.historic
.iter_newer(lsn)
.any(|layer| !layer.is_incremental())
}
// Set new open layer for a SegEntry.
// It's ok to rewrite previous open layer,
// but only if it is not writeable anymore.
pub fn update_open(&mut self, layer: Arc<InMemoryLayer>) {
if let Some(prev_open) = &self.open {
assert!(!prev_open.is_writeable());
}
self.open = Some(layer);
}
pub fn insert_historic(&mut self, layer: Arc<dyn Layer>) {
self.historic.insert(layer);
}
}
/// Entry held in LayerMap::open_layers, with boilerplate comparison routines
/// to implement a min-heap ordered by 'oldest_pending_lsn' and 'generation'
///
/// The generation number associated with each entry can be used to distinguish
/// recently-added entries (i.e after last call to increment_generation()) from older
/// entries with the same 'oldest_pending_lsn'.
struct OpenLayerEntry {
pub oldest_pending_lsn: Lsn, // copy of layer.get_oldest_pending_lsn()
pub generation: u64,
pub layer: Arc<InMemoryLayer>,
}
impl Ord for OpenLayerEntry {
fn cmp(&self, other: &Self) -> Ordering {
// BinaryHeap is a max-heap, and we want a min-heap. Reverse the ordering here
// to get that. Entries with identical oldest_pending_lsn are ordered by generation
other
.oldest_pending_lsn
.cmp(&self.oldest_pending_lsn)
.then_with(|| other.generation.cmp(&self.generation))
}
}
impl PartialOrd for OpenLayerEntry {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for OpenLayerEntry {
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == Ordering::Equal
}
}
impl Eq for OpenLayerEntry {}
/// Iterator returned by LayerMap::iter_historic_layers()
pub struct HistoricLayerIter<'a> {
seg_iter: std::collections::hash_map::Iter<'a, SegmentTag, SegEntry>,
iter: Option<IntervalIter<'a, dyn Layer>>,
}
impl<'a> Iterator for HistoricLayerIter<'a> {
type Item = Arc<dyn Layer>;
fn next(&mut self) -> std::option::Option<<Self as std::iter::Iterator>::Item> {
loop {
if let Some(x) = &mut self.iter {
if let Some(x) = x.next() {
return Some(Arc::clone(&x));
}
}
if let Some((_tag, segentry)) = self.seg_iter.next() {
self.iter = Some(segentry.historic.iter());
continue;
} else {
return None;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::PageServerConf;
use std::str::FromStr;
use zenith_utils::zid::{ZTenantId, ZTimelineId};
/// Arbitrary relation tag, for testing.
const TESTREL_A: RelishTag = RelishTag::Relation(RelTag {
spcnode: 0,
dbnode: 111,
relnode: 1000,
forknum: 0,
});
/// Construct a dummy InMemoryLayer for testing
fn dummy_inmem_layer(
conf: &'static PageServerConf,
segno: u32,
start_lsn: Lsn,
oldest_pending_lsn: Lsn,
) -> Arc<InMemoryLayer> {
Arc::new(
InMemoryLayer::create(
conf,
ZTimelineId::from_str("00000000000000000000000000000000").unwrap(),
ZTenantId::from_str("00000000000000000000000000000000").unwrap(),
SegmentTag {
rel: TESTREL_A,
segno,
},
start_lsn,
oldest_pending_lsn,
)
.unwrap(),
)
}
#[test]
fn test_open_layers() -> Result<()> {
let conf = PageServerConf::dummy_conf(PageServerConf::test_repo_dir("dummy_inmem_layer"));
let conf = Box::leak(Box::new(conf));
let mut layers = LayerMap::default();
let gen1 = layers.increment_generation();
layers.insert_open(dummy_inmem_layer(conf, 0, Lsn(0x100), Lsn(0x100)));
layers.insert_open(dummy_inmem_layer(conf, 1, Lsn(0x100), Lsn(0x200)));
layers.insert_open(dummy_inmem_layer(conf, 2, Lsn(0x100), Lsn(0x120)));
layers.insert_open(dummy_inmem_layer(conf, 3, Lsn(0x100), Lsn(0x110)));
let gen2 = layers.increment_generation();
layers.insert_open(dummy_inmem_layer(conf, 4, Lsn(0x100), Lsn(0x110)));
layers.insert_open(dummy_inmem_layer(conf, 5, Lsn(0x100), Lsn(0x100)));
// A helper function (closure) to pop the next oldest open entry from the layer map,
// and assert that it is what we'd expect
let mut assert_pop_layer = |expected_segno: u32, expected_generation: u64| {
let (l, generation) = layers.peek_oldest_open().unwrap();
assert!(l.get_seg_tag().segno == expected_segno);
assert!(generation == expected_generation);
layers.pop_oldest_open();
};
assert_pop_layer(0, gen1); // 0x100
assert_pop_layer(5, gen2); // 0x100
assert_pop_layer(3, gen1); // 0x110
assert_pop_layer(4, gen2); // 0x110
assert_pop_layer(2, gen1); // 0x120
assert_pop_layer(1, gen1); // 0x200
Ok(())
}
}
|
//#![no_std]
pub mod attribute;
pub mod attribute_parser;
pub mod data_set_parser;
pub mod encoding;
pub mod handler;
pub mod meta_information;
pub mod p10;
pub mod p10_parser;
pub mod prefix;
pub mod tag;
pub mod test;
pub mod value_parser;
pub mod vr;
|
pub mod io;
pub mod cartridge;
pub mod memory_bus;
pub mod work_ram;
pub mod registers;
|
use std::io;
fn main() {
loop {
println!("\nInput a temperature (e.g. 1°C or 2.3°K):");
let mut input = String::new();
io::stdin().read_line(&mut input).expect("Couldn't read user input!");
// check if user wants to exit
if input.contains("q") {
println!("Thanks for the run!");
return;
}
// clean user input
let mut value = String::new();
let mut unit = '°';
for c in input.chars() {// single-pass cleaning of all input chars
match c {
x if x.is_numeric() || x == '.' => {
value.push(c);
},
'C' => {
unit = 'C';
},
'K' => {
unit = 'K';
}
_ => {/* invalid char, skip */}
}
}
// parse final value
let value: f32 = match value.parse() {
Ok(num) => num,
Err(_) => {
println!("Value isn't a valid numeric value (e.g. like 42 or 37.5)");
continue;
}
};
// do conversion
match unit {
'C' => {
println!("{}°C is equal to {}°K", value, value + 273.15);
continue;
},
'K' => {
println!("{}°K is equal to {}°C", value, value - 273.15);
continue;
},
_ => {
println!("Missing or incorrect unit, try again! Or type \"quit\"");
continue;
}
}
}
}
|
use crate::ui::common::table::Table;
use crate::ui::Refresh;
use gtk::prelude::*;
use sysinfo::{ProcessExt, SystemExt};
pub struct Processes {
pub table: Table,
}
impl Processes {
pub fn new() -> Self {
let column_names = [
"PID",
"User ID",
"Status",
"CPU%",
"MEM KiB",
"Process Name",
];
let column_types = [
u32::static_type(),
u32::static_type(),
String::static_type(),
String::static_type(),
u32::static_type(),
String::static_type(),
];
let table = Table::new(&column_names, &column_types);
Self { table }
}
}
impl Refresh for Processes {
fn refresh(&self, system: &sysinfo::System) {
let processes_list = system.get_processes();
self.table.get_store().clear();
for (pid, process) in processes_list.iter() {
if process.cmd().len() != 0 {
self.table.get_store().insert_with_values(
None,
&[0, 1, 2, 3, 4, 5],
&[
pid,
// &extract_username(process.environ()),
&process.uid,
&format!("{:?}", process.status()),
&format!("{:.1}", process.cpu_usage()),
&process.memory(),
&process.cmd().join(" "),
],
);
}
}
}
}
// fn extract_username(environ: &[String]) -> String {
// println!("{:?}", environ);
// let user = environ.iter().find(|line| {
// if line.len() > 9 && &line[..=8] == "USERNAME=" {
// return true;
// }
// false
// });
// let user = match user {
// Some(user) => user.split("=").nth(1).unwrap(),
// None => "Unknown",
// };
// String::from(user)
// }
|
extern crate pest;
#[macro_use]
extern crate pest_derive;
use pest::Parser;
use pest::iterators::Pairs;
use std::io::{self, Write};
#[cfg(debug_assertions)]
const _GRAMMAR: &'static str = include_str!("bvh.pest");
#[derive(Parser)]
#[grammar = "bvh.pest"]
struct BvhParser;
#[derive(Debug)]
pub struct Bvh {
pub hierarchy: Hierarchy,
pub motion: Motion,
}
#[derive(Debug)]
pub struct Hierarchy {
pub root: Joint,
}
#[derive(Debug)]
pub struct Joint {
pub name: String,
pub offset: Offset,
pub channels: Vec<Channel>,
pub children: JointChildren,
}
impl Joint {
pub fn total_channels(&self) -> u32 {
(self.channels.len() as u32) + match self.children {
JointChildren::Joints(ref joints) => joints.iter().map(|joint| joint.total_channels()).sum(),
JointChildren::EndSite(_) => 0,
}
}
}
#[derive(Debug)]
pub struct Offset {
pub x: f64,
pub y: f64,
pub z: f64,
}
#[derive(Debug)]
pub enum Channel {
XPosition,
YPosition,
ZPosition,
XRotation,
YRotation,
ZRotation,
}
#[derive(Debug)]
pub enum JointChildren {
Joints(Vec<Joint>),
EndSite(EndSite),
}
#[derive(Debug)]
pub struct EndSite {
pub offset: Offset,
}
#[derive(Debug)]
pub struct Motion {
pub num_frames: u32,
pub frame_time: f64,
pub frames: Vec<Vec<f64>>,
}
pub fn parse(input: &str) -> Result<Bvh, String> {
let mut pairs = BvhParser::parse(Rule::bvh, &input).map_err(|e| format!("Couldn't parse BVH: {:?}", e))?;
let mut bvh_pairs = pairs.find(|pair| pair.as_rule() == Rule::bvh).unwrap().into_inner();
let mut hierarchy_pairs = bvh_pairs.find(|pair| pair.as_rule() == Rule::hierarchy).unwrap().into_inner();
let mut root_pairs = hierarchy_pairs.find(|pair| pair.as_rule() == Rule::root_joint).unwrap().into_inner();
let root_joint_body_pairs = root_pairs.find(|pair| pair.as_rule() == Rule::joint_body).unwrap().into_inner();
let root = parse_joint(root_joint_body_pairs);
let mut motion_pairs = bvh_pairs.find(|pair| pair.as_rule() == Rule::motion).unwrap().into_inner();
let mut frames_pairs = motion_pairs.find(|pair| pair.as_rule() == Rule::frames).unwrap().into_inner();
let num_frames = frames_pairs.find(|pair| pair.as_rule() == Rule::integer).unwrap().as_str().parse::<u32>().unwrap();
let frame_time = parse_f64(&mut frames_pairs);
let mut frames = Vec::new();
let mut frame = Vec::new();
let total_channels = root.total_channels();
for (index, value) in frames_pairs.filter(|pair| pair.as_rule() == Rule::float).map(|pair| pair.as_str().parse::<f64>().unwrap()).enumerate() {
frame.push(value);
if (index as u32) % total_channels == total_channels - 1 {
frames.push(frame);
frame = Vec::new();
}
}
let motion = Motion {
num_frames: num_frames,
frame_time: frame_time,
frames: frames,
};
Ok(Bvh {
hierarchy: Hierarchy {
root: root,
},
motion: motion,
})
}
fn parse_joint(mut joint_body_pairs: Pairs<Rule>) -> Joint {
let name = joint_body_pairs.find(|pair| pair.as_rule() == Rule::identifier).unwrap().as_str().into();
let mut offset_pairs = joint_body_pairs.find(|pair| pair.as_rule() == Rule::offset).unwrap().into_inner();
let offset = parse_offset(&mut offset_pairs);
let channel_pairs = joint_body_pairs.find(|pair| pair.as_rule() == Rule::channels).unwrap().into_inner();
let joints: Vec<Joint> = joint_body_pairs.clone().filter(|pair| pair.as_rule() == Rule::joint).map(|pair| {
let body_pairs = pair.into_inner().find(|pair| pair.as_rule() == Rule::joint_body).unwrap().into_inner();
parse_joint(body_pairs)
}).collect();
let children = if joints.len() > 0 {
JointChildren::Joints(joints)
} else {
let mut end_site_pairs = joint_body_pairs.find(|pair| pair.as_rule() == Rule::end_site).unwrap().into_inner();
let mut offset_pairs = end_site_pairs.find(|pair| pair.as_rule() == Rule::offset).unwrap().into_inner();
let offset = parse_offset(&mut offset_pairs);
JointChildren::EndSite(EndSite {
offset: offset,
})
};
Joint {
name: name,
offset: offset,
channels: channel_pairs.filter(|pair| pair.as_rule() == Rule::channel).map(|pair| match pair.as_str() {
"Xposition" => Channel::XPosition,
"Yposition" => Channel::YPosition,
"Zposition" => Channel::ZPosition,
"Xrotation" => Channel::XRotation,
"Yrotation" => Channel::YRotation,
"Zrotation" => Channel::ZRotation,
_ => unreachable!()
}).collect(),
children: children,
}
}
fn parse_offset(offset_pairs: &mut Pairs<Rule>) -> Offset {
Offset {
x: parse_f64(offset_pairs),
y: parse_f64(offset_pairs),
z: parse_f64(offset_pairs),
}
}
fn parse_f64(offset_pairs: &mut Pairs<Rule>) -> f64 {
offset_pairs.find(|pair| pair.as_rule() == Rule::float).unwrap().as_str().parse::<f64>().unwrap()
}
pub fn serialize<W: Write>(bvh: &Bvh, w: &mut W) -> io::Result<()> {
serialize_hierarchy(&bvh.hierarchy, w)?;
serialize_motion(&bvh.motion, w)?;
Ok(())
}
fn serialize_hierarchy<W: Write>(hierarchy: &Hierarchy, w: &mut W) -> io::Result<()> {
writeln!(w, "HIERARCHY")?;
write!(w, "ROOT ")?;
serialize_joint(&hierarchy.root, w)?;
Ok(())
}
fn serialize_joint<W: Write>(joint: &Joint, w: &mut W) -> io::Result<()> {
writeln!(w, "{}", joint.name)?;
writeln!(w, "{{")?;
serialize_offset(&joint.offset, w)?;
write!(w, "CHANNELS {}", joint.channels.len())?;
for channel in joint.channels.iter() {
match *channel {
Channel::XPosition => write!(w, " Xposition"),
Channel::YPosition => write!(w, " Yposition"),
Channel::ZPosition => write!(w, " Zposition"),
Channel::XRotation => write!(w, " Xrotation"),
Channel::YRotation => write!(w, " Yrotation"),
Channel::ZRotation => write!(w, " Zrotation"),
}?;
}
writeln!(w, "")?;
match joint.children {
JointChildren::Joints(ref joints) => {
for joint in joints.iter() {
write!(w, "JOINT ")?;
serialize_joint(joint, w)?;
}
}
JointChildren::EndSite(ref end_site) => {
writeln!(w, "End Site")?;
writeln!(w, "{{")?;
serialize_offset(&end_site.offset, w)?;
writeln!(w, "}}")?;
}
}
writeln!(w, "}}")?;
Ok(())
}
fn serialize_offset<W: Write>(offset: &Offset, w: &mut W) -> io::Result<()> {
writeln!(w, "OFFSET {} {} {}", offset.x, offset.y, offset.z)
}
fn serialize_motion<W: Write>(motion: &Motion, w: &mut W) -> io::Result<()> {
writeln!(w, "MOTION")?;
writeln!(w, "Frames: {}", motion.num_frames)?;
writeln!(w, "Frame Time: {}", motion.frame_time)?;
for frame in motion.frames.iter() {
for (index, value) in frame.iter().enumerate() {
write!(w, "{}", value)?;
if index % frame.len() != frame.len() - 1 {
write!(w, " ")?;
}
}
writeln!(w, "")?;
}
Ok(())
}
|
use crate::actor::{telegram_receiver::TbReceiverActor, telegram_sender::TbSenderActor};
use crate::clients::create_telegram_client;
use crate::controllers::push_event::register_push_event;
use actix::prelude::*;
use actix::Addr;
use actix_rt::System;
use actix_web::{middleware, web, App, HttpResponse, HttpServer};
use dotenv::dotenv;
use std::env;
mod actor;
mod clients;
mod controllers;
mod errors;
mod model;
fn main() -> std::io::Result<()> {
dotenv().ok();
let sys = System::new("Service Bot");
let env_port: u16 = env::var("ENV_PORT")
.expect("ENV_PORT, not set")
.parse()
.expect("Invalid conversion from String to u16");
let telegram_client = create_telegram_client();
let tb_sender = TbSenderActor(telegram_client.clone());
let tb_sender_addr: Addr<TbSenderActor> = tb_sender.start();
let tb_receiver = TbReceiverActor(telegram_client.clone());
let tb_receiver_addr: Addr<TbReceiverActor> = tb_receiver.start();
println!("Running server on port {port}", port = env_port);
HttpServer::new(move || {
App::new()
.wrap(middleware::Logger::default())
.data(tb_sender_addr.clone())
.data(tb_receiver_addr.clone())
.service(
web::scope("/api").service(
web::scope("/v1")
.service(web::resource("/").to(|| HttpResponse::Ok().json("Test Works")))
.service(
web::resource("/event")
.route(web::post().to_async(register_push_event)),
),
),
)
})
.bind("0.0.0.0:5000")?
.start();
sys.run()
}
|
use std::io;
use std::io::prelude::*;
use std::io::BufReader;
use std::fs::File;
use std::collections::HashMap;
#[derive(Debug)]
pub enum ParseError {
Io(io::Error),
Format(String),
}
impl From<io::Error> for ParseError {
fn from(err: io::Error) -> ParseError {
ParseError::Io(err)
}
}
impl From<String> for ParseError {
fn from(err: String) -> ParseError {
ParseError::Format(err)
}
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Tile {
Food,
Empty,
Pit,
Snake,
}
#[derive(Clone)]
pub struct Map {
data: Vec<Tile>,
pub head: (i32, i32),
pub width: i32,
pub height: i32,
pub food: i32,
}
impl Map {
pub fn new(width: i32, height: i32) -> Map {
Map { data: vec![], width: width, height: height, head: (0, 0), food: 0 }
}
pub fn get(&self, y: i32, x: i32) -> Option<Tile> {
if y >= 0 && y < self.height && x >= 0 && x < self.width {
Some(self.data[(y * self.width + x) as usize])
} else {
None
}
}
pub fn set(&mut self, y: i32, x: i32, tile: Tile) {
self.data[(y * self.width + x) as usize] = tile;
}
pub fn print(&self) {
self.print_with_path(vec![]);
}
pub fn print_with_path(&self, path: Vec<(char, i32, i32)>) {
let path_set: HashMap<(i32, i32), char> = path.iter().map(|&(c, y, x)| ((y, x), c)).collect();
let print_border = || {
print!("+");
for _ in 0..self.width { print!("-"); }
println!("+");
};
print_border();
for y in 0..self.height {
print!("|");
for x in 0..self.width {
let c = match self.get(y, x).unwrap() {
Tile::Empty => ' ',
Tile::Snake => 's',
Tile::Food => '*',
Tile::Pit => 'O',
};
let x = path_set.get(&(y, x)).unwrap_or(&c);
print!("{}", x);
}
println!("|");
}
print_border();
}
}
fn parse_maps(lines: Vec<String>) -> Result<Vec<Map>, ParseError> {
let mut maps = Vec::new();
let mut map = Map::new(0, 0);
for line in lines {
let chars: Vec<char> = line.chars().collect();
if chars.len() < 1 {
continue
}
if chars[0] == '+' {
if line.as_str().contains("map") {
map = Map::new((chars.len() - 2) as i32, 0);
} else {
let h = map.data.iter().position(|&t| t == Tile::Snake).unwrap_or(0) as i32;
map.head = (h / map.width, h % map.width);
map.food = map.data.iter().filter(|&t| *t == Tile::Food).count() as i32;
maps.push(map.clone());
}
continue;
}
for c in chars {
match c {
'|' => continue,
' ' => map.data.push(Tile::Empty),
's' => map.data.push(Tile::Snake),
'*' => map.data.push(Tile::Food),
'O' => map.data.push(Tile::Pit),
x => return Err(ParseError::Format(format!("Unknown char {}", x))),
};
}
map.height += 1;
}
Ok(maps)
}
fn get_lines(path: &str) -> Result<Vec<String>, io::Error> {
let f = try!(File::open(path));
let reader = BufReader::new(f);
let mut lines = Vec::new();
for line in reader.lines() {
lines.push(try!(line));
}
Ok(lines)
}
pub fn parse_input_file(path: &str) -> Result<Vec<Map>, ParseError> {
let lines = try!(get_lines(path));
parse_maps(lines)
}
|
use super::fetch_data::FetchResponse;
use crate::Error;
use rskafka_proto::{
apis::{
fetch::{FetchRequestV4, IsolationLevel, PartitionFetch, TopicFetch},
metadata::TopicMetadata,
offset_fetch::TopicOffsets,
},
BrokerId, ErrorCode, RecordBatch,
};
use rskafka_wire_format::WireFormatBorrowParse;
use std::collections::HashMap;
pub trait FetchStrategy {
fn next_fetch(&mut self) -> (BrokerId, FetchRequestV4);
fn update_fetched(&mut self, r: &FetchResponse);
}
pub struct SimpleFetchStrategy<'a> {
a: &'a AssignmentContext,
offsets: Offsets,
cycle: Box<dyn Iterator<Item = (&'a str, i32)> + Send + 'a>,
leaders: HashMap<(&'a str, i32), BrokerId>,
}
impl<'a> SimpleFetchStrategy<'a> {
pub fn new(a: &'a AssignmentContext, offsets: Offsets) -> Self {
let cycle = a
.assigned_partitions
.iter()
.flat_map(|(t, partitions)| partitions.iter().map(move |p| (t.as_str(), *p)))
.cycle();
let leaders = a
.topic_metadata
.values()
.flat_map(|t| {
t.partitions
.iter()
.map(move |p| ((t.name.as_str(), p.partition_index), p.leader))
})
.collect();
SimpleFetchStrategy {
a,
offsets,
cycle: Box::new(cycle),
leaders,
}
}
}
impl<'a> FetchStrategy for SimpleFetchStrategy<'a> {
fn next_fetch(&mut self) -> (BrokerId, FetchRequestV4) {
let (topic, partition) = self.cycle.next().unwrap();
let broker = *self.leaders.get(&(topic, partition)).unwrap();
let request = FetchRequestV4 {
replica_id: -1,
max_wait_time: 100,
min_bytes: 1024,
max_bytes: 1024 * 1024 * 1024,
isolation_level: IsolationLevel::ReadCommitted,
topics: vec![TopicFetch {
name: topic.to_owned().into(),
partitions: vec![PartitionFetch {
fetch_offset: self.offsets.get(topic, partition).expect("missing offset"), //TODO: error on missing topic
index: partition,
partition_max_bytes: 1024 * 1024 * 1024,
}],
}],
};
(broker, request)
}
fn update_fetched(&mut self, r: &FetchResponse) {
r.partitions().for_each(|(t, p)| {
// let batch = RecordBatch::over_wire_bytes(&p.record_set).unwrap(); // TODO: change batch parsing so it's not parsed twice
// let offset_val = batch.base_offset
// + batch
// .records
// .as_ref()
// .last()
// .map(|r| r.offset_delta.0 as i64)
// .unwrap_or(0);
let offset_val = p.high_watermark; //TODO: Hihgly unsure if this is correct value to use as fetched offset
self.offsets.update(t, p.index, offset_val)
});
}
}
#[derive(Debug)]
pub struct Offsets(HashMap<String, HashMap<i32, i64>>);
impl Offsets {
pub fn from_response(r: Vec<TopicOffsets>) -> Result<Self, Error> {
let mut topics = HashMap::new();
for t in r.into_iter() {
let mut partitions = HashMap::new();
for p in t.partitions {
match p.error_code {
ErrorCode::None => {
partitions.insert(p.index, p.committed_offset + 1);
}
error => return Err(Error::ErrorResponse(error, "offset fetch error".into())),
}
}
topics.insert(t.name, partitions);
}
Ok(Offsets(topics))
}
pub fn update(&mut self, topic: &str, partition: i32, offset: i64) {
let partitions = self.0.get_mut(topic).unwrap(); //TODO: error on missing topic
*partitions.entry(partition).or_default() = offset;
}
pub fn get(&self, topic: &str, partition: i32) -> Option<i64> {
self.0.get(topic).and_then(|t| t.get(&partition).copied())
}
}
#[derive(Debug)]
pub struct AssignmentContext {
pub generation_id: i32,
pub member_id: String,
pub assigned_partitions: HashMap<String, Vec<i32>>,
pub topic_metadata: HashMap<String, TopicMetadata>,
pub coordinator: BrokerId,
}
|
#[macro_export]
macro_rules! remote_type {
//
// Service
//
(
$(#[$meta:meta])*
service $service: ident {
properties: {
$( { $( $property: tt)+ } )*
}
methods: {
$( { $( $method: tt)+ } )*
}
}
) => {
$(#[$meta])*
#[derive(Clone)]
pub struct $service<'a> {
connection: &'a $crate::client::Connection,
}
impl<'a> $service<'a> {
/// Creates a new service using the given `connection`.
pub fn new(connection: &'a $crate::client::Connection) -> Self {
Self { connection }
}
// Properties
$(
remote_type!(@property(service=$service) $( $property )+ );
)*
// Methods
$(
remote_type!(@method(service=$service) $( $method )+ );
)*
}
impl<'a> std::fmt::Debug for $service<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
write!(f, "{}", stringify!($service))
}
}
remote_type!(
@stream_service(service=$service)
properties: {
$( { $( $property)+ } )*
}
methods: {
$( { $( $method)+ } )*
}
);
remote_type!(
@call_service(service=$service)
properties: {
$( { $( $property)+ } )*
}
methods: {
$( { $( $method)+ } )*
}
);
};
//
// Properties
//
(
@property(service=$service:tt)
$prop_name: ident {
$(#[$getter_meta:meta])*
get: $getter_name: ident -> $getter_type: ty $(,
$(#[$setter_meta:meta])*
set: $setter_name: ident ($setter_type: ty) )?
}
) => {
remote_type!(@method(service=$service, prefix=get_)
$( #[$getter_meta] )*
fn $getter_name() -> $getter_type {
$prop_name()
}
);
$(
remote_type!(@method(service=$service, prefix=set_)
$( #[$setter_meta] )*
fn $setter_name(value: $setter_type) {
$prop_name(value)
}
);
)?
};
(
@property(service=$service:tt)
$( $props: tt)*
) => {
compile_error!(concat!("Invalid Service property definition:\n", stringify!($($props)*)));
};
//
// Methods
//
(
@method(service=$service:tt $(, prefix=$prefix:tt)?)
$(#[$meta:meta])*
fn $method_name: ident ($( $arg_name: ident : $arg_type: ty), *) -> $return_type: ty {
$rpc_name: tt($( $arg_expr: expr ),* )
}
) => {
$(#[$meta])*
pub fn $method_name(&self $(, $arg_name : $arg_type)*) -> $crate::client::KrpcResult<$return_type> {
let args: Vec<Vec<u8>> = vec![$($arg_expr.encode()?),*];
let response = self.connection.invoke(stringify!($service),
concat!( $( stringify!($prefix), )? stringify!($rpc_name)),
&args)?;
Ok(<$return_type>::decode(&response, self.connection)?)
}
};
(
@method(service=$service:tt $(, prefix=$prefix:tt)?)
$(#[$meta:meta])*
fn $method_name: ident ($( $arg_name: ident : $arg_type: ty), *) {
$rpc_name: tt($( $arg_expr: expr ),* )
}
) => {
$(#[$meta])*
pub fn $method_name(&self $(, $arg_name : $arg_type)*) -> $crate::client::KrpcResult<()> {
let args: Vec<Vec<u8>> = vec![$($arg_expr.encode()?),*];
self.connection.invoke(stringify!($service),
concat!( $( stringify!($prefix), )? stringify!($rpc_name)),
&args)?;
Ok(())
}
};
(
@method(service=$service:tt $(, prefix=$prefix:tt)?)
$( $methods: tt)*
) => {
compile_error!(concat!("Invalid Service method definition:\n", stringify!($($methods)*)));
};
//
// Service Stream
//
(
@stream_service(service=$service: ident)
properties: {}
methods: {}
) => {
};
(
@stream_service(service=$service: ident)
properties: {
$( { $( $property: tt)+ } )*
}
methods: {
$( { $( $method: tt)+ } )*
}
) => {
paste::item! {
#[derive(Debug, Clone)]
pub struct [<$service Stream>]<'a> {
connection: &'a $crate::client::Connection,
}
impl<'a> $service<'a> {
/// Returns a stream instance that provides streaming versions of the
/// property getters and methods with return values.
pub fn stream(&self) -> [<$service Stream>]<'a> {
[<$service Stream>]::new(self.connection)
}
}
impl<'a> [<$service Stream>]<'a> {
pub fn new(connection: &'a $crate::client::Connection) -> Self {
Self { connection }
}
// Properties
$(
remote_type!(@stream_property(service=$service) $( $property )+ );
)*
// Methods
$(
remote_type!(@stream_method(service=$service) $( $method )+ );
)*
}
}
};
//
// Stream Properties
//
(
@stream_property(service=$service:tt)
$prop_name: ident {
$(#[$getter_meta:meta])*
get: $getter_name: ident -> $getter_type: ty $(,
$(#[$setter_meta:meta])*
set: $setter_name: ident ($setter_type: ty) )?
}
) => {
remote_type!(@stream_method(service=$service, prefix=get_)
$( #[$getter_meta] )*
fn $getter_name() -> $getter_type {
$prop_name()
});
};
(
@stream_property(service=$service:tt)
$( $props: tt)*
) => {
};
//
// Stream Methods
//
(
@stream_method(service=$service:tt $(, prefix=$prefix:tt)?)
$(#[$meta:meta])*
fn $method_name: ident ($( $arg_name: ident : $arg_type: ty), *) -> $return_type: ty {
$rpc_name: tt($( $arg_expr: expr ),* )
}
) => {
$(#[$meta])*
pub fn $method_name(&self $(, $arg_name : $arg_type)*) -> $crate::client::KrpcResult<$crate::client::Stream<$return_type>> {
let args: Vec<Vec<u8>> = vec![$($arg_expr.encode()?),*];
Ok(self.connection.add_stream(
stringify!($service),
concat!( $( stringify!($prefix), )? stringify!($rpc_name)),
&args
)?)
}
};
(
@stream_method(service=$service:tt $(, prefix=$prefix:tt)?)
$(#[$meta:meta])*
fn $method_name: ident ($( $arg_name: ident : $arg_type: ty), *) {
$rpc_name: tt($( $arg_expr: expr ),* )
}
) => {
// This space intentionally left blank
};
(
@stream_method(service=$service:tt $(, prefix=$prefix:tt)?)
$( $methods: tt)*
) => {
};
//
// Service Call
//
(
@call_service(service=$service: ident)
properties: {}
methods: {}
) => {
};
(
@call_service(service=$service: ident)
properties: {
$( { $( $property: tt)+ } )*
}
methods: {
$( { $( $method: tt)+ } )*
}
) => {
paste::item! {
#[derive(Debug, Clone)]
pub struct [<$service Call>]<'a> {
connection: &'a $crate::client::Connection,
}
impl<'a> $service<'a> {
/// Returns a call instance that provides versions of the properties
/// and methods as `ProcedureCall`s.
pub fn call(&self) -> [<$service Call>] {
[<$service Call>]::new(self.connection)
}
}
impl<'a> [<$service Call>]<'a> {
pub fn new(connection: &'a $crate::client::Connection) -> Self {
Self { connection }
}
// Properties
$(
remote_type!(@call_property(service=$service) $( $property )+ );
)*
// Methods
$(
remote_type!(@call_method(service=$service) $( $method )+ );
)*
}
}
};
//
// Call Properties
//
(
@call_property(service=$service:tt)
$prop_name: ident {
$(#[$getter_meta:meta])*
get: $getter_name: ident -> $getter_type: ty $(,
$(#[$setter_meta:meta])*
set: $setter_name: ident ($setter_type: ty) )?
}
) => {
remote_type!(
@call_method(service=$service, prefix=get_)
$( #[$getter_meta] )*
fn $getter_name() -> $getter_type {
$prop_name()
}
);
$(
remote_type!(
@call_method(service=$service, prefix=set_)
$( #[$setter_meta] )*
fn $setter_name(value: $setter_type) {
$prop_name(value)
}
);
)?
};
(
@call_property(service=$service:tt)
$( $props: tt)*
) => {
};
//
// Call Methods
//
(
@call_method(service=$service:tt $(, prefix=$prefix:tt)?)
$(#[$meta:meta])*
fn $method_name: ident ($( $arg_name: ident : $arg_type: ty), *) $( -> $return_type: ty )? {
$rpc_name: tt($( $arg_expr: expr ),* )
}
) => {
$(#[$meta])*
pub fn $method_name(&self $(, $arg_name : $arg_type)*) -> $crate::client::KrpcResult<$crate::client::ProcedureCall> {
let args: Vec<Vec<u8>> = vec![$($arg_expr.encode()?),*];
Ok(self.connection.procedure_call(
stringify!($service),
concat!( $( stringify!($prefix), )? stringify!($rpc_name)),
&args
))
}
};
(
@call_method(service=$service:tt $(, prefix=$prefix:tt)?)
$( $methods: tt)*
) => {
};
//
// Remote Object
//
(
$(#[$meta:meta])*
object $service: tt.$object_name: ident {
$(properties: {
$( { $( $property: tt)+ } )*
})?
$(methods: {
$( { $( $method: tt)+ } )*
})?
$(static_methods: {
$( { $( $static_method: tt)+ } )*
})?
}
) => {
$(#[$meta])*
#[derive(Clone)]
pub struct $object_name<'a> {
#[allow(dead_code)]
connection: &'a $crate::client::Connection,
id: u64
}
impl<'a> $crate::RemoteObject<'a> for $object_name<'a> {
fn new(connection: &'a $crate::client::Connection, id: u64) -> Self {
Self { connection, id }
}
fn id(&self) -> u64 { self.id }
}
impl<'a> $crate::codec::Decode<'a> for $object_name<'a> {
fn decode(bytes: &Vec<u8>, connection: &'a $crate::client::Connection) -> $crate::codec::CodecResult<Self> {
let id = u64::decode(bytes, connection)?;
if id == 0 {
Err(failure::Error::from($crate::codec::CodecError::NullValue))
} else {
Ok($object_name::new(connection, id))
}
}
}
impl<'a> $crate::codec::Decode<'a> for Option<$object_name<'a>> {
fn decode(bytes: &Vec<u8>, connection: &'a $crate::client::Connection) -> $crate::codec::CodecResult<Self> {
let id = u64::decode(bytes, connection)?;
if id == 0 {
Ok(None)
} else {
Ok(Some($object_name::new(connection, id)))
}
}
}
impl<'a> $crate::codec::Encode for $object_name<'a> {
fn encode(&self) -> $crate::codec::CodecResult<Vec<u8>> {
self.id().encode()
}
}
impl<'a> $crate::codec::Encode for Option<$object_name<'a>> {
fn encode(&self) -> $crate::codec::CodecResult<Vec<u8>> {
match self {
None => (0 as u64).encode(),
Some(obj) => obj.id().encode()
}
}
}
impl<'a> $crate::codec::Encode for Option<&$object_name<'a>> {
fn encode(&self) -> $crate::codec::CodecResult<Vec<u8>> {
match self {
None => (0 as u64).encode(),
Some(ref obj) => obj.id().encode()
}
}
}
impl<'a> std::fmt::Debug for $object_name<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
write!(f, "{}.{}{{ id: {} }}", stringify!($service), stringify!($object_name), self.id)
}
}
impl<'a> $object_name<'a> {
// Properties
$(
$(
remote_type!(@property(service=$service, class=$object_name) $( $property )+ );
)*
)?
// Methods
$(
$(
remote_type!(@method(service=$service, class=$object_name, separator=_) $( $method )+ );
)*
)?
// Static Methods
$(
$(
remote_type!(@static_method(service=$service, class=$object_name) $( $static_method )+ );
)*
)?
}
remote_type!(
@stream_remote_object(service=$service, class=$object_name)
properties: {
$( $( { $( $property)+ } )* )?
}
methods: {
$( $( { $( $method)+ } )* )?
}
);
remote_type!(
@call_remote_object(service=$service, class=$object_name)
properties: {
$( $( { $( $property)+ } )* )?
}
methods: {
$( $( { $( $method)+ } )* )?
}
);
};
//
// Properties
//
(
@property(service=$service:tt, class=$class:tt)
$prop_name: ident {
$(#[$getter_meta:meta])*
get: $getter_name: ident -> $getter_type: ty $(,
$(#[$setter_meta:meta])*
set: $setter_name: ident ($setter_type: ty) )?
}
) => {
remote_type!(@method(service=$service, class=$class, separator=_get_)
$( #[$getter_meta] )*
fn $getter_name() -> $getter_type {
$prop_name()
}
);
$(
remote_type!(@method(service=$service, class=$class, separator=_set_)
$( #[$setter_meta] )*
fn $setter_name(value: $setter_type) {
$prop_name(value)
}
);
)?
};
(
@property(service=$service:tt, class=$class:tt)
$( $props: tt)*
) => {
compile_error!(concat!("Invalid Remote Object property definition:\n", stringify!($($props)*)));
};
//
// Methods
//
(
@method(service=$service:tt, class=$class:tt, separator=$separator:tt)
$(#[$meta:meta])*
fn $method_name: ident ($( $arg_name: ident : $arg_type: ty), *) -> $return_type: ty {
$rpc_name: tt($( $arg_expr: expr ),* )
}
) => {
$(#[$meta])*
pub fn $method_name(&self $(, $arg_name : $arg_type)*) -> $crate::client::KrpcResult<$return_type> {
let args: Vec<Vec<u8>> = vec![self.encode()? $(, $arg_expr.encode()?)*];
let response = self.connection.invoke(stringify!($service),
concat!( stringify!($class), stringify!($separator), stringify!($rpc_name)),
&args)?;
Ok(<$return_type>::decode(&response, self.connection)?)
}
};
(
@method(service=$service:tt, class=$class:tt, separator=$separator:tt)
$(#[$meta:meta])*
fn $method_name: ident ($( $arg_name: ident : $arg_type: ty), *) {
$rpc_name: tt($( $arg_expr: expr ),* )
}
) => {
$(#[$meta])*
pub fn $method_name(&self $(, $arg_name : $arg_type)*) -> $crate::client::KrpcResult<()> {
let args: Vec<Vec<u8>> = vec![self.encode()? $(, $arg_expr.encode()?)*];
self.connection.invoke(stringify!($service),
concat!( stringify!($class), stringify!($separator), stringify!($rpc_name)),
&args)?;
Ok(())
}
};
(
@method(service=$service:tt, class=$class:tt, separator=$separator:tt)
$( $methods: tt)*
) => {
compile_error!(concat!("Invalid Remote Object method definition:\n", stringify!($($methods)*)));
};
//
// Static Methods
//
(
@static_method(service=$service:tt, class=$class:tt)
$(#[$meta:meta])*
fn $method_name: ident ($( $arg_name: ident : $arg_type: ty), *) -> $return_type: ty {
$rpc_name: tt($( $arg_expr: expr ),* )
}
) => {
$(#[$meta])*
pub fn $method_name(connection: &'a $crate::client::Connection $(, $arg_name : $arg_type)*) -> $crate::client::KrpcResult<$return_type> {
let args: Vec<Vec<u8>> = vec![$($arg_expr.encode()?),*];
let response = connection.invoke(stringify!($service),
concat!( stringify!($class), "_static_", stringify!($rpc_name)),
&args)?;
Ok(<$return_type>::decode(&response, connection)?)
}
};
(
@static_method(service=$service:tt, class=$class:tt)
$( $methods: tt)*
) => {
compile_error!(concat!("Invalid Remote Object static method definition:\n", stringify!($($methods)*)));
};
//
// Remote Object Stream
//
(
@stream_remote_object(service=$service: ident, class=$object_name: ident)
properties: {}
methods: {}
) => {
};
(
@stream_remote_object(service=$service: ident, class=$object_name: ident)
properties: {
$( { $( $property: tt)+ } )*
}
methods: {
$( { $( $method: tt)+ } )*
}
) => {
paste::item! {
#[derive(Debug, Clone)]
pub struct [<$object_name Stream>]<'a> {
connection: &'a $crate::client::Connection,
id: u64
}
impl<'a> $object_name<'a> {
/// Returns a stream instance that provides streaming versions of the
/// property getters and methods with return values.
pub fn stream(&self) -> [<$object_name Stream>]<'a> {
[<$object_name Stream>]::new(self)
}
}
impl<'a> [<$object_name Stream>]<'a> {
pub fn new(remote_object: &$object_name<'a>) -> Self {
Self {
connection: remote_object.connection,
id: remote_object.id
}
}
// Properties
$(
remote_type!(@stream_property(service=$service, class=$object_name) $( $property )+ );
)*
// Methods
$(
remote_type!(@stream_method(service=$service, class=$object_name, separator=_) $( $method )+ );
)*
}
}
};
//
// Stream Properties
//
(
@stream_property(service=$service:tt, class=$class:tt)
$prop_name: ident {
$(#[$getter_meta:meta])*
get: $getter_name: ident -> $getter_type: ty $(,
$(#[$setter_meta:meta])*
set: $setter_name: ident ($setter_type: ty) )?
}
) => {
remote_type!(@stream_method(service=$service, class=$class, separator=_get_)
$( #[$getter_meta] )*
fn $getter_name() -> $getter_type {
$prop_name()
});
};
(
@stream_property(service=$service:tt, class=$class:tt)
$( $props: tt)*
) => {
// silently ignore since it should be caught by the normal property definition
};
//
// Stream Methods
//
(
@stream_method(service=$service:tt, class=$class:tt, separator=$separator:tt)
$(#[$meta:meta])*
fn $method_name: ident ($( $arg_name: ident : $arg_type: ty), *) -> $return_type: ty {
$rpc_name: tt($( $arg_expr: expr ),* )
}
) => {
$(#[$meta])*
pub fn $method_name(&self $(, $arg_name : $arg_type)*) -> $crate::client::KrpcResult<$crate::client::Stream<$return_type>> {
let args: Vec<Vec<u8>> = vec![self.id.encode()? $(, $arg_expr.encode()?)*];
Ok(self.connection.add_stream(
stringify!($service),
concat!( stringify!($class), stringify!($separator), stringify!($rpc_name)),
&args
)?)
}
};
(
@stream_method(service=$service:tt, class=$class:tt, separator=$separator:tt)
$(#[$meta:meta])*
fn $method_name: ident ($( $arg_name: ident : $arg_type: ty), *) {
$rpc_name: tt($( $arg_expr: expr ),* )
}
) => {
// This space intentionally left blank
};
(
@stream_method(service=$service:tt, class=$class:tt, separator=$separator:tt)
$( $methods: tt)*
) => {
};
//
// Remote Object Call
//
(
@call_remote_object(service=$service: ident, class=$object_name: ident)
properties: {}
methods: {}
) => {
};
(
@call_remote_object(service=$service: ident, class=$object_name: ident)
properties: {
$( { $( $property: tt)+ } )*
}
methods: {
$( { $( $method: tt)+ } )*
}
) => {
paste::item! {
#[derive(Debug, Clone)]
pub struct [<$object_name Call>]<'a> {
connection: &'a $crate::client::Connection,
id: u64
}
impl<'a> $object_name<'a> {
/// Returns a call instance that provides versions of the properties
/// and methods as `ProcedureCall`s.
pub fn call(&self) -> [<$object_name Call>] {
[<$object_name Call>]::new(self)
}
}
impl<'a> [<$object_name Call>]<'a> {
pub fn new(remote_object: &$object_name<'a>) -> Self {
Self {
connection: remote_object.connection,
id: remote_object.id
}
}
// Propertie
$(
remote_type!(@call_property(service=$service, class=$object_name) $( $property )+ );
)*
// Methods
$(
remote_type!(@call_method(service=$service, class=$object_name, separator=_) $( $method )+ );
)*
}
}
};
//
// Call Properties
//
(
@call_property(service=$service:tt, class=$class:tt)
$prop_name: ident {
$(#[$getter_meta:meta])*
get: $getter_name: ident -> $getter_type: ty $(,
$(#[$setter_meta:meta])*
set: $setter_name: ident ($setter_type: ty) )?
}
) => {
remote_type!(
@call_method(service=$service, class=$class, separator=_get_)
$( #[$getter_meta] )*
fn $getter_name() -> $getter_type {
$prop_name()
}
);
$(
remote_type!(
@call_method(service=$service, class=$class, separator=_set_)
$( #[$setter_meta] )*
fn $setter_name(value: $setter_type) {
$prop_name(value)
}
);
)?
};
(
@call_property(service=$service:tt, class=$class:tt)
$( $props: tt)*
) => {
// silently ignore since it should be caught by the normal property definition
};
//
// Call Methods
//
(
@call_method(service=$service:tt, class=$class:tt, separator=$separator:tt)
$(#[$meta:meta])*
fn $method_name: ident ($( $arg_name: ident : $arg_type: ty), *) $( -> $return_type: ty )? {
$rpc_name: tt($( $arg_expr: expr ),* )
}
) => {
$(#[$meta])*
pub fn $method_name(&self $(, $arg_name : $arg_type)*) -> $crate::client::KrpcResult<$crate::client::ProcedureCall> {
let args: Vec<Vec<u8>> = vec![self.id.encode()? $(, $arg_expr.encode()?)*];
Ok(self.connection.procedure_call(
stringify!($service),
concat!( stringify!($class), stringify!($separator), stringify!($rpc_name)),
&args,
))
}
};
(
@call_method(service=$service:tt, class=$class:tt, separator=$separator:tt)
$( $methods: tt)*
) => {
};
//
// Remote Enum
//
( $(#[$enum_meta:meta])*
enum $enum_name: ident {
$( $(#[$variant_meta:meta])* $value_name: ident = $value_int : expr),+ $(,)?
}) => {
$(#[$enum_meta])*
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)]
pub enum $enum_name {
$(
$(#[$variant_meta])*
$value_name = $value_int
),+
}
impl $crate::RemoteEnum for $enum_name {
fn from_value(value: i64) -> Option<Self> {
match value {
$( $value_int => Some($enum_name::$value_name)),+,
_ => None
}
}
fn value(&self) -> i64 {
*self as i64
}
}
impl<'a> $crate::codec::Decode<'a> for $enum_name {
fn decode(bytes: &Vec<u8>, connection: &'a $crate::client::Connection) -> $crate::codec::CodecResult<Self> {
let value = i64::decode(bytes, connection)?;
Ok(Self::from_value(value)
.ok_or($crate::codec::CodecError::InvalidEnumValue(value))?)
}
}
impl $crate::codec::Encode for $enum_name {
fn encode(&self) -> $crate::codec::CodecResult<Vec<u8>> {
self.value().encode()
}
}
}
}
|
use std::fmt::{Debug, Display};
use async_trait::async_trait;
use data_types::{Namespace, NamespaceId, NamespaceSchema};
pub mod catalog;
pub mod mock;
#[async_trait]
pub trait NamespacesSource: Debug + Display + Send + Sync {
/// Get Namespace for a given namespace
///
/// This method performs retries.
async fn fetch_by_id(&self, ns: NamespaceId) -> Option<Namespace>;
/// Get NamespaceSchema for a given namespace
///
/// todo: make this method perform retries.
async fn fetch_schema_by_id(&self, ns: NamespaceId) -> Option<NamespaceSchema>;
}
|
// Copyright © 2017-2023 Trust Wallet.
//
// This file is part of Trust. The full Trust copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
use std::ffi::CString;
use tw_encoding::ffi::{decode_base58, encode_base58, Base58Alphabet};
#[test]
fn test_base58_encode() {
let data = b"Hello, world!";
let expected = "72k1xXWG59wUsYv7h2";
let result_ptr = unsafe { encode_base58(data.as_ptr(), data.len(), Base58Alphabet::Bitcoin) };
let result = unsafe { CString::from_raw(result_ptr) };
assert_eq!(result.to_str().unwrap(), expected);
}
#[test]
fn test_base58_decode() {
let data = "72k1xXWG59wUsYv7h2";
let expected = b"Hello, world!";
let input = CString::new(data).unwrap();
let decoded_ptr = unsafe { decode_base58(input.as_ptr(), Base58Alphabet::Bitcoin) };
let decoded_slice = unsafe { std::slice::from_raw_parts(decoded_ptr.data, decoded_ptr.size) };
assert_eq!(decoded_slice, expected);
}
|
//! GDAL Raster Data
mod rasterband;
mod types;
mod warp;
pub use rasterband::{Buffer, ByteBuffer, ColorInterpretation, RasterBand, ResampleAlg};
pub use types::{GDALDataType, GdalType};
pub use warp::reproject;
#[derive(Debug)]
pub struct RasterCreationOption<'a> {
pub key: &'a str,
pub value: &'a str,
}
#[cfg(test)]
mod tests;
|
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtWidgets/qprogressdialog.h
// dst-file: /src/widgets/qprogressdialog.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block begin =>
// <= main block end
// use block begin =>
use super::qdialog::*; // 773
use std::ops::Deref;
use super::super::core::qobject::*; // 771
use super::super::core::qstring::*; // 771
use super::qwidget::*; // 773
use super::qprogressbar::*; // 773
use super::super::core::qsize::*; // 771
use super::qlabel::*; // 773
use super::super::core::qobjectdefs::*; // 771
use super::qpushbutton::*; // 773
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QProgressDialog_Class_Size() -> c_int;
// proto: void QProgressDialog::setAutoClose(bool close);
fn C_ZN15QProgressDialog12setAutoCloseEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: void QProgressDialog::open(QObject * receiver, const char * member);
fn C_ZN15QProgressDialog4openEP7QObjectPKc(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_char);
// proto: void QProgressDialog::setMaximum(int maximum);
fn C_ZN15QProgressDialog10setMaximumEi(qthis: u64 /* *mut c_void*/, arg0: c_int);
// proto: void QProgressDialog::setMinimum(int minimum);
fn C_ZN15QProgressDialog10setMinimumEi(qthis: u64 /* *mut c_void*/, arg0: c_int);
// proto: void QProgressDialog::setLabelText(const QString & text);
fn C_ZN15QProgressDialog12setLabelTextERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: bool QProgressDialog::wasCanceled();
fn C_ZNK15QProgressDialog11wasCanceledEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QProgressDialog::~QProgressDialog();
fn C_ZN15QProgressDialogD2Ev(qthis: u64 /* *mut c_void*/);
// proto: int QProgressDialog::minimumDuration();
fn C_ZNK15QProgressDialog15minimumDurationEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: void QProgressDialog::setMinimumDuration(int ms);
fn C_ZN15QProgressDialog18setMinimumDurationEi(qthis: u64 /* *mut c_void*/, arg0: c_int);
// proto: int QProgressDialog::maximum();
fn C_ZNK15QProgressDialog7maximumEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: void QProgressDialog::setBar(QProgressBar * bar);
fn C_ZN15QProgressDialog6setBarEP12QProgressBar(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QProgressDialog::cancel();
fn C_ZN15QProgressDialog6cancelEv(qthis: u64 /* *mut c_void*/);
// proto: bool QProgressDialog::autoClose();
fn C_ZNK15QProgressDialog9autoCloseEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: int QProgressDialog::minimum();
fn C_ZNK15QProgressDialog7minimumEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: bool QProgressDialog::autoReset();
fn C_ZNK15QProgressDialog9autoResetEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QProgressDialog::reset();
fn C_ZN15QProgressDialog5resetEv(qthis: u64 /* *mut c_void*/);
// proto: void QProgressDialog::setRange(int minimum, int maximum);
fn C_ZN15QProgressDialog8setRangeEii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int);
// proto: void QProgressDialog::setCancelButtonText(const QString & text);
fn C_ZN15QProgressDialog19setCancelButtonTextERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QSize QProgressDialog::sizeHint();
fn C_ZNK15QProgressDialog8sizeHintEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QString QProgressDialog::labelText();
fn C_ZNK15QProgressDialog9labelTextEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QProgressDialog::setLabel(QLabel * label);
fn C_ZN15QProgressDialog8setLabelEP6QLabel(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: const QMetaObject * QProgressDialog::metaObject();
fn C_ZNK15QProgressDialog10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QProgressDialog::setAutoReset(bool reset);
fn C_ZN15QProgressDialog12setAutoResetEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: int QProgressDialog::value();
fn C_ZNK15QProgressDialog5valueEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: void QProgressDialog::setCancelButton(QPushButton * button);
fn C_ZN15QProgressDialog15setCancelButtonEP11QPushButton(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QProgressDialog::setValue(int progress);
fn C_ZN15QProgressDialog8setValueEi(qthis: u64 /* *mut c_void*/, arg0: c_int);
fn QProgressDialog_SlotProxy_connect__ZN15QProgressDialog8canceledEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
} // <= ext block end
// body block begin =>
// class sizeof(QProgressDialog)=1
#[derive(Default)]
pub struct QProgressDialog {
qbase: QDialog,
pub qclsinst: u64 /* *mut c_void*/,
pub _canceled: QProgressDialog_canceled_signal,
}
impl /*struct*/ QProgressDialog {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QProgressDialog {
return QProgressDialog{qbase: QDialog::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
}
}
impl Deref for QProgressDialog {
type Target = QDialog;
fn deref(&self) -> &QDialog {
return & self.qbase;
}
}
impl AsRef<QDialog> for QProgressDialog {
fn as_ref(& self) -> & QDialog {
return & self.qbase;
}
}
// proto: void QProgressDialog::setAutoClose(bool close);
impl /*struct*/ QProgressDialog {
pub fn setAutoClose<RetType, T: QProgressDialog_setAutoClose<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setAutoClose(self);
// return 1;
}
}
pub trait QProgressDialog_setAutoClose<RetType> {
fn setAutoClose(self , rsthis: & QProgressDialog) -> RetType;
}
// proto: void QProgressDialog::setAutoClose(bool close);
impl<'a> /*trait*/ QProgressDialog_setAutoClose<()> for (i8) {
fn setAutoClose(self , rsthis: & QProgressDialog) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QProgressDialog12setAutoCloseEb()};
let arg0 = self as c_char;
unsafe {C_ZN15QProgressDialog12setAutoCloseEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QProgressDialog::open(QObject * receiver, const char * member);
impl /*struct*/ QProgressDialog {
pub fn open<RetType, T: QProgressDialog_open<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.open(self);
// return 1;
}
}
pub trait QProgressDialog_open<RetType> {
fn open(self , rsthis: & QProgressDialog) -> RetType;
}
// proto: void QProgressDialog::open(QObject * receiver, const char * member);
impl<'a> /*trait*/ QProgressDialog_open<()> for (&'a QObject, &'a String) {
fn open(self , rsthis: & QProgressDialog) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QProgressDialog4openEP7QObjectPKc()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.as_ptr() as *mut c_char;
unsafe {C_ZN15QProgressDialog4openEP7QObjectPKc(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QProgressDialog::setMaximum(int maximum);
impl /*struct*/ QProgressDialog {
pub fn setMaximum<RetType, T: QProgressDialog_setMaximum<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setMaximum(self);
// return 1;
}
}
pub trait QProgressDialog_setMaximum<RetType> {
fn setMaximum(self , rsthis: & QProgressDialog) -> RetType;
}
// proto: void QProgressDialog::setMaximum(int maximum);
impl<'a> /*trait*/ QProgressDialog_setMaximum<()> for (i32) {
fn setMaximum(self , rsthis: & QProgressDialog) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QProgressDialog10setMaximumEi()};
let arg0 = self as c_int;
unsafe {C_ZN15QProgressDialog10setMaximumEi(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QProgressDialog::setMinimum(int minimum);
impl /*struct*/ QProgressDialog {
pub fn setMinimum<RetType, T: QProgressDialog_setMinimum<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setMinimum(self);
// return 1;
}
}
pub trait QProgressDialog_setMinimum<RetType> {
fn setMinimum(self , rsthis: & QProgressDialog) -> RetType;
}
// proto: void QProgressDialog::setMinimum(int minimum);
impl<'a> /*trait*/ QProgressDialog_setMinimum<()> for (i32) {
fn setMinimum(self , rsthis: & QProgressDialog) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QProgressDialog10setMinimumEi()};
let arg0 = self as c_int;
unsafe {C_ZN15QProgressDialog10setMinimumEi(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QProgressDialog::setLabelText(const QString & text);
impl /*struct*/ QProgressDialog {
pub fn setLabelText<RetType, T: QProgressDialog_setLabelText<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setLabelText(self);
// return 1;
}
}
pub trait QProgressDialog_setLabelText<RetType> {
fn setLabelText(self , rsthis: & QProgressDialog) -> RetType;
}
// proto: void QProgressDialog::setLabelText(const QString & text);
impl<'a> /*trait*/ QProgressDialog_setLabelText<()> for (&'a QString) {
fn setLabelText(self , rsthis: & QProgressDialog) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QProgressDialog12setLabelTextERK7QString()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN15QProgressDialog12setLabelTextERK7QString(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: bool QProgressDialog::wasCanceled();
impl /*struct*/ QProgressDialog {
pub fn wasCanceled<RetType, T: QProgressDialog_wasCanceled<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.wasCanceled(self);
// return 1;
}
}
pub trait QProgressDialog_wasCanceled<RetType> {
fn wasCanceled(self , rsthis: & QProgressDialog) -> RetType;
}
// proto: bool QProgressDialog::wasCanceled();
impl<'a> /*trait*/ QProgressDialog_wasCanceled<i8> for () {
fn wasCanceled(self , rsthis: & QProgressDialog) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK15QProgressDialog11wasCanceledEv()};
let mut ret = unsafe {C_ZNK15QProgressDialog11wasCanceledEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QProgressDialog::~QProgressDialog();
impl /*struct*/ QProgressDialog {
pub fn free<RetType, T: QProgressDialog_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QProgressDialog_free<RetType> {
fn free(self , rsthis: & QProgressDialog) -> RetType;
}
// proto: void QProgressDialog::~QProgressDialog();
impl<'a> /*trait*/ QProgressDialog_free<()> for () {
fn free(self , rsthis: & QProgressDialog) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QProgressDialogD2Ev()};
unsafe {C_ZN15QProgressDialogD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: int QProgressDialog::minimumDuration();
impl /*struct*/ QProgressDialog {
pub fn minimumDuration<RetType, T: QProgressDialog_minimumDuration<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.minimumDuration(self);
// return 1;
}
}
pub trait QProgressDialog_minimumDuration<RetType> {
fn minimumDuration(self , rsthis: & QProgressDialog) -> RetType;
}
// proto: int QProgressDialog::minimumDuration();
impl<'a> /*trait*/ QProgressDialog_minimumDuration<i32> for () {
fn minimumDuration(self , rsthis: & QProgressDialog) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK15QProgressDialog15minimumDurationEv()};
let mut ret = unsafe {C_ZNK15QProgressDialog15minimumDurationEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: void QProgressDialog::setMinimumDuration(int ms);
impl /*struct*/ QProgressDialog {
pub fn setMinimumDuration<RetType, T: QProgressDialog_setMinimumDuration<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setMinimumDuration(self);
// return 1;
}
}
pub trait QProgressDialog_setMinimumDuration<RetType> {
fn setMinimumDuration(self , rsthis: & QProgressDialog) -> RetType;
}
// proto: void QProgressDialog::setMinimumDuration(int ms);
impl<'a> /*trait*/ QProgressDialog_setMinimumDuration<()> for (i32) {
fn setMinimumDuration(self , rsthis: & QProgressDialog) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QProgressDialog18setMinimumDurationEi()};
let arg0 = self as c_int;
unsafe {C_ZN15QProgressDialog18setMinimumDurationEi(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: int QProgressDialog::maximum();
impl /*struct*/ QProgressDialog {
pub fn maximum<RetType, T: QProgressDialog_maximum<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.maximum(self);
// return 1;
}
}
pub trait QProgressDialog_maximum<RetType> {
fn maximum(self , rsthis: & QProgressDialog) -> RetType;
}
// proto: int QProgressDialog::maximum();
impl<'a> /*trait*/ QProgressDialog_maximum<i32> for () {
fn maximum(self , rsthis: & QProgressDialog) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK15QProgressDialog7maximumEv()};
let mut ret = unsafe {C_ZNK15QProgressDialog7maximumEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: void QProgressDialog::setBar(QProgressBar * bar);
impl /*struct*/ QProgressDialog {
pub fn setBar<RetType, T: QProgressDialog_setBar<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setBar(self);
// return 1;
}
}
pub trait QProgressDialog_setBar<RetType> {
fn setBar(self , rsthis: & QProgressDialog) -> RetType;
}
// proto: void QProgressDialog::setBar(QProgressBar * bar);
impl<'a> /*trait*/ QProgressDialog_setBar<()> for (&'a QProgressBar) {
fn setBar(self , rsthis: & QProgressDialog) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QProgressDialog6setBarEP12QProgressBar()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN15QProgressDialog6setBarEP12QProgressBar(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QProgressDialog::cancel();
impl /*struct*/ QProgressDialog {
pub fn cancel<RetType, T: QProgressDialog_cancel<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.cancel(self);
// return 1;
}
}
pub trait QProgressDialog_cancel<RetType> {
fn cancel(self , rsthis: & QProgressDialog) -> RetType;
}
// proto: void QProgressDialog::cancel();
impl<'a> /*trait*/ QProgressDialog_cancel<()> for () {
fn cancel(self , rsthis: & QProgressDialog) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QProgressDialog6cancelEv()};
unsafe {C_ZN15QProgressDialog6cancelEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: bool QProgressDialog::autoClose();
impl /*struct*/ QProgressDialog {
pub fn autoClose<RetType, T: QProgressDialog_autoClose<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.autoClose(self);
// return 1;
}
}
pub trait QProgressDialog_autoClose<RetType> {
fn autoClose(self , rsthis: & QProgressDialog) -> RetType;
}
// proto: bool QProgressDialog::autoClose();
impl<'a> /*trait*/ QProgressDialog_autoClose<i8> for () {
fn autoClose(self , rsthis: & QProgressDialog) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK15QProgressDialog9autoCloseEv()};
let mut ret = unsafe {C_ZNK15QProgressDialog9autoCloseEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: int QProgressDialog::minimum();
impl /*struct*/ QProgressDialog {
pub fn minimum<RetType, T: QProgressDialog_minimum<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.minimum(self);
// return 1;
}
}
pub trait QProgressDialog_minimum<RetType> {
fn minimum(self , rsthis: & QProgressDialog) -> RetType;
}
// proto: int QProgressDialog::minimum();
impl<'a> /*trait*/ QProgressDialog_minimum<i32> for () {
fn minimum(self , rsthis: & QProgressDialog) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK15QProgressDialog7minimumEv()};
let mut ret = unsafe {C_ZNK15QProgressDialog7minimumEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: bool QProgressDialog::autoReset();
impl /*struct*/ QProgressDialog {
pub fn autoReset<RetType, T: QProgressDialog_autoReset<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.autoReset(self);
// return 1;
}
}
pub trait QProgressDialog_autoReset<RetType> {
fn autoReset(self , rsthis: & QProgressDialog) -> RetType;
}
// proto: bool QProgressDialog::autoReset();
impl<'a> /*trait*/ QProgressDialog_autoReset<i8> for () {
fn autoReset(self , rsthis: & QProgressDialog) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK15QProgressDialog9autoResetEv()};
let mut ret = unsafe {C_ZNK15QProgressDialog9autoResetEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QProgressDialog::reset();
impl /*struct*/ QProgressDialog {
pub fn reset<RetType, T: QProgressDialog_reset<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.reset(self);
// return 1;
}
}
pub trait QProgressDialog_reset<RetType> {
fn reset(self , rsthis: & QProgressDialog) -> RetType;
}
// proto: void QProgressDialog::reset();
impl<'a> /*trait*/ QProgressDialog_reset<()> for () {
fn reset(self , rsthis: & QProgressDialog) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QProgressDialog5resetEv()};
unsafe {C_ZN15QProgressDialog5resetEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QProgressDialog::setRange(int minimum, int maximum);
impl /*struct*/ QProgressDialog {
pub fn setRange<RetType, T: QProgressDialog_setRange<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setRange(self);
// return 1;
}
}
pub trait QProgressDialog_setRange<RetType> {
fn setRange(self , rsthis: & QProgressDialog) -> RetType;
}
// proto: void QProgressDialog::setRange(int minimum, int maximum);
impl<'a> /*trait*/ QProgressDialog_setRange<()> for (i32, i32) {
fn setRange(self , rsthis: & QProgressDialog) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QProgressDialog8setRangeEii()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
unsafe {C_ZN15QProgressDialog8setRangeEii(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QProgressDialog::setCancelButtonText(const QString & text);
impl /*struct*/ QProgressDialog {
pub fn setCancelButtonText<RetType, T: QProgressDialog_setCancelButtonText<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setCancelButtonText(self);
// return 1;
}
}
pub trait QProgressDialog_setCancelButtonText<RetType> {
fn setCancelButtonText(self , rsthis: & QProgressDialog) -> RetType;
}
// proto: void QProgressDialog::setCancelButtonText(const QString & text);
impl<'a> /*trait*/ QProgressDialog_setCancelButtonText<()> for (&'a QString) {
fn setCancelButtonText(self , rsthis: & QProgressDialog) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QProgressDialog19setCancelButtonTextERK7QString()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN15QProgressDialog19setCancelButtonTextERK7QString(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QSize QProgressDialog::sizeHint();
impl /*struct*/ QProgressDialog {
pub fn sizeHint<RetType, T: QProgressDialog_sizeHint<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.sizeHint(self);
// return 1;
}
}
pub trait QProgressDialog_sizeHint<RetType> {
fn sizeHint(self , rsthis: & QProgressDialog) -> RetType;
}
// proto: QSize QProgressDialog::sizeHint();
impl<'a> /*trait*/ QProgressDialog_sizeHint<QSize> for () {
fn sizeHint(self , rsthis: & QProgressDialog) -> QSize {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK15QProgressDialog8sizeHintEv()};
let mut ret = unsafe {C_ZNK15QProgressDialog8sizeHintEv(rsthis.qclsinst)};
let mut ret1 = QSize::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QString QProgressDialog::labelText();
impl /*struct*/ QProgressDialog {
pub fn labelText<RetType, T: QProgressDialog_labelText<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.labelText(self);
// return 1;
}
}
pub trait QProgressDialog_labelText<RetType> {
fn labelText(self , rsthis: & QProgressDialog) -> RetType;
}
// proto: QString QProgressDialog::labelText();
impl<'a> /*trait*/ QProgressDialog_labelText<QString> for () {
fn labelText(self , rsthis: & QProgressDialog) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK15QProgressDialog9labelTextEv()};
let mut ret = unsafe {C_ZNK15QProgressDialog9labelTextEv(rsthis.qclsinst)};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QProgressDialog::setLabel(QLabel * label);
impl /*struct*/ QProgressDialog {
pub fn setLabel<RetType, T: QProgressDialog_setLabel<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setLabel(self);
// return 1;
}
}
pub trait QProgressDialog_setLabel<RetType> {
fn setLabel(self , rsthis: & QProgressDialog) -> RetType;
}
// proto: void QProgressDialog::setLabel(QLabel * label);
impl<'a> /*trait*/ QProgressDialog_setLabel<()> for (&'a QLabel) {
fn setLabel(self , rsthis: & QProgressDialog) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QProgressDialog8setLabelEP6QLabel()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN15QProgressDialog8setLabelEP6QLabel(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: const QMetaObject * QProgressDialog::metaObject();
impl /*struct*/ QProgressDialog {
pub fn metaObject<RetType, T: QProgressDialog_metaObject<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.metaObject(self);
// return 1;
}
}
pub trait QProgressDialog_metaObject<RetType> {
fn metaObject(self , rsthis: & QProgressDialog) -> RetType;
}
// proto: const QMetaObject * QProgressDialog::metaObject();
impl<'a> /*trait*/ QProgressDialog_metaObject<QMetaObject> for () {
fn metaObject(self , rsthis: & QProgressDialog) -> QMetaObject {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK15QProgressDialog10metaObjectEv()};
let mut ret = unsafe {C_ZNK15QProgressDialog10metaObjectEv(rsthis.qclsinst)};
let mut ret1 = QMetaObject::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QProgressDialog::setAutoReset(bool reset);
impl /*struct*/ QProgressDialog {
pub fn setAutoReset<RetType, T: QProgressDialog_setAutoReset<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setAutoReset(self);
// return 1;
}
}
pub trait QProgressDialog_setAutoReset<RetType> {
fn setAutoReset(self , rsthis: & QProgressDialog) -> RetType;
}
// proto: void QProgressDialog::setAutoReset(bool reset);
impl<'a> /*trait*/ QProgressDialog_setAutoReset<()> for (i8) {
fn setAutoReset(self , rsthis: & QProgressDialog) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QProgressDialog12setAutoResetEb()};
let arg0 = self as c_char;
unsafe {C_ZN15QProgressDialog12setAutoResetEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: int QProgressDialog::value();
impl /*struct*/ QProgressDialog {
pub fn value<RetType, T: QProgressDialog_value<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.value(self);
// return 1;
}
}
pub trait QProgressDialog_value<RetType> {
fn value(self , rsthis: & QProgressDialog) -> RetType;
}
// proto: int QProgressDialog::value();
impl<'a> /*trait*/ QProgressDialog_value<i32> for () {
fn value(self , rsthis: & QProgressDialog) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK15QProgressDialog5valueEv()};
let mut ret = unsafe {C_ZNK15QProgressDialog5valueEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: void QProgressDialog::setCancelButton(QPushButton * button);
impl /*struct*/ QProgressDialog {
pub fn setCancelButton<RetType, T: QProgressDialog_setCancelButton<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setCancelButton(self);
// return 1;
}
}
pub trait QProgressDialog_setCancelButton<RetType> {
fn setCancelButton(self , rsthis: & QProgressDialog) -> RetType;
}
// proto: void QProgressDialog::setCancelButton(QPushButton * button);
impl<'a> /*trait*/ QProgressDialog_setCancelButton<()> for (&'a QPushButton) {
fn setCancelButton(self , rsthis: & QProgressDialog) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QProgressDialog15setCancelButtonEP11QPushButton()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN15QProgressDialog15setCancelButtonEP11QPushButton(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QProgressDialog::setValue(int progress);
impl /*struct*/ QProgressDialog {
pub fn setValue<RetType, T: QProgressDialog_setValue<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setValue(self);
// return 1;
}
}
pub trait QProgressDialog_setValue<RetType> {
fn setValue(self , rsthis: & QProgressDialog) -> RetType;
}
// proto: void QProgressDialog::setValue(int progress);
impl<'a> /*trait*/ QProgressDialog_setValue<()> for (i32) {
fn setValue(self , rsthis: & QProgressDialog) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QProgressDialog8setValueEi()};
let arg0 = self as c_int;
unsafe {C_ZN15QProgressDialog8setValueEi(rsthis.qclsinst, arg0)};
// return 1;
}
}
#[derive(Default)] // for QProgressDialog_canceled
pub struct QProgressDialog_canceled_signal{poi:u64}
impl /* struct */ QProgressDialog {
pub fn canceled(&self) -> QProgressDialog_canceled_signal {
return QProgressDialog_canceled_signal{poi:self.qclsinst};
}
}
impl /* struct */ QProgressDialog_canceled_signal {
pub fn connect<T: QProgressDialog_canceled_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QProgressDialog_canceled_signal_connect {
fn connect(self, sigthis: QProgressDialog_canceled_signal);
}
// canceled()
extern fn QProgressDialog_canceled_signal_connect_cb_0(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QProgressDialog_canceled_signal_connect_cb_box_0(rsfptr_raw:*mut Box<Fn()>, ) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
// rsfptr();
unsafe{(*rsfptr_raw)()};
}
impl /* trait */ QProgressDialog_canceled_signal_connect for fn() {
fn connect(self, sigthis: QProgressDialog_canceled_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QProgressDialog_canceled_signal_connect_cb_0 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QProgressDialog_SlotProxy_connect__ZN15QProgressDialog8canceledEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QProgressDialog_canceled_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QProgressDialog_canceled_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QProgressDialog_canceled_signal_connect_cb_box_0 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QProgressDialog_SlotProxy_connect__ZN15QProgressDialog8canceledEv(arg0, arg1, arg2)};
}
}
// <= body block end
|
use poem::{web::Json, IntoResponse, Response};
/// Response for `async_graphql::Request`.
pub struct GraphQLResponse(pub async_graphql::Response);
impl From<async_graphql::Response> for GraphQLResponse {
fn from(resp: async_graphql::Response) -> Self {
Self(resp)
}
}
impl IntoResponse for GraphQLResponse {
fn into_response(self) -> Response {
GraphQLBatchResponse(self.0.into()).into_response()
}
}
/// Response for `async_graphql::BatchRequest`.
pub struct GraphQLBatchResponse(pub async_graphql::BatchResponse);
impl From<async_graphql::BatchResponse> for GraphQLBatchResponse {
fn from(resp: async_graphql::BatchResponse) -> Self {
Self(resp)
}
}
impl IntoResponse for GraphQLBatchResponse {
fn into_response(self) -> Response {
let mut resp = Json(&self.0).into_response();
if self.0.is_ok() {
if let Some(cache_control) = self.0.cache_control().value() {
if let Ok(value) = cache_control.try_into() {
resp.headers_mut().insert("cache-control", value);
}
}
}
resp.headers_mut().extend(self.0.http_headers());
resp
}
}
|
use std::cmp;
use std::f64;
use std::time;
#[derive(Debug, Clone)]
struct LogBuffer<T>
where
T: Clone,
{
head: usize,
size: usize,
samples: usize,
contents: Vec<T>,
}
impl<T> LogBuffer<T>
where
T: Clone + Copy,
{
fn new(size: usize, init_val: T) -> LogBuffer<T> {
LogBuffer {
head: 0,
size,
contents: vec![init_val; size],
samples: 1,
}
}
fn push(&mut self, item: T) {
self.head = (self.head + 1) % self.contents.len();
self.contents[self.head] = item;
self.size = cmp::min(self.size + 1, self.contents.len());
self.samples += 1;
}
fn contents(&self) -> &[T] {
if self.samples > self.size {
&self.contents
} else {
&self.contents[..self.samples]
}
}
fn latest(&self) -> T {
self.contents[self.head]
}
}
#[derive(Debug)]
pub struct TimeContext {
init_instant: time::Instant,
last_instant: time::Instant,
frame_durations: LogBuffer<time::Duration>,
residual_update_dt: time::Duration,
frame_count: usize,
}
const TIME_LOG_FRAMES: usize = 200;
impl TimeContext {
pub fn new() -> TimeContext {
let initial_dt = time::Duration::from_millis(16);
TimeContext {
init_instant: time::Instant::now(),
last_instant: time::Instant::now(),
frame_durations: LogBuffer::new(TIME_LOG_FRAMES, initial_dt),
residual_update_dt: time::Duration::from_secs(0),
frame_count: 0,
}
}
pub fn tick(&mut self) {
let now = time::Instant::now();
let time_since_last = now - self.last_instant;
self.frame_durations.push(time_since_last);
self.last_instant = now;
self.frame_count += 1;
self.residual_update_dt += time_since_last;
}
pub fn delta(&self) -> time::Duration {
self.frame_durations.latest()
}
pub fn last_delta(&self) -> f64 {
duration_to_f64(self.delta())
}
pub fn get_fps(&self) -> f64 {
fps(self)
}
}
pub fn average_delta(tc: &TimeContext) -> time::Duration {
let sum: time::Duration = tc.frame_durations.contents().iter().sum();
if tc.frame_durations.samples > tc.frame_durations.size {
sum / (tc.frame_durations.size as u32)
} else {
sum / (tc.frame_durations.samples as u32)
}
}
pub fn duration_to_f64(d: time::Duration) -> f64 {
let seconds = d.as_secs() as f64;
let nanos = f64::from(d.subsec_nanos());
seconds + (nanos * 1e-9)
}
pub fn fps(tc: &TimeContext) -> f64 {
let duration_per_frame = average_delta(tc);
let seconds_per_frame = duration_to_f64(duration_per_frame);
1.0 / seconds_per_frame
}
|
use crate::prelude::*;
use std::os::raw::c_void;
use std::ptr;
#[repr(C)]
#[derive(Debug)]
pub struct VkPhysicalDevicePushDescriptorPropertiesKHR {
pub sType: VkStructureType,
pub pNext: *const c_void,
pub maxPushDescriptors: u32,
}
impl VkPhysicalDevicePushDescriptorPropertiesKHR {
pub fn new(max_push_descriptors: u32) -> Self {
VkPhysicalDevicePushDescriptorPropertiesKHR {
sType: VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PUSH_DESCRIPTOR_PROPERTIES_KHR,
pNext: ptr::null(),
maxPushDescriptors: max_push_descriptors,
}
}
}
|
mod news_controller;
mod photo_controller;
mod user_controller;
mod video_controller;
use rocket::Route;
pub fn routes() -> Vec<Route> {
let routes_list = vec![
news_controller::news_routes(),
photo_controller::photo_routes(),
video_controller::video_routes(),
user_controller::user_routes(),
];
routes_list.into_iter().flatten().collect()
}
|
use fyrox::{
core::{
algebra::{UnitQuaternion, Vector3},
pool::Handle,
},
engine::{resource_manager::ResourceManager, Engine, EngineInitParams, SerializationContext},
event::{DeviceEvent, ElementState, Event, VirtualKeyCode, WindowEvent},
event_loop::{ControlFlow, EventLoop},
resource::texture::TextureWrapMode,
scene::{
base::BaseBuilder,
camera::{CameraBuilder, SkyBox, SkyBoxBuilder},
collider::{ColliderBuilder, ColliderShape},
node::Node,
rigidbody::RigidBodyBuilder,
transform::TransformBuilder,
Scene,
},
window::WindowBuilder,
};
use std::{sync::Arc, time};
// Our game logic will be updated at 60 Hz rate.
const TIMESTEP: f32 = 1.0 / 60.0;
#[derive(Default)]
struct InputController {
move_forward: bool,
move_backward: bool,
move_left: bool,
move_right: bool,
pitch: f32,
yaw: f32,
}
struct Player {
camera: Handle<Node>,
rigid_body: Handle<Node>,
controller: InputController,
}
async fn create_skybox(resource_manager: ResourceManager) -> SkyBox {
// Load skybox textures in parallel.
let (front, back, left, right, top, bottom) = fyrox::core::futures::join!(
resource_manager.request_texture("data/textures/skybox/front.jpg"),
resource_manager.request_texture("data/textures/skybox/back.jpg"),
resource_manager.request_texture("data/textures/skybox/left.jpg"),
resource_manager.request_texture("data/textures/skybox/right.jpg"),
resource_manager.request_texture("data/textures/skybox/up.jpg"),
resource_manager.request_texture("data/textures/skybox/down.jpg")
);
// Unwrap everything.
let skybox = SkyBoxBuilder {
front: Some(front.unwrap()),
back: Some(back.unwrap()),
left: Some(left.unwrap()),
right: Some(right.unwrap()),
top: Some(top.unwrap()),
bottom: Some(bottom.unwrap()),
}
.build()
.unwrap();
// Set S and T coordinate wrap mode, ClampToEdge will remove any possible seams on edges
// of the skybox.
let skybox_texture = skybox.cubemap().unwrap();
let mut data = skybox_texture.data_ref();
data.set_s_wrap_mode(TextureWrapMode::ClampToEdge);
data.set_t_wrap_mode(TextureWrapMode::ClampToEdge);
skybox
}
impl Player {
async fn new(scene: &mut Scene, resource_manager: ResourceManager) -> Self {
// Create rigid body with a camera, move it a bit up to "emulate" head.
let camera;
let rigid_body_handle = RigidBodyBuilder::new(
BaseBuilder::new()
.with_local_transform(
TransformBuilder::new()
// Offset player a bit.
.with_local_position(Vector3::new(0.0, 1.0, -1.0))
.build(),
)
.with_children(&[
{
camera = CameraBuilder::new(
BaseBuilder::new().with_local_transform(
TransformBuilder::new()
.with_local_position(Vector3::new(0.0, 0.25, 0.0))
.build(),
),
)
.with_skybox(create_skybox(resource_manager).await)
.build(&mut scene.graph);
camera
},
// Add capsule collider for the rigid body.
ColliderBuilder::new(BaseBuilder::new())
.with_shape(ColliderShape::capsule_y(0.25, 0.2))
.build(&mut scene.graph),
]),
)
// We don't want the player to tilt.
.with_locked_rotations(true)
// We don't want the rigid body to sleep (be excluded from simulation)
.with_can_sleep(false)
.build(&mut scene.graph);
Self {
camera,
rigid_body: rigid_body_handle,
controller: Default::default(),
}
}
fn update(&mut self, scene: &mut Scene) {
// Set pitch for the camera. These lines responsible for up-down camera rotation.
scene.graph[self.camera].local_transform_mut().set_rotation(
UnitQuaternion::from_axis_angle(&Vector3::x_axis(), self.controller.pitch.to_radians()),
);
// Borrow rigid body node.
let body = scene.graph[self.rigid_body].as_rigid_body_mut();
// Keep only vertical velocity, and drop horizontal.
let mut velocity = Vector3::new(0.0, body.lin_vel().y, 0.0);
// Change the velocity depending on the keys pressed.
if self.controller.move_forward {
// If we moving forward then add "look" vector of the body.
velocity += body.look_vector();
}
if self.controller.move_backward {
// If we moving backward then subtract "look" vector of the body.
velocity -= body.look_vector();
}
if self.controller.move_left {
// If we moving left then add "side" vector of the body.
velocity += body.side_vector();
}
if self.controller.move_right {
// If we moving right then subtract "side" vector of the body.
velocity -= body.side_vector();
}
// Finally new linear velocity.
body.set_lin_vel(velocity);
// Change the rotation of the rigid body according to current yaw. These lines responsible for
// left-right rotation.
body.local_transform_mut()
.set_rotation(UnitQuaternion::from_axis_angle(
&Vector3::y_axis(),
self.controller.yaw.to_radians(),
));
}
fn process_input_event(&mut self, event: &Event<()>) {
match event {
Event::WindowEvent { event, .. } => {
if let WindowEvent::KeyboardInput { input, .. } = event {
if let Some(key_code) = input.virtual_keycode {
match key_code {
VirtualKeyCode::W => {
self.controller.move_forward = input.state == ElementState::Pressed;
}
VirtualKeyCode::S => {
self.controller.move_backward =
input.state == ElementState::Pressed;
}
VirtualKeyCode::A => {
self.controller.move_left = input.state == ElementState::Pressed;
}
VirtualKeyCode::D => {
self.controller.move_right = input.state == ElementState::Pressed;
}
_ => (),
}
}
}
}
Event::DeviceEvent { event, .. } => {
if let DeviceEvent::MouseMotion { delta } = event {
self.controller.yaw -= delta.0 as f32;
self.controller.pitch =
(self.controller.pitch + delta.1 as f32).clamp(-90.0, 90.0);
}
}
_ => (),
}
}
}
struct Game {
scene: Handle<Scene>,
player: Player,
}
impl Game {
pub async fn new(engine: &mut Engine) -> Self {
let mut scene = Scene::new();
// Load a scene resource and create its instance.
engine
.resource_manager
.request_model("data/models/scene.rgs")
.await
.unwrap()
.instantiate(&mut scene);
Self {
player: Player::new(&mut scene, engine.resource_manager.clone()).await,
scene: engine.scenes.add(scene),
}
}
pub fn update(&mut self, engine: &mut Engine) {
self.player.update(&mut engine.scenes[self.scene]);
}
}
fn main() {
// Configure main window first.
let window_builder = WindowBuilder::new().with_title("3D Shooter Tutorial");
// Create event loop that will be used to "listen" events from the OS.
let event_loop = EventLoop::new();
// Finally create an instance of the engine.
let serialization_context = Arc::new(SerializationContext::new());
let mut engine = Engine::new(EngineInitParams {
window_builder,
resource_manager: ResourceManager::new(serialization_context.clone()),
serialization_context,
events_loop: &event_loop,
vsync: false,
headless: false,
})
.unwrap();
// Initialize game instance.
let mut game = fyrox::core::futures::executor::block_on(Game::new(&mut engine));
// Run the event loop of the main window. which will respond to OS and window events and update
// engine's state accordingly. Engine lets you to decide which event should be handled,
// this is minimal working example if how it should be.
let mut previous = time::Instant::now();
let mut lag = 0.0;
event_loop.run(move |event, _, control_flow| {
game.player.process_input_event(&event);
match event {
Event::MainEventsCleared => {
// This main game loop - it has fixed time step which means that game
// code will run at fixed speed even if renderer can't give you desired
// 60 fps.
let elapsed = previous.elapsed();
previous = time::Instant::now();
lag += elapsed.as_secs_f32();
while lag >= TIMESTEP {
lag -= TIMESTEP;
// Run our game's logic.
game.update(&mut engine);
// Update engine each frame.
engine.update(TIMESTEP, control_flow, &mut lag, Default::default());
}
// Rendering must be explicitly requested and handled after RedrawRequested event is received.
engine.get_window().request_redraw();
}
Event::RedrawRequested(_) => {
// Render at max speed - it is not tied to the game code.
engine.render().unwrap();
}
Event::WindowEvent { event, .. } => match event {
WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit,
WindowEvent::KeyboardInput { input, .. } => {
// Exit game by hitting Escape.
if let Some(VirtualKeyCode::Escape) = input.virtual_keycode {
*control_flow = ControlFlow::Exit
}
}
WindowEvent::Resized(size) => {
// It is very important to handle Resized event from window, because
// renderer knows nothing about window size - it must be notified
// directly when window size has changed.
engine.set_frame_size(size.into()).unwrap();
}
_ => (),
},
_ => *control_flow = ControlFlow::Poll,
}
});
}
|
use minifb::Window;
const SCREEN_WIDTH: u16 = 64;
const SCREEN_HEIGHT: u16 = 32;
pub const SCREEN_SIZE: usize = SCREEN_WIDTH as usize * SCREEN_HEIGHT as usize;
// sprites
pub const BYTES_PER_CHARACTER: u8 = 5;
pub const NUM_FONT_CHARACTERS: u8 = 16;
pub const FONT_ARRAY_SIZE: usize = (BYTES_PER_CHARACTER * NUM_FONT_CHARACTERS) as usize;
pub const FONT_SPRITES: [u8; FONT_ARRAY_SIZE] = [
// 0
0b11110000,
0b10010000,
0b10010000,
0b10010000,
0b11110000,
// 1
0b00100000,
0b01100000,
0b00100000,
0b00100000,
0b01110000,
// 2
0b11110000,
0b00010000,
0b11110000,
0b10000000,
0b11110000,
// 3
0b11110000,
0b00010000,
0b11110000,
0b00010000,
0b11110000,
// 4
0b10100000,
0b10100000,
0b11100000,
0b00100000,
0b00100000,
// 5
0b11110000,
0b10000000,
0b11110000,
0b00010000,
0b11110000,
// 6
0b11110000,
0b10000000,
0b11110000,
0b10010000,
0b11110000,
// 7
0b11110000,
0b00010000,
0b00100000,
0b01000000,
0b01000000,
// 8
0b11110000,
0b10010000,
0b11110000,
0b10010000,
0b11110000,
// 9
0b11110000,
0b10010000,
0b11110000,
0b00010000,
0b11110000,
// A
0b11110000,
0b10010000,
0b11110000,
0b10010000,
0b10010000,
// B
0b11100000,
0b10000000,
0b11100000,
0b10010000,
0b11100000,
// C
0b11110000,
0b10000000,
0b10000000,
0b10000000,
0b11110000,
// D
0b11100000,
0b10010000,
0b10010000,
0b10010000,
0b11100000,
// E
0b11110000,
0b10000000,
0b11110000,
0b10000000,
0b11110000,
// F
0b11110000,
0b10000000,
0b11110000,
0b10000000,
0b10000000];
pub const COLORS: [u32; 14] = [
// white
0xFFFFFF,
// red
0xFF0000,
// orange
0xFF8000,
// yellow
0xFFFF00,
// light green
0x80FF00,
// green
0x00FF00,
// dark green
0x00FF80,
// teal
0x00FFFF,
// blue
0x0080FF,
// dark blue
0x0000FF,
// purple
0x7F00FF,
// pink
0xFF00FF,
// magenta
0xFF007F,
// gray
0x808080
];
pub struct MiniFbDisplay {
color: u32,
redraw: bool,
screen: [u8; SCREEN_SIZE],
times_rendered: u64,
}
impl MiniFbDisplay {
pub fn new(initial_color: u32) -> Self {
MiniFbDisplay {
color: initial_color,
redraw: false,
screen: [0; SCREEN_SIZE],
times_rendered: 0,
}
}
pub fn read(&self, pos: usize) -> u8 {
self.screen[pos]
}
pub fn write(&mut self, pos: usize, value: u8) {
self.screen[pos] = value;
}
pub fn set_redraw(&mut self, redraw: bool) {
self.redraw = redraw;
}
pub fn change_color(&mut self) {
for (i, color) in COLORS.iter().enumerate() {
if self.color == *color {
let index = if i + 1 < COLORS.len() {
i + 1
} else {
0
};
self.color = COLORS[index];
break;
}
}
}
pub fn clear(&mut self) {
for pixel in self.screen.iter_mut() {
if *pixel != 0 {
self.redraw = true;
*pixel = 0;
}
}
}
pub fn render(&mut self, window: &mut Window) {
if !self.redraw {
return;
}
let mut buf: [u32; SCREEN_SIZE] = [0; SCREEN_SIZE];
for (i, pixel) in self.screen.iter_mut().enumerate() {
if *pixel != 0 {
buf[i] = self.color;
}
}
self.redraw = false;
self.times_rendered += 1;
// unwrap, we want to know if this fails
window.update_with_buffer(&buf).unwrap();
}
pub fn get_times_rendered(&self) -> u64 {
self.times_rendered
}
} |
//! An example of an escrow program, inspired by PaulX tutorial seen here
//! https://paulx.dev/blog/2021/01/14/programming-on-solana-an-introduction/
//! This example has some changes to implementation, but more or less should be the same overall
//! Also gives examples on how to use some newer anchor features and CPI
//!
//! User (Initializer) constructs an escrow deal:
//! - SPL token (X) they will offer and amount
//! - SPL token (Y) count they want in return and amount
//! - Program will take ownership of initializer's token X account
//!
//! Once this escrow is initialised, either:
//! 1. User (Taker) can call the exchange function to exchange their Y for X
//! - This will close the escrow account and no longer be usable
//! OR
//! 2. If no one has exchanged, the initializer can close the escrow account
//! - Initializer will get back ownership of their token X account
use anchor_lang::prelude::*;
use anchor_spl::token::{self, CloseAccount, Mint, SetAuthority, TokenAccount, Transfer};
use spl_token::instruction::AuthorityType;
declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");
#[program]
pub mod escrow {
use super::*;
const ESCROW_PDA_SEED: &[u8] = b"escrow";
pub fn initialize_escrow(
ctx: Context<InitializeEscrow>,
_vault_account_bump: u8,
initializer_amount: u64,
taker_amount: u64,
) -> ProgramResult {
ctx.accounts.escrow_account.initializer_key = *ctx.accounts.initializer.key;
ctx.accounts
.escrow_account
.initializer_deposit_token_account = *ctx
.accounts
.initializer_deposit_token_account
.to_account_info()
.key;
ctx.accounts
.escrow_account
.initializer_receive_token_account = *ctx
.accounts
.initializer_receive_token_account
.to_account_info()
.key;
ctx.accounts.escrow_account.initializer_amount = initializer_amount;
ctx.accounts.escrow_account.taker_amount = taker_amount;
let (vault_authority, _vault_authority_bump) =
Pubkey::find_program_address(&[ESCROW_PDA_SEED], ctx.program_id);
token::set_authority(
ctx.accounts.into_set_authority_context(),
AuthorityType::AccountOwner,
Some(vault_authority),
)?;
token::transfer(
ctx.accounts.into_transfer_to_pda_context(),
ctx.accounts.escrow_account.initializer_amount,
)?;
Ok(())
}
pub fn cancel_escrow(ctx: Context<CancelEscrow>) -> ProgramResult {
let (_vault_authority, vault_authority_bump) =
Pubkey::find_program_address(&[ESCROW_PDA_SEED], ctx.program_id);
let authority_seeds = &[&ESCROW_PDA_SEED[..], &[vault_authority_bump]];
token::transfer(
ctx.accounts
.into_transfer_to_initializer_context()
.with_signer(&[&authority_seeds[..]]),
ctx.accounts.escrow_account.initializer_amount,
)?;
token::close_account(
ctx.accounts
.into_close_context()
.with_signer(&[&authority_seeds[..]]),
)?;
Ok(())
}
pub fn exchange(ctx: Context<Exchange>) -> ProgramResult {
// Transferring from initializer to taker
let (_vault_authority, vault_authority_bump) =
Pubkey::find_program_address(&[ESCROW_PDA_SEED], ctx.program_id);
let authority_seeds = &[&ESCROW_PDA_SEED[..], &[vault_authority_bump]];
token::transfer(
ctx.accounts.into_transfer_to_initializer_context(),
ctx.accounts.escrow_account.taker_amount,
)?;
token::transfer(
ctx.accounts
.into_transfer_to_taker_context()
.with_signer(&[&authority_seeds[..]]),
ctx.accounts.escrow_account.initializer_amount,
)?;
token::close_account(
ctx.accounts
.into_close_context()
.with_signer(&[&authority_seeds[..]]),
)?;
Ok(())
}
}
#[derive(Accounts)]
#[instruction(vault_account_bump: u8, initializer_amount: u64)]
pub struct InitializeEscrow<'info> {
#[account(mut, signer)]
pub initializer: AccountInfo<'info>,
pub mint: Account<'info, Mint>,
#[account(
init,
seeds = [b"token-seed".as_ref()],
bump = vault_account_bump,
payer = initializer,
token::mint = mint,
token::authority = initializer,
)]
pub vault_account: Account<'info, TokenAccount>,
#[account(
mut,
constraint = initializer_deposit_token_account.amount >= initializer_amount
)]
pub initializer_deposit_token_account: Account<'info, TokenAccount>,
pub initializer_receive_token_account: Account<'info, TokenAccount>,
#[account(zero)]
pub escrow_account: ProgramAccount<'info, EscrowAccount>,
pub system_program: AccountInfo<'info>,
pub rent: Sysvar<'info, Rent>,
pub token_program: AccountInfo<'info>,
}
#[derive(Accounts)]
pub struct CancelEscrow<'info> {
#[account(mut, signer)]
pub initializer: AccountInfo<'info>,
#[account(mut)]
pub vault_account: Account<'info, TokenAccount>,
pub vault_authority: AccountInfo<'info>,
#[account(mut)]
pub initializer_deposit_token_account: Account<'info, TokenAccount>,
#[account(
mut,
constraint = escrow_account.initializer_key == *initializer.key,
constraint = escrow_account.initializer_deposit_token_account == *initializer_deposit_token_account.to_account_info().key,
close = initializer
)]
pub escrow_account: ProgramAccount<'info, EscrowAccount>,
pub token_program: AccountInfo<'info>,
}
#[derive(Accounts)]
pub struct Exchange<'info> {
#[account(signer)]
pub taker: AccountInfo<'info>,
#[account(mut)]
pub taker_deposit_token_account: Account<'info, TokenAccount>,
#[account(mut)]
pub taker_receive_token_account: Account<'info, TokenAccount>,
#[account(mut)]
pub initializer_deposit_token_account: Account<'info, TokenAccount>,
#[account(mut)]
pub initializer_receive_token_account: Account<'info, TokenAccount>,
#[account(mut)]
pub initializer: AccountInfo<'info>,
#[account(
mut,
constraint = escrow_account.taker_amount <= taker_deposit_token_account.amount,
constraint = escrow_account.initializer_deposit_token_account == *initializer_deposit_token_account.to_account_info().key,
constraint = escrow_account.initializer_receive_token_account == *initializer_receive_token_account.to_account_info().key,
constraint = escrow_account.initializer_key == *initializer.key,
close = initializer
)]
pub escrow_account: ProgramAccount<'info, EscrowAccount>,
#[account(mut)]
pub vault_account: Account<'info, TokenAccount>,
pub vault_authority: AccountInfo<'info>,
pub token_program: AccountInfo<'info>,
}
#[account]
pub struct EscrowAccount {
pub initializer_key: Pubkey,
pub initializer_deposit_token_account: Pubkey,
pub initializer_receive_token_account: Pubkey,
pub initializer_amount: u64,
pub taker_amount: u64,
}
impl<'info> InitializeEscrow<'info> {
fn into_transfer_to_pda_context(&self) -> CpiContext<'_, '_, '_, 'info, Transfer<'info>> {
let cpi_accounts = Transfer {
from: self
.initializer_deposit_token_account
.to_account_info()
.clone(),
to: self.vault_account.to_account_info().clone(),
authority: self.initializer.clone(),
};
CpiContext::new(self.token_program.clone(), cpi_accounts)
}
fn into_set_authority_context(&self) -> CpiContext<'_, '_, '_, 'info, SetAuthority<'info>> {
let cpi_accounts = SetAuthority {
account_or_mint: self.vault_account.to_account_info().clone(),
current_authority: self.initializer.clone(),
};
let cpi_program = self.token_program.to_account_info();
CpiContext::new(cpi_program, cpi_accounts)
}
}
impl<'info> CancelEscrow<'info> {
fn into_transfer_to_initializer_context(
&self,
) -> CpiContext<'_, '_, '_, 'info, Transfer<'info>> {
let cpi_accounts = Transfer {
from: self.vault_account.to_account_info().clone(),
to: self
.initializer_deposit_token_account
.to_account_info()
.clone(),
authority: self.vault_authority.clone(),
};
let cpi_program = self.token_program.to_account_info();
CpiContext::new(cpi_program, cpi_accounts)
}
fn into_close_context(&self) -> CpiContext<'_, '_, '_, 'info, CloseAccount<'info>> {
let cpi_accounts = CloseAccount {
account: self.vault_account.to_account_info().clone(),
destination: self.initializer.clone(),
authority: self.vault_authority.clone(),
};
let cpi_program = self.token_program.to_account_info();
CpiContext::new(cpi_program, cpi_accounts)
}
}
impl<'info> Exchange<'info> {
fn into_transfer_to_initializer_context(
&self,
) -> CpiContext<'_, '_, '_, 'info, Transfer<'info>> {
let cpi_accounts = Transfer {
from: self.taker_deposit_token_account.to_account_info().clone(),
to: self
.initializer_receive_token_account
.to_account_info()
.clone(),
authority: self.taker.clone(),
};
let cpi_program = self.token_program.to_account_info();
CpiContext::new(cpi_program, cpi_accounts)
}
fn into_transfer_to_taker_context(&self) -> CpiContext<'_, '_, '_, 'info, Transfer<'info>> {
let cpi_accounts = Transfer {
from: self.vault_account.to_account_info().clone(),
to: self.taker_receive_token_account.to_account_info().clone(),
authority: self.vault_authority.clone(),
};
CpiContext::new(self.token_program.clone(), cpi_accounts)
}
fn into_close_context(&self) -> CpiContext<'_, '_, '_, 'info, CloseAccount<'info>> {
let cpi_accounts = CloseAccount {
account: self.vault_account.to_account_info().clone(),
destination: self.initializer.clone(),
authority: self.vault_authority.clone(),
};
CpiContext::new(self.token_program.clone(), cpi_accounts)
}
}
|
use std::{time::Duration, thread};
use chrono::{DateTime, Local};
#[derive(Copy, Clone)]
struct Column {
pub rows: [bool; 4],
}
impl Column {
fn new() -> Column {
Column {
rows: [false; 4]
}
}
fn update(&mut self, mut digit: i32) {
for i in 0..4 {
let index: usize = (3-i) as usize;
let binary_number = 2i32.pow(index as u32);
if digit - binary_number >= 0 {
self.rows[index] = true;
digit -= binary_number;
} else {
self.rows[index] = false;
}
}
}
}
pub trait Clock {
fn update(&mut self);
fn draw(&self);
}
struct BinaryClock {
formatted: String,
columns: [Column; 6],
}
impl BinaryClock {
fn new() -> BinaryClock {
BinaryClock {
formatted: Local::now().format("%H%M%S").to_string(),
columns: [Column::new(); 6],
}
}
}
impl Clock for BinaryClock {
fn update(&mut self) {
self.formatted = Local::now().format("%H%M%S").to_string();
for (index, _) in self.formatted.chars().enumerate() {
let digit = &self.formatted[index..(index+1)];
self.columns[index].update(digit.parse().unwrap());
self.columns[index].rows.reverse();
}
}
fn draw(&self) {
println!(" HH MM SS");
for row in 0..4 {
let mut row_display: String = String::new();
let binary_number = 2i32.pow(3-row);
let binary_number_string = format!("{:02}: ", binary_number.to_string());
row_display.push_str(&binary_number_string[..]);
for col in 0..6 {
if self.columns[col].rows[row as usize] {
row_display.push_str("x");
} else {
row_display.push_str(".");
}
if (col+1) % 2 == 0 {
row_display.push_str(" ");
}
}
println!("{:}", row_display);
row_display = String::new();
}
}
}
fn main() {
let mut clock = BinaryClock::new();
loop {
// Clear screen.
println!("\x1b[2J");
clock.update();
clock.draw();
thread::sleep(Duration::from_millis(1000))
}
}
|
/*BEGIN*/fn main() {
// ^^^^^^^^^WARN(no-trans) function is never used
// ^^^^^^^^^NOTE(no-trans) #[warn(dead_code)]
// 1.24 nightly has changed how these no-trans messages are displayed (instead
// of encompassing the entire function).
}/*END*/
// ~NOTE(check) here is a function named 'main'
|
use crate::postgres::stream::PgStream;
use crate::url::Url;
#[cfg_attr(not(feature = "tls"), allow(unused_variables))]
pub(crate) async fn request_if_needed(stream: &mut PgStream, url: &Url) -> crate::Result<()> {
// https://www.postgresql.org/docs/12/libpq-ssl.html#LIBPQ-SSL-SSLMODE-STATEMENTS
match url.param("sslmode").as_deref() {
Some("disable") | Some("allow") => {
// Do nothing
}
#[cfg(feature = "tls")]
Some("prefer") | None => {
// We default to [prefer] if TLS is compiled in
if !try_upgrade(stream, url, true, true).await? {
// TLS upgrade failed; fall back to a normal connection
}
}
#[cfg(not(feature = "tls"))]
None => {
// The user neither explicitly enabled TLS in the connection string
// nor did they turn the `tls` feature on
// Do nothing
}
#[cfg(feature = "tls")]
Some(mode @ "require") | Some(mode @ "verify-ca") | Some(mode @ "verify-full") => {
if !try_upgrade(
stream,
url,
// false for both verify-ca and verify-full
mode == "require",
// false for only verify-full
mode != "verify-full",
)
.await?
{
return Err(tls_err!("server does not support TLS").into());
}
}
#[cfg(not(feature = "tls"))]
Some(mode @ "prefer")
| Some(mode @ "require")
| Some(mode @ "verify-ca")
| Some(mode @ "verify-full") => {
return Err(tls_err!(
"sslmode {:?} unsupported; rbatis_core was compiled without `tls` feature",
mode
)
.into());
}
Some(mode) => {
return Err(tls_err!("unknown `sslmode` value: {:?}", mode).into());
}
}
Ok(())
}
#[cfg(feature = "tls")]
async fn try_upgrade(
stream: &mut PgStream,
url: &Url,
accept_invalid_certs: bool,
accept_invalid_host_names: bool,
) -> crate::Result<bool> {
use async_native_tls::TlsConnector;
stream.write(crate::postgres::protocol::SslRequest);
stream.flush().await?;
// The server then responds with a single byte containing S or N,
// indicating that it is willing or unwilling to perform SSL, respectively.
let ind = stream.stream.peek(1).await?[0];
stream.stream.consume(1);
match ind {
b'S' => {
// The server is ready and willing to accept an SSL connection
}
b'N' => {
// The server is _unwilling_ to perform SSL
return Ok(false);
}
other => {
return Err(tls_err!("unexpected response from SSLRequest: 0x{:02X}", other).into());
}
}
let mut connector = TlsConnector::new()
.danger_accept_invalid_certs(accept_invalid_certs)
.danger_accept_invalid_hostnames(accept_invalid_host_names);
if !accept_invalid_certs {
// Try to read in the root certificate for postgres using several
// standard methods (used by psql and libpq)
if let Some(cert) = read_root_certificate(&url).await? {
connector = connector.add_root_certificate(cert);
}
}
stream.stream.upgrade(url, connector).await?;
Ok(true)
}
#[cfg(feature = "tls")]
async fn read_root_certificate(url: &Url) -> crate::Result<Option<async_native_tls::Certificate>> {
use crate::runtime::fs;
use std::env;
let mut data = None;
if let Some(path) = url
.param("sslrootcert")
.or_else(|| env::var("PGSSLROOTCERT").ok().map(Into::into))
{
data = Some(fs::read(&*path).await?);
} else if cfg!(windows) {
if let Ok(app_data) = env::var("APPDATA") {
let path = format!("{}\\postgresql\\root.crt", app_data);
data = fs::read(path).await.ok();
}
} else {
if let Ok(home) = env::var("HOME") {
let path = format!("{}/.postgresql/root.crt", home);
data = fs::read(path).await.ok();
}
}
data.map(|data| async_native_tls::Certificate::from_pem(&data))
.transpose()
.map_err(Into::into)
}
|
use {
flate2::{write::GzEncoder, Compression},
futures::{
compat::Future01CompatExt,
future::{FutureExt, TryFutureExt},
},
futures_util::{compat::Stream01CompatExt, TryStreamExt},
hyper::{
header::{HeaderMap, HeaderValue},
service::service_fn,
Body, Method, Request, Response, Server, StatusCode,
},
std::{collections::HashSet, io::Write, net::SocketAddr},
};
use crate::configuration::CONFIG;
use crate::error::{Error, ErrorKind, Result};
use crate::{handlers, Auth};
use crate::{router, User};
lazy_static::lazy_static! {
pub static ref LOG: slog::Logger = { crate::LOG.new(slog::o!("mod" => "service")) };
}
async fn is_valid_auth(auth_token: String) -> Result<Auth> {
slog::debug!(LOG, "checking auth");
let conn = redis::Client::open(CONFIG.redis_url.as_ref())?
.get_async_connection()
.compat()
.await?;
let (_, opt): (_, Option<User>) = redis::cmd("HGET")
.arg("mpix.users")
.arg(&auth_token)
.query_async(conn)
.compat()
.await
.unwrap();
slog::debug!(LOG, "authorized user";
"user" => format!("{:?}", opt));
if let Some(_) = opt {
Ok(Auth {
user_token: auth_token,
})
} else {
Err(ErrorKind::InvalidAuth("missing auth token".into()))?
}
}
/// Require an auth bearer token on requests
async fn ensure_auth(
req: Request<Body>,
) -> Result<(Request<Body>, Option<Auth>, Option<Response<Body>>)> {
lazy_static::lazy_static! {
static ref ALLOWED: HashSet<&'static str> = maplit::hashset!{"", "/status"};
};
let path = req.uri().path().trim_end_matches("/");
if ALLOWED.contains(path) || path.starts_with("/p/") {
return Ok((req, None, None));
}
let maybe_auth = req
.headers()
.get("x-mpix-auth")
.ok_or_else(|| Error::from("missing auth header"))
.and_then(|hv| Ok(hv.to_str()?.to_string()))
.ok();
if let Some(auth_token) = maybe_auth {
if let Some(auth) = is_valid_auth(auth_token).await.ok() {
return Ok((req, Some(auth), None));
}
}
let resp = Response::builder()
.status(StatusCode::UNAUTHORIZED)
.body(Body::from("unauthorized"))?;
Ok((req, None, Some(resp)))
}
/// gzip response content if the request accepts gzip
async fn gzip_response(headers: HeaderMap, mut resp: Response<Body>) -> Result<Response<Body>> {
if let Some(accept) = headers.get("accept-encoding") {
if accept.to_str()?.contains("gzip") {
resp.headers_mut()
.insert("content-encoding", HeaderValue::from_str("gzip")?);
// split so we can modify the body
let (parts, bod) = resp.into_parts();
let mut e = GzEncoder::new(Vec::new(), Compression::default());
// `bod` is a futures01 stream that needs to be made std::future compatible
let bytes = bod.compat().try_concat().await?;
let bytes_size = bytes.len();
e.write_all(bytes.as_ref())
.map_err(|e| format!("error writing bytes to gzip encoder {:?}", e))?;
let res = e
.finish()
.map_err(|e| format!("error finishing gzip {:?}", e))?;
let res_size = res.len();
let new_bod = Body::from(res);
let resp = Response::from_parts(parts, new_bod);
slog::debug!(
LOG, "gzipped";
"original_size" => bytes_size, "gzipped_size" => res_size
);
return Ok(resp);
}
}
Ok(resp)
}
async fn route(
req: Request<Body>,
auth: Option<Auth>,
method: Method,
uri: String,
) -> Result<Response<Body>> {
router!(
req, auth, method, uri.trim_end_matches("/"),
[Method::GET, r"^/p/(?P<token>[a-zA-Z0-9-_]+)$", {"token"}] -> handlers::track,
[Method::GET, r"^/status$", {}] -> handlers::status,
[Method::GET, r"^$", {}] -> handlers::index,
[Method::POST, r"^/create$", {}] -> handlers::create,
[Method::GET, r"^/stat$", {}] -> handlers::tracking_stats,
[Method::GET, r"^/stat/(?P<token>[a-zA-Z0-9-_]+)$", {"token"}] -> handlers::tracking_stats,
_ -> handlers::not_found,
);
}
/// Pipe an incoming request through pre-processing, routing, and post-processing hooks
async fn process(req: Request<Body>) -> Result<Response<Body>> {
let headers = req.headers().clone();
// before
let (req, auth, resp) = ensure_auth(req).await?;
if let Some(resp) = resp {
return Ok(resp);
}
// route
let method = req.method().clone();
let uri = req.uri().path().to_string();
let resp = route(req, auth, method, uri).await?;
// after
let resp = gzip_response(headers, resp).await?;
Ok(resp)
}
async fn serve(req: Request<Body>) -> Result<Response<Body>> {
// capture incoming info for logs
let now = chrono::Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
let start = std::time::Instant::now();
let method = req.method().clone();
let uri = req.uri().clone();
let response = match process(req).await {
Ok(resp) => resp,
Err(err) => {
slog::error!(LOG, "handler error";
"error" => format!("{}", err));
Response::builder()
.status(500)
.body("server error".into())?
}
};
let status = response.status();
let elap = start.elapsed();
let elap_ms = (elap.as_secs_f32() * 1_000.) + (elap.subsec_nanos() as f32 / 1_000_000.);
slog::info!(LOG, "request";
"method" => method.as_str(),
"status" => status.as_u16(),
"uri" => uri.path(),
"timestamp" => now,
"elapsed_ms" => elap_ms);
Ok(response)
}
/// Build a server future that can be passed to a runtime
pub async fn run(addr: SocketAddr) {
slog::info!(LOG, "Listening"; "host" => format!("http://{}", addr));
let server_future = Server::bind(&addr).serve(|| {
service_fn(|req| {
// `serve` returns a `std::future` so we need to box and
// wrap it to make it futures01 compatible before handing
// it over to hyper
serve(req).boxed().compat()
})
});
// and now `server_future` is a futures01 future that we need to
// make `std::futures` compatible so we can `.await` it
if let Err(e) = server_future.compat().await {
slog::error!(LOG, "server error"; "error" => format!("{}", e));
}
}
|
//! CLI math tool
extern crate arithmancy;
extern crate getopts;
use std::process;
use std::env::args;
// Show short CLI spec
fn usage(brief : &str, opts : &getopts::Options) {
println!("{}", (*opts).usage(brief));
}
// CLI entry point
fn main() {
let arguments : Vec<String> = args()
.collect();
let program : &str = arguments[0]
.as_ref();
let brief = format!("Usage: {} [options]", program);
let mut opts : getopts::Options = getopts::Options::new();
opts.optopt("n", "integer", "increment an integer by two (required)", "VAL");
opts.optflag("h", "help", "print usage info");
match opts.parse(&arguments[1..]) {
Err(_) => {
usage(&brief, &opts);
process::abort();
},
Ok(optmatches) => {
if optmatches.opt_present("h") {
usage(&brief, &opts);
process::exit(0);
} else if optmatches.opt_present("n") {
let n : i64 = optmatches
.opt_str("n")
.unwrap()
.parse()
.expect("Error parsing integer");
println!("{}", arithmancy::add_two(n));
} else {
usage(&brief, &opts);
process::abort();
}
}
}
}
|
/*!
An application that load different interfaces using the partial feature.
Partials can be used to split large GUI application into smaller bits.
Requires the following features: `cargo run --example partials_d --features "listbox frame combobox flexbox"`
*/
extern crate native_windows_gui as nwg;
extern crate native_windows_derive as nwd;
use nwd::{NwgUi, NwgPartial};
use nwg::NativeUi;
#[derive(Default, NwgUi)]
pub struct PartialDemo {
#[nwg_control(size: (500, 400), position: (300, 300), title: "Many UI")]
#[nwg_events( OnWindowClose: [PartialDemo::exit] )]
window: nwg::Window,
#[nwg_layout(parent: window)]
layout: nwg::FlexboxLayout,
#[nwg_control(collection: vec!["People", "Animals", "Food"])]
#[nwg_layout_item(layout: layout)]
#[nwg_events( OnListBoxSelect: [PartialDemo::change_interface] )]
menu: nwg::ListBox<&'static str>,
#[nwg_control]
#[nwg_layout_item(layout: layout)]
frame1: nwg::Frame,
#[nwg_control(flags: "BORDER")]
frame2: nwg::Frame,
#[nwg_control(flags: "BORDER")]
frame3: nwg::Frame,
#[nwg_partial(parent: frame1)]
#[nwg_events( (save_btn, OnButtonClick): [PartialDemo::save] )]
people_ui: PeopleUi,
#[nwg_partial(parent: frame2)]
#[nwg_events( (save_btn, OnButtonClick): [PartialDemo::save] )]
animal_ui: AnimalUi,
#[nwg_partial(parent: frame3)]
#[nwg_events( (save_btn, OnButtonClick): [PartialDemo::save] )]
food_ui: FoodUi,
}
impl PartialDemo {
fn change_interface(&self) {
self.frame1.set_visible(false);
self.frame2.set_visible(false);
self.frame3.set_visible(false);
let layout = &self.layout;
if layout.has_child(&self.frame1) { layout.remove_child(&self.frame1); }
if layout.has_child(&self.frame2) { layout.remove_child(&self.frame2); }
if layout.has_child(&self.frame3) { layout.remove_child(&self.frame3); }
use nwg::stretch::{geometry::Size, style::{Style, Dimension as D}};
let mut style = Style::default();
style.size = Size { width: D::Percent(1.0), height: D::Auto };
match self.menu.selection() {
None | Some(0) => {
layout.add_child(&self.frame1, style).unwrap();
self.frame1.set_visible(true);
},
Some(1) => {
layout.add_child(&self.frame2, style).unwrap();
self.frame2.set_visible(true);
},
Some(2) => {
layout.add_child(&self.frame3, style).unwrap();
self.frame3.set_visible(true);
},
Some(_) => unreachable!()
}
}
fn save(&self) {
nwg::simple_message("Saved!", "Data saved!");
}
fn exit(&self) {
nwg::stop_thread_dispatch();
}
}
#[derive(Default, NwgPartial)]
pub struct PeopleUi {
#[nwg_layout(max_size: [1000, 150], min_size: [100, 120])]
layout: nwg::GridLayout,
#[nwg_layout(min_size: [100, 200], max_column: Some(2), max_row: Some(6))]
layout2: nwg::GridLayout,
#[nwg_control(text: "Name:", h_align: HTextAlign::Right)]
#[nwg_layout_item(layout: layout, col: 0, row: 0)]
label1: nwg::Label,
#[nwg_control(text: "Age:", h_align: HTextAlign::Right)]
#[nwg_layout_item(layout: layout, col: 0, row: 1)]
label2: nwg::Label,
#[nwg_control(text: "Job:", h_align: HTextAlign::Right)]
#[nwg_layout_item(layout: layout, col: 0, row: 2)]
label3: nwg::Label,
#[nwg_control(text: "John Doe")]
#[nwg_layout_item(layout: layout, col: 1, row: 0)]
#[nwg_events(OnChar: [print_char(EVT_DATA)])]
name_input: nwg::TextInput,
#[nwg_control(text: "75", flags: "NUMBER|VISIBLE")]
#[nwg_layout_item(layout: layout, col: 1, row: 1)]
age_input: nwg::TextInput,
#[nwg_control(text: "Programmer")]
#[nwg_layout_item(layout: layout, col: 1, row: 2)]
job_input: nwg::TextInput,
#[nwg_control(text: "Save")]
#[nwg_layout_item(layout: layout2, col: 1, row: 5)]
save_btn: nwg::Button,
}
#[derive(Default, NwgPartial)]
pub struct AnimalUi {
#[nwg_layout(max_size: [1000, 150], min_size: [100, 120])]
layout: nwg::GridLayout,
#[nwg_layout(min_size: [100, 200], max_column: Some(2), max_row: Some(6))]
layout2: nwg::GridLayout,
#[nwg_control(text: "Name:", h_align: HTextAlign::Right)]
#[nwg_layout_item(layout: layout, col: 0, row: 0)]
label1: nwg::Label,
#[nwg_control(text: "Race:", h_align: HTextAlign::Right)]
#[nwg_layout_item(layout: layout, col: 0, row: 1)]
label2: nwg::Label,
#[nwg_control(text: "Is fluffy:", h_align: HTextAlign::Right)]
#[nwg_layout_item(layout: layout, col: 0, row: 2)]
label3: nwg::Label,
#[nwg_control(text: "Mittens")]
#[nwg_layout_item(layout: layout, col: 1, row: 0)]
#[nwg_events(OnChar: [print_char(EVT_DATA)])]
name_input: nwg::TextInput,
#[nwg_control(collection: vec!["Cat", "Dog", "Pidgeon", "Monkey"], selected_index: Some(0))]
#[nwg_layout_item(layout: layout, col: 1, row: 1)]
race_input: nwg::ComboBox<&'static str>,
#[nwg_control(text: "", check_state: CheckBoxState::Checked)]
#[nwg_layout_item(layout: layout, col: 1, row: 2)]
is_soft_input: nwg::CheckBox,
#[nwg_control(text: "Save")]
#[nwg_layout_item(layout: layout2, col: 1, row: 5)]
save_btn: nwg::Button,
}
#[derive(Default, NwgPartial)]
pub struct FoodUi {
#[nwg_layout(max_size: [1000, 90], min_size: [100, 80])]
layout: nwg::GridLayout,
#[nwg_layout(min_size: [100, 200], max_column: Some(2), max_row: Some(6))]
layout2: nwg::GridLayout,
#[nwg_control(text: "Name:", h_align: HTextAlign::Right)]
#[nwg_layout_item(layout: layout, col: 0, row: 0)]
label1: nwg::Label,
#[nwg_control(text: "Tasty:", h_align: HTextAlign::Right)]
#[nwg_layout_item(layout: layout, col: 0, row: 1)]
label2: nwg::Label,
#[nwg_control(text: "Banana")]
#[nwg_layout_item(layout: layout, col: 1, row: 0)]
#[nwg_events(OnChar: [print_char(EVT_DATA)])]
name_input: nwg::TextInput,
#[nwg_control(text: "", check_state: CheckBoxState::Checked)]
#[nwg_layout_item(layout: layout, col: 1, row: 1)]
tasty_input: nwg::CheckBox,
#[nwg_control(text: "Save")]
#[nwg_layout_item(layout: layout2, col: 1, row: 5)]
save_btn: nwg::Button,
}
fn print_char(data: &nwg::EventData) {
println!("{:?}", data.on_char());
}
fn main() {
nwg::init().expect("Failed to init Native Windows GUI");
nwg::Font::set_global_family("Segoe UI").expect("Failed to set default font");
let _ui = PartialDemo::build_ui(Default::default()).expect("Failed to build UI");
nwg::dispatch_thread_events();
}
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[cfg(feature = "ApplicationModel_Calls_Background")]
pub mod Background;
#[cfg(feature = "ApplicationModel_Calls_Provider")]
pub mod Provider;
#[link(name = "windows")]
extern "system" {}
pub type CallAnswerEventArgs = *mut ::core::ffi::c_void;
pub type CallRejectEventArgs = *mut ::core::ffi::c_void;
pub type CallStateChangeEventArgs = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct CellularDtmfMode(pub i32);
impl CellularDtmfMode {
pub const Continuous: Self = Self(0i32);
pub const Burst: Self = Self(1i32);
}
impl ::core::marker::Copy for CellularDtmfMode {}
impl ::core::clone::Clone for CellularDtmfMode {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct DtmfKey(pub i32);
impl DtmfKey {
pub const D0: Self = Self(0i32);
pub const D1: Self = Self(1i32);
pub const D2: Self = Self(2i32);
pub const D3: Self = Self(3i32);
pub const D4: Self = Self(4i32);
pub const D5: Self = Self(5i32);
pub const D6: Self = Self(6i32);
pub const D7: Self = Self(7i32);
pub const D8: Self = Self(8i32);
pub const D9: Self = Self(9i32);
pub const Star: Self = Self(10i32);
pub const Pound: Self = Self(11i32);
}
impl ::core::marker::Copy for DtmfKey {}
impl ::core::clone::Clone for DtmfKey {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct DtmfToneAudioPlayback(pub i32);
impl DtmfToneAudioPlayback {
pub const Play: Self = Self(0i32);
pub const DoNotPlay: Self = Self(1i32);
}
impl ::core::marker::Copy for DtmfToneAudioPlayback {}
impl ::core::clone::Clone for DtmfToneAudioPlayback {
fn clone(&self) -> Self {
*self
}
}
pub type LockScreenCallEndCallDeferral = *mut ::core::ffi::c_void;
pub type LockScreenCallEndRequestedEventArgs = *mut ::core::ffi::c_void;
pub type LockScreenCallUI = *mut ::core::ffi::c_void;
pub type MuteChangeEventArgs = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct PhoneAudioRoutingEndpoint(pub i32);
impl PhoneAudioRoutingEndpoint {
pub const Default: Self = Self(0i32);
pub const Bluetooth: Self = Self(1i32);
pub const Speakerphone: Self = Self(2i32);
}
impl ::core::marker::Copy for PhoneAudioRoutingEndpoint {}
impl ::core::clone::Clone for PhoneAudioRoutingEndpoint {
fn clone(&self) -> Self {
*self
}
}
pub type PhoneCall = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct PhoneCallAudioDevice(pub i32);
impl PhoneCallAudioDevice {
pub const Unknown: Self = Self(0i32);
pub const LocalDevice: Self = Self(1i32);
pub const RemoteDevice: Self = Self(2i32);
}
impl ::core::marker::Copy for PhoneCallAudioDevice {}
impl ::core::clone::Clone for PhoneCallAudioDevice {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct PhoneCallDirection(pub i32);
impl PhoneCallDirection {
pub const Unknown: Self = Self(0i32);
pub const Incoming: Self = Self(1i32);
pub const Outgoing: Self = Self(2i32);
}
impl ::core::marker::Copy for PhoneCallDirection {}
impl ::core::clone::Clone for PhoneCallDirection {
fn clone(&self) -> Self {
*self
}
}
pub type PhoneCallHistoryEntry = *mut ::core::ffi::c_void;
pub type PhoneCallHistoryEntryAddress = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct PhoneCallHistoryEntryMedia(pub i32);
impl PhoneCallHistoryEntryMedia {
pub const Audio: Self = Self(0i32);
pub const Video: Self = Self(1i32);
}
impl ::core::marker::Copy for PhoneCallHistoryEntryMedia {}
impl ::core::clone::Clone for PhoneCallHistoryEntryMedia {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct PhoneCallHistoryEntryOtherAppReadAccess(pub i32);
impl PhoneCallHistoryEntryOtherAppReadAccess {
pub const Full: Self = Self(0i32);
pub const SystemOnly: Self = Self(1i32);
}
impl ::core::marker::Copy for PhoneCallHistoryEntryOtherAppReadAccess {}
impl ::core::clone::Clone for PhoneCallHistoryEntryOtherAppReadAccess {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct PhoneCallHistoryEntryQueryDesiredMedia(pub u32);
impl PhoneCallHistoryEntryQueryDesiredMedia {
pub const None: Self = Self(0u32);
pub const Audio: Self = Self(1u32);
pub const Video: Self = Self(2u32);
pub const All: Self = Self(4294967295u32);
}
impl ::core::marker::Copy for PhoneCallHistoryEntryQueryDesiredMedia {}
impl ::core::clone::Clone for PhoneCallHistoryEntryQueryDesiredMedia {
fn clone(&self) -> Self {
*self
}
}
pub type PhoneCallHistoryEntryQueryOptions = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct PhoneCallHistoryEntryRawAddressKind(pub i32);
impl PhoneCallHistoryEntryRawAddressKind {
pub const PhoneNumber: Self = Self(0i32);
pub const Custom: Self = Self(1i32);
}
impl ::core::marker::Copy for PhoneCallHistoryEntryRawAddressKind {}
impl ::core::clone::Clone for PhoneCallHistoryEntryRawAddressKind {
fn clone(&self) -> Self {
*self
}
}
pub type PhoneCallHistoryEntryReader = *mut ::core::ffi::c_void;
pub type PhoneCallHistoryManagerForUser = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct PhoneCallHistorySourceIdKind(pub i32);
impl PhoneCallHistorySourceIdKind {
pub const CellularPhoneLineId: Self = Self(0i32);
pub const PackageFamilyName: Self = Self(1i32);
}
impl ::core::marker::Copy for PhoneCallHistorySourceIdKind {}
impl ::core::clone::Clone for PhoneCallHistorySourceIdKind {
fn clone(&self) -> Self {
*self
}
}
pub type PhoneCallHistoryStore = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct PhoneCallHistoryStoreAccessType(pub i32);
impl PhoneCallHistoryStoreAccessType {
pub const AppEntriesReadWrite: Self = Self(0i32);
pub const AllEntriesLimitedReadWrite: Self = Self(1i32);
pub const AllEntriesReadWrite: Self = Self(2i32);
}
impl ::core::marker::Copy for PhoneCallHistoryStoreAccessType {}
impl ::core::clone::Clone for PhoneCallHistoryStoreAccessType {
fn clone(&self) -> Self {
*self
}
}
pub type PhoneCallInfo = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct PhoneCallMedia(pub i32);
impl PhoneCallMedia {
pub const Audio: Self = Self(0i32);
pub const AudioAndVideo: Self = Self(1i32);
pub const AudioAndRealTimeText: Self = Self(2i32);
}
impl ::core::marker::Copy for PhoneCallMedia {}
impl ::core::clone::Clone for PhoneCallMedia {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct PhoneCallOperationStatus(pub i32);
impl PhoneCallOperationStatus {
pub const Succeeded: Self = Self(0i32);
pub const OtherFailure: Self = Self(1i32);
pub const TimedOut: Self = Self(2i32);
pub const ConnectionLost: Self = Self(3i32);
pub const InvalidCallState: Self = Self(4i32);
}
impl ::core::marker::Copy for PhoneCallOperationStatus {}
impl ::core::clone::Clone for PhoneCallOperationStatus {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct PhoneCallStatus(pub i32);
impl PhoneCallStatus {
pub const Lost: Self = Self(0i32);
pub const Incoming: Self = Self(1i32);
pub const Dialing: Self = Self(2i32);
pub const Talking: Self = Self(3i32);
pub const Held: Self = Self(4i32);
pub const Ended: Self = Self(5i32);
}
impl ::core::marker::Copy for PhoneCallStatus {}
impl ::core::clone::Clone for PhoneCallStatus {
fn clone(&self) -> Self {
*self
}
}
pub type PhoneCallStore = *mut ::core::ffi::c_void;
pub type PhoneCallVideoCapabilities = *mut ::core::ffi::c_void;
pub type PhoneCallsResult = *mut ::core::ffi::c_void;
pub type PhoneDialOptions = *mut ::core::ffi::c_void;
pub type PhoneLine = *mut ::core::ffi::c_void;
pub type PhoneLineCellularDetails = *mut ::core::ffi::c_void;
pub type PhoneLineConfiguration = *mut ::core::ffi::c_void;
pub type PhoneLineDialResult = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct PhoneLineNetworkOperatorDisplayTextLocation(pub i32);
impl PhoneLineNetworkOperatorDisplayTextLocation {
pub const Default: Self = Self(0i32);
pub const Tile: Self = Self(1i32);
pub const Dialer: Self = Self(2i32);
pub const InCallUI: Self = Self(3i32);
}
impl ::core::marker::Copy for PhoneLineNetworkOperatorDisplayTextLocation {}
impl ::core::clone::Clone for PhoneLineNetworkOperatorDisplayTextLocation {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct PhoneLineOperationStatus(pub i32);
impl PhoneLineOperationStatus {
pub const Succeeded: Self = Self(0i32);
pub const OtherFailure: Self = Self(1i32);
pub const TimedOut: Self = Self(2i32);
pub const ConnectionLost: Self = Self(3i32);
pub const InvalidCallState: Self = Self(4i32);
}
impl ::core::marker::Copy for PhoneLineOperationStatus {}
impl ::core::clone::Clone for PhoneLineOperationStatus {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct PhoneLineTransport(pub i32);
impl PhoneLineTransport {
pub const Cellular: Self = Self(0i32);
pub const VoipApp: Self = Self(1i32);
pub const Bluetooth: Self = Self(2i32);
}
impl ::core::marker::Copy for PhoneLineTransport {}
impl ::core::clone::Clone for PhoneLineTransport {
fn clone(&self) -> Self {
*self
}
}
pub type PhoneLineTransportDevice = *mut ::core::ffi::c_void;
pub type PhoneLineWatcher = *mut ::core::ffi::c_void;
pub type PhoneLineWatcherEventArgs = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct PhoneLineWatcherStatus(pub i32);
impl PhoneLineWatcherStatus {
pub const Created: Self = Self(0i32);
pub const Started: Self = Self(1i32);
pub const EnumerationCompleted: Self = Self(2i32);
pub const Stopped: Self = Self(3i32);
}
impl ::core::marker::Copy for PhoneLineWatcherStatus {}
impl ::core::clone::Clone for PhoneLineWatcherStatus {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct PhoneNetworkState(pub i32);
impl PhoneNetworkState {
pub const Unknown: Self = Self(0i32);
pub const NoSignal: Self = Self(1i32);
pub const Deregistered: Self = Self(2i32);
pub const Denied: Self = Self(3i32);
pub const Searching: Self = Self(4i32);
pub const Home: Self = Self(5i32);
pub const RoamingInternational: Self = Self(6i32);
pub const RoamingDomestic: Self = Self(7i32);
}
impl ::core::marker::Copy for PhoneNetworkState {}
impl ::core::clone::Clone for PhoneNetworkState {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct PhoneSimState(pub i32);
impl PhoneSimState {
pub const Unknown: Self = Self(0i32);
pub const PinNotRequired: Self = Self(1i32);
pub const PinUnlocked: Self = Self(2i32);
pub const PinLocked: Self = Self(3i32);
pub const PukLocked: Self = Self(4i32);
pub const NotInserted: Self = Self(5i32);
pub const Invalid: Self = Self(6i32);
pub const Disabled: Self = Self(7i32);
}
impl ::core::marker::Copy for PhoneSimState {}
impl ::core::clone::Clone for PhoneSimState {
fn clone(&self) -> Self {
*self
}
}
pub type PhoneVoicemail = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct PhoneVoicemailType(pub i32);
impl PhoneVoicemailType {
pub const None: Self = Self(0i32);
pub const Traditional: Self = Self(1i32);
pub const Visual: Self = Self(2i32);
}
impl ::core::marker::Copy for PhoneVoicemailType {}
impl ::core::clone::Clone for PhoneVoicemailType {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct TransportDeviceAudioRoutingStatus(pub i32);
impl TransportDeviceAudioRoutingStatus {
pub const Unknown: Self = Self(0i32);
pub const CanRouteToLocalDevice: Self = Self(1i32);
pub const CannotRouteToLocalDevice: Self = Self(2i32);
}
impl ::core::marker::Copy for TransportDeviceAudioRoutingStatus {}
impl ::core::clone::Clone for TransportDeviceAudioRoutingStatus {
fn clone(&self) -> Self {
*self
}
}
pub type VoipCallCoordinator = *mut ::core::ffi::c_void;
pub type VoipPhoneCall = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct VoipPhoneCallMedia(pub u32);
impl VoipPhoneCallMedia {
pub const None: Self = Self(0u32);
pub const Audio: Self = Self(1u32);
pub const Video: Self = Self(2u32);
}
impl ::core::marker::Copy for VoipPhoneCallMedia {}
impl ::core::clone::Clone for VoipPhoneCallMedia {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct VoipPhoneCallRejectReason(pub i32);
impl VoipPhoneCallRejectReason {
pub const UserIgnored: Self = Self(0i32);
pub const TimedOut: Self = Self(1i32);
pub const OtherIncomingCall: Self = Self(2i32);
pub const EmergencyCallExists: Self = Self(3i32);
pub const InvalidCallState: Self = Self(4i32);
}
impl ::core::marker::Copy for VoipPhoneCallRejectReason {}
impl ::core::clone::Clone for VoipPhoneCallRejectReason {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct VoipPhoneCallResourceReservationStatus(pub i32);
impl VoipPhoneCallResourceReservationStatus {
pub const Success: Self = Self(0i32);
pub const ResourcesNotAvailable: Self = Self(1i32);
}
impl ::core::marker::Copy for VoipPhoneCallResourceReservationStatus {}
impl ::core::clone::Clone for VoipPhoneCallResourceReservationStatus {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct VoipPhoneCallState(pub i32);
impl VoipPhoneCallState {
pub const Ended: Self = Self(0i32);
pub const Held: Self = Self(1i32);
pub const Active: Self = Self(2i32);
pub const Incoming: Self = Self(3i32);
pub const Outgoing: Self = Self(4i32);
}
impl ::core::marker::Copy for VoipPhoneCallState {}
impl ::core::clone::Clone for VoipPhoneCallState {
fn clone(&self) -> Self {
*self
}
}
|
#![allow(clippy::comparison_chain)]
#![allow(clippy::collapsible_if)]
use std::cmp::Reverse;
use std::cmp::{max, min};
use std::collections::{BTreeSet, HashMap, HashSet};
use std::fmt::Debug;
use itertools::{sorted, Itertools};
use whiteread::parse_line;
const ten97: usize = 1000_000_007;
/// 2の逆元 mod ten97.割りたいときに使う
const inv2ten97: u128 = 500_000_004;
fn main() {
let (n, m): (usize, usize) = parse_line().unwrap();
let mut aaa: Vec<Vec<char>> = vec![];
for _ in 0..2 * n {
let aa: String = parse_line().unwrap();
let aa: Vec<char> = aa.chars().collect_vec();
aaa.push(aa);
}
let mut katikazu: Vec<(Reverse<usize>, usize)> = vec![];
for i in 1..=2 * n {
katikazu.push((Reverse(0), i));
}
for j in 0..m {
katikazu.sort();
for i in 0..n {
let a = katikazu[2 * i];
let b = katikazu[2 * i + 1];
let (aa, bb) = battle(aaa[a.1 - 1][j], aaa[b.1 - 1][j]);
let tmp = katikazu[2 * i].0;
katikazu[2 * i].0 = Reverse(tmp.0 + aa);
let tmp = katikazu[2 * i + 1].0;
katikazu[2 * i + 1].0 = Reverse(tmp.0 + bb);
}
// println!("{:?}", &katikazu);
}
katikazu.sort();
for k in 0..2 * n {
println!("{}", katikazu[k].1);
}
}
fn battle(a: char, b: char) -> (usize, usize) {
if (a == 'G' && b == 'C') || (a == 'C' && b == 'P') || (a == 'P' && b == 'G') {
(1, 0)
} else if (b == 'G' && a == 'C') || (b == 'C' && a == 'P') || (b == 'P' && a == 'G') {
(0, 1)
} else {
(0, 0)
}
}
|
fn check_slope(ski_map : &Vec<Vec<char>>, dx : usize, dy : usize) -> u32 {
let mut x = 0;
let mut y = 0;
let mut tree_count = 0;
while y < ski_map.len() {
if ski_map[y][x] == '#' {
tree_count += 1;
}
x = (x + dx) % (ski_map[0].len());
y += dy;
}
return tree_count;
}
fn main() {
let mut ski_map = Vec::new();
if let Ok(lines) = aoc::read_lines("./day3.txt") {
for line in lines {
if let Ok(line) = line {
ski_map.push(line.chars().collect::<Vec<_>>());
}
}
}
println!("Trees: {}", check_slope(&ski_map, 3, 1));
let mut product : u64 = 1;
for (dx, dy) in [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)].iter() {
product *= check_slope(&ski_map, *dx, *dy) as u64;
}
println!("Trees Product: {}", product);
}
|
use actix_web::{middleware, web, App, HttpRequest, HttpResponse, HttpServer, Responder};
use env_logger;
mod routing;
use dotenv;
use serde::Serialize;
use sqlx::postgres::PgPoolOptions;
mod auth;
#[derive(Serialize)]
struct ErrorResp<'a> {
message: &'a str,
}
pub async fn resp_not_found() -> HttpResponse {
HttpResponse::NotFound().json(ErrorResp {
message: "Page not found",
})
}
async fn greet(_req: HttpRequest) -> impl Responder {
println!("HELLO");
HttpResponse::Ok().json(ErrorResp {
message: "HELLO WORLD",
})
}
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
std::env::set_var("RUST_LOG", "actix_web=debug,actix_server=info");
std::env::set_var("RUST_BACKTRACE", "1");
//dotenv::dotenv().unwrap();
let pool = PgPoolOptions::new()
.max_connections(10)
.connect(&std::env::var("DATABASE_URL").expect("DATABASE_URL not set"))
.await
.unwrap();
env_logger::init();
HttpServer::new(move || {
App::new()
.data(pool.clone())
.route("/", web::get().to(greet))
.wrap(auth::RequiresAuth)
.configure(routing::init_routes)
.default_service(web::route().to(resp_not_found))
.wrap(middleware::Logger::default())
})
.bind("0.0.0.0:8000")?
.run()
.await
}
|
extern crate aoc;
use std::cmp;
use std::fs::File;
use std::io::prelude::*;
use std::io::{self, BufReader};
#[derive(Debug)]
struct Claim {
id: u32,
left: u32,
top: u32,
width: u32,
height: u32,
}
fn to_claim(line: String) -> Result<Claim, io::Error> {
let index_at = line
.find('@')
.ok_or(io::Error::from(io::ErrorKind::InvalidData))?;
let id = line[1..index_at - 1]
.parse()
.map_err(|_| io::Error::from(io::ErrorKind::InvalidData))?;
let index_comma = line
.find(',')
.ok_or(io::Error::from(io::ErrorKind::InvalidData))?;
let left = line[index_at + 2..index_comma]
.parse()
.map_err(|_| io::Error::from(io::ErrorKind::InvalidData))?;
let index_colon = line
.find(':')
.ok_or(io::Error::from(io::ErrorKind::InvalidData))?;
let top = line[index_comma + 1..index_colon]
.parse()
.map_err(|_| io::Error::from(io::ErrorKind::InvalidData))?;
let index_x = line
.find('x')
.ok_or(io::Error::from(io::ErrorKind::InvalidData))?;
let width = line[index_colon + 2..index_x]
.parse()
.map_err(|_| io::Error::from(io::ErrorKind::InvalidData))?;
let height = line[index_x + 1..]
.parse()
.map_err(|_| io::Error::from(io::ErrorKind::InvalidData))?;
Ok(Claim {
id,
left,
top,
width,
height,
})
}
fn parse_input(file_name: &str) -> Result<Vec<Claim>, io::Error> {
let mut file = File::open(file_name)?;
let reader = BufReader::new(&mut file);
Ok(reader
.lines()
.map(|line| line.unwrap())
.map(to_claim)
.map(|claim| claim.unwrap())
.collect::<Vec<_>>())
}
fn main() -> Result<(), io::Error> {
let arg = aoc::get_cmdline_arg()?;
let claims = parse_input(&arg)?;
let mut min_left = std::u32::MAX;
let mut min_top = std::u32::MAX;
let mut max_right = 0;
let mut max_bottom = 0;
for c in &claims {
min_left = cmp::min(c.left, min_left);
min_top = cmp::min(c.top, min_top);
max_right = cmp::max(c.left + c.width, max_right);
max_bottom = cmp::max(c.top + c.height, max_bottom);
}
let mut fabric =
vec![vec![0u32; (max_bottom - min_top) as usize]; (max_right - min_left) as usize];
for c in &claims {
for i in c.left..(c.left + c.width) {
for j in c.top..(c.top + c.height) {
fabric[(i - min_left) as usize][(j - min_top) as usize] += 1;
}
}
}
let mut inches = 0;
for i in &fabric {
for j in i {
if *j > 1 {
inches += 1;
}
}
}
println!("inches: {}", inches);
for c in claims {
let mut count = 0;
for i in c.left..(c.left + c.width) {
for j in c.top..(c.top + c.height) {
count += fabric[(i - min_left) as usize][(j - min_top) as usize];
}
}
if count == (c.width * c.height) {
println!("id: {}", c.id);
break;
}
}
Ok(())
}
|
use candy_frontend::id::CountableId;
use candy_vm::fiber::FiberId;
use extension_trait::extension_trait;
#[extension_trait]
pub impl FiberIdThreadIdConversion for FiberId {
fn from_thread_id(id: usize) -> Self {
Self::from_usize(id)
}
fn to_thread_id(self) -> usize {
self.to_usize()
}
}
|
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtCore/qsysinfo.h
// dst-file: /src/core/qsysinfo.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block begin =>
// <= main block end
// use block begin =>
use std::ops::Deref;
use super::qstring::*; // 773
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QSysInfo_Class_Size() -> c_int;
// proto: static QString QSysInfo::kernelType();
fn C_ZN8QSysInfo10kernelTypeEv() -> *mut c_void;
// proto: static QString QSysInfo::productType();
fn C_ZN8QSysInfo11productTypeEv() -> *mut c_void;
// proto: static QString QSysInfo::prettyProductName();
fn C_ZN8QSysInfo17prettyProductNameEv() -> *mut c_void;
// proto: static QString QSysInfo::currentCpuArchitecture();
fn C_ZN8QSysInfo22currentCpuArchitectureEv() -> *mut c_void;
// proto: static QString QSysInfo::buildCpuArchitecture();
fn C_ZN8QSysInfo20buildCpuArchitectureEv() -> *mut c_void;
// proto: static QString QSysInfo::kernelVersion();
fn C_ZN8QSysInfo13kernelVersionEv() -> *mut c_void;
// proto: static QString QSysInfo::productVersion();
fn C_ZN8QSysInfo14productVersionEv() -> *mut c_void;
// proto: static QString QSysInfo::buildAbi();
fn C_ZN8QSysInfo8buildAbiEv() -> *mut c_void;
} // <= ext block end
// body block begin =>
// class sizeof(QSysInfo)=1
#[derive(Default)]
pub struct QSysInfo {
// qbase: None,
pub qclsinst: u64 /* *mut c_void*/,
}
impl /*struct*/ QSysInfo {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QSysInfo {
return QSysInfo{qclsinst: qthis, ..Default::default()};
}
}
// proto: static QString QSysInfo::kernelType();
impl /*struct*/ QSysInfo {
pub fn kernelType_s<RetType, T: QSysInfo_kernelType_s<RetType>>( overload_args: T) -> RetType {
return overload_args.kernelType_s();
// return 1;
}
}
pub trait QSysInfo_kernelType_s<RetType> {
fn kernelType_s(self ) -> RetType;
}
// proto: static QString QSysInfo::kernelType();
impl<'a> /*trait*/ QSysInfo_kernelType_s<QString> for () {
fn kernelType_s(self ) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QSysInfo10kernelTypeEv()};
let mut ret = unsafe {C_ZN8QSysInfo10kernelTypeEv()};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static QString QSysInfo::productType();
impl /*struct*/ QSysInfo {
pub fn productType_s<RetType, T: QSysInfo_productType_s<RetType>>( overload_args: T) -> RetType {
return overload_args.productType_s();
// return 1;
}
}
pub trait QSysInfo_productType_s<RetType> {
fn productType_s(self ) -> RetType;
}
// proto: static QString QSysInfo::productType();
impl<'a> /*trait*/ QSysInfo_productType_s<QString> for () {
fn productType_s(self ) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QSysInfo11productTypeEv()};
let mut ret = unsafe {C_ZN8QSysInfo11productTypeEv()};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static QString QSysInfo::prettyProductName();
impl /*struct*/ QSysInfo {
pub fn prettyProductName_s<RetType, T: QSysInfo_prettyProductName_s<RetType>>( overload_args: T) -> RetType {
return overload_args.prettyProductName_s();
// return 1;
}
}
pub trait QSysInfo_prettyProductName_s<RetType> {
fn prettyProductName_s(self ) -> RetType;
}
// proto: static QString QSysInfo::prettyProductName();
impl<'a> /*trait*/ QSysInfo_prettyProductName_s<QString> for () {
fn prettyProductName_s(self ) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QSysInfo17prettyProductNameEv()};
let mut ret = unsafe {C_ZN8QSysInfo17prettyProductNameEv()};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static QString QSysInfo::currentCpuArchitecture();
impl /*struct*/ QSysInfo {
pub fn currentCpuArchitecture_s<RetType, T: QSysInfo_currentCpuArchitecture_s<RetType>>( overload_args: T) -> RetType {
return overload_args.currentCpuArchitecture_s();
// return 1;
}
}
pub trait QSysInfo_currentCpuArchitecture_s<RetType> {
fn currentCpuArchitecture_s(self ) -> RetType;
}
// proto: static QString QSysInfo::currentCpuArchitecture();
impl<'a> /*trait*/ QSysInfo_currentCpuArchitecture_s<QString> for () {
fn currentCpuArchitecture_s(self ) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QSysInfo22currentCpuArchitectureEv()};
let mut ret = unsafe {C_ZN8QSysInfo22currentCpuArchitectureEv()};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static QString QSysInfo::buildCpuArchitecture();
impl /*struct*/ QSysInfo {
pub fn buildCpuArchitecture_s<RetType, T: QSysInfo_buildCpuArchitecture_s<RetType>>( overload_args: T) -> RetType {
return overload_args.buildCpuArchitecture_s();
// return 1;
}
}
pub trait QSysInfo_buildCpuArchitecture_s<RetType> {
fn buildCpuArchitecture_s(self ) -> RetType;
}
// proto: static QString QSysInfo::buildCpuArchitecture();
impl<'a> /*trait*/ QSysInfo_buildCpuArchitecture_s<QString> for () {
fn buildCpuArchitecture_s(self ) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QSysInfo20buildCpuArchitectureEv()};
let mut ret = unsafe {C_ZN8QSysInfo20buildCpuArchitectureEv()};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static QString QSysInfo::kernelVersion();
impl /*struct*/ QSysInfo {
pub fn kernelVersion_s<RetType, T: QSysInfo_kernelVersion_s<RetType>>( overload_args: T) -> RetType {
return overload_args.kernelVersion_s();
// return 1;
}
}
pub trait QSysInfo_kernelVersion_s<RetType> {
fn kernelVersion_s(self ) -> RetType;
}
// proto: static QString QSysInfo::kernelVersion();
impl<'a> /*trait*/ QSysInfo_kernelVersion_s<QString> for () {
fn kernelVersion_s(self ) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QSysInfo13kernelVersionEv()};
let mut ret = unsafe {C_ZN8QSysInfo13kernelVersionEv()};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static QString QSysInfo::productVersion();
impl /*struct*/ QSysInfo {
pub fn productVersion_s<RetType, T: QSysInfo_productVersion_s<RetType>>( overload_args: T) -> RetType {
return overload_args.productVersion_s();
// return 1;
}
}
pub trait QSysInfo_productVersion_s<RetType> {
fn productVersion_s(self ) -> RetType;
}
// proto: static QString QSysInfo::productVersion();
impl<'a> /*trait*/ QSysInfo_productVersion_s<QString> for () {
fn productVersion_s(self ) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QSysInfo14productVersionEv()};
let mut ret = unsafe {C_ZN8QSysInfo14productVersionEv()};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static QString QSysInfo::buildAbi();
impl /*struct*/ QSysInfo {
pub fn buildAbi_s<RetType, T: QSysInfo_buildAbi_s<RetType>>( overload_args: T) -> RetType {
return overload_args.buildAbi_s();
// return 1;
}
}
pub trait QSysInfo_buildAbi_s<RetType> {
fn buildAbi_s(self ) -> RetType;
}
// proto: static QString QSysInfo::buildAbi();
impl<'a> /*trait*/ QSysInfo_buildAbi_s<QString> for () {
fn buildAbi_s(self ) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QSysInfo8buildAbiEv()};
let mut ret = unsafe {C_ZN8QSysInfo8buildAbiEv()};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// <= body block end
|
use std::collections::{HashMap, HashSet};
use std::iter;
use std::slice::{Iter, IterMut};
use interpreter::{Action, Condition, Output};
use interpreter::{Empty, True};
pub type StateID = Vec<usize>;
pub type StateLabel = String;
pub trait Node {
fn id(&self) -> &StateID;
fn label(&self) -> &StateLabel;
fn substate(&self, label: &str) -> Option<&State>;
fn initial(&self) -> Option<&StateLabel>;
fn parent(&self) -> Option<&StateID>;
fn on_entry(&self) -> &Vec<Action>;
fn on_exit(&self) -> &Vec<Action>;
}
pub trait ActiveNode: Node {
fn transitions(&self) -> &Vec<Transition>;
}
#[derive(Debug, Clone, Builder)]
pub struct Atomic {
#[builder(default="vec![]")]
id: StateID,
#[builder(setter(into))]
label: StateLabel,
#[builder(default="vec![]")]
on_entry: Vec<Action>,
#[builder(default="vec![]")]
on_exit: Vec<Action>,
#[builder(default="vec![]")]
transitions: Vec<Transition>,
#[builder(setter(skip))]
parent: Option<StateID>,
}
impl PartialEq for Atomic {
fn eq(&self, other: &Self) -> bool {
(&self.id, &self.label, &self.on_entry, &self.on_exit, &self.transitions) ==
(&other.id, &other.label, &other.on_entry, &other.on_exit, &other.transitions)
}
}
impl Node for Atomic {
fn id(&self) -> &StateID {
&self.id
}
fn label(&self) -> &StateLabel {
&self.label
}
fn substate(&self, _: &str) -> Option<&State> {
None
}
fn initial(&self) -> Option<&StateLabel> {
None
}
fn parent(&self) -> Option<&StateID> {
self.parent.as_ref()
}
fn on_entry(&self) -> &Vec<Action> {
&self.on_entry
}
fn on_exit(&self) -> &Vec<Action> {
&self.on_exit
}
}
impl ActiveNode for Atomic {
fn transitions(&self) -> &Vec<Transition> {
&self.transitions
}
}
impl Atomic {
pub fn node(&self) -> &Node {
self as &Node
}
pub fn active_node(&self) -> &ActiveNode {
self as &ActiveNode
}
}
#[derive(Debug, Clone, Builder)]
pub struct Compound {
#[builder(default="vec![]")]
id: StateID,
#[builder(setter(into))]
label: StateLabel,
#[builder(default="None")]
initial_label: Option<StateLabel>,
#[builder(default="vec![]")]
on_entry: Vec<Action>,
#[builder(default="vec![]")]
on_exit: Vec<Action>,
#[builder(default="vec![]")]
transitions: Vec<Transition>,
#[builder(default="vec![]")]
substates: Vec<State>,
#[builder(setter(skip))]
parent: Option<StateID>,
}
impl PartialEq for Compound {
fn eq(&self, other: &Self) -> bool {
(&self.id,
&self.label,
&self.initial_label,
&self.on_entry,
&self.on_exit,
&self.transitions,
&self.substates) ==
(&other.id,
&other.label,
&other.initial_label,
&other.on_entry,
&other.on_exit,
&other.transitions,
&other.substates)
}
}
impl Node for Compound {
fn id(&self) -> &StateID {
&self.id
}
fn label(&self) -> &StateLabel {
&self.label
}
fn substate(&self, label: &str) -> Option<&State> {
for ss in self.substates.iter() {
if ss.node().label() == label {
return Some(ss);
}
}
None
}
fn initial(&self) -> Option<&StateLabel> {
match self.initial_label {
Some(ref l) => Some(l),
None => {
for ss in self.substates.iter() {
return Some(ss.node().label());
}
None
}
}
}
fn parent(&self) -> Option<&StateID> {
self.parent.as_ref()
}
fn on_entry(&self) -> &Vec<Action> {
&self.on_entry
}
fn on_exit(&self) -> &Vec<Action> {
&self.on_exit
}
}
impl ActiveNode for Compound {
fn transitions(&self) -> &Vec<Transition> {
&self.transitions
}
}
impl Compound {
pub fn node(&self) -> &Node {
self as &Node
}
pub fn active_node(&self) -> &ActiveNode {
self as &ActiveNode
}
}
#[derive(Debug, Clone, Builder)]
pub struct Parallel {
#[builder(default="vec![]")]
id: StateID,
#[builder(setter(into))]
label: StateLabel,
#[builder(default="vec![]")]
on_entry: Vec<Action>,
#[builder(default="vec![]")]
on_exit: Vec<Action>,
#[builder(default="vec![]")]
transitions: Vec<Transition>,
#[builder(default="vec![]")]
substates: Vec<State>,
#[builder(setter(skip))]
parent: Option<StateID>,
}
impl PartialEq for Parallel {
fn eq(&self, other: &Self) -> bool {
(&self.id,
&self.label,
&self.on_entry,
&self.on_exit,
&self.transitions,
&self.substates) ==
(&other.id,
&other.label,
&other.on_entry,
&other.on_exit,
&other.transitions,
&other.substates)
}
}
impl Node for Parallel {
fn id(&self) -> &StateID {
&self.id
}
fn label(&self) -> &StateLabel {
&self.label
}
fn substate(&self, label: &str) -> Option<&State> {
for ss in self.substates.iter() {
if ss.node().label() == label {
return Some(ss);
}
}
None
}
fn initial(&self) -> Option<&StateLabel> {
None
}
fn parent(&self) -> Option<&StateID> {
self.parent.as_ref()
}
fn on_entry(&self) -> &Vec<Action> {
&self.on_entry
}
fn on_exit(&self) -> &Vec<Action> {
&self.on_exit
}
}
impl ActiveNode for Parallel {
fn transitions(&self) -> &Vec<Transition> {
&self.transitions
}
}
impl Parallel {
pub fn node(&self) -> &Node {
self as &Node
}
pub fn active_node(&self) -> &ActiveNode {
self as &ActiveNode
}
}
#[derive(Debug, Clone, Builder)]
pub struct Final {
#[builder(default="vec![]")]
id: StateID,
#[builder(setter(into))]
label: StateLabel,
#[builder(default="vec![]")]
on_entry: Vec<Action>,
#[builder(default="vec![]")]
on_exit: Vec<Action>,
#[builder(default="Output::Empty(Empty)")]
result: Output,
#[builder(setter(skip))]
parent: Option<StateID>,
}
impl PartialEq for Final {
fn eq(&self, other: &Self) -> bool {
(&self.id, &self.label, &self.on_entry, &self.on_exit, &self.result) ==
(&other.id, &other.label, &other.on_entry, &other.on_exit, &other.result)
}
}
impl Node for Final {
fn id(&self) -> &StateID {
&self.id
}
fn label(&self) -> &StateLabel {
&self.label
}
fn substate(&self, _: &str) -> Option<&State> {
None
}
fn initial(&self) -> Option<&StateLabel> {
None
}
fn parent(&self) -> Option<&StateID> {
self.parent.as_ref()
}
fn on_entry(&self) -> &Vec<Action> {
&self.on_entry
}
fn on_exit(&self) -> &Vec<Action> {
&self.on_exit
}
}
impl Final {
pub fn node(&self) -> &Node {
self as &Node
}
pub fn result(&self) -> &Output {
&self.result
}
}
#[derive(Debug, PartialEq, Clone)]
pub enum State {
Atomic(Atomic),
Compound(Compound),
Parallel(Parallel),
Final(Final),
}
impl State {
pub fn node(&self) -> &Node {
match self {
&State::Atomic(ref a) => a.node(),
&State::Compound(ref c) => c.node(),
&State::Parallel(ref p) => p.node(),
&State::Final(ref f) => f.node(),
}
}
pub fn active_node(&self) -> Option<&ActiveNode> {
match self {
&State::Atomic(ref a) => Some(a.active_node()),
&State::Compound(ref c) => Some(c.active_node()),
&State::Parallel(ref p) => Some(p.active_node()),
&State::Final(_) => None,
}
}
fn find(&self, id: &StateID) -> Option<&State> {
self.find_from(id, 0)
}
fn find_from(&self, id: &StateID, depth: usize) -> Option<&State> {
if depth == id.len() {
return Some(self);
}
let ss = match self {
&State::Atomic(_) => return None,
&State::Compound(ref c) => &c.substates,
&State::Parallel(ref p) => &p.substates,
&State::Final(_) => return None,
};
if id[depth] < ss.len() {
ss[id[depth]].find_from(id, depth + 1)
} else {
None
}
}
pub fn allstates(st: &State) -> Vec<&State> {
iter::once(st).chain(st.substates().flat_map(|ss| State::allstates(ss))).collect()
}
pub fn substates(&self) -> Iter<State> {
match self {
&State::Atomic(_) => [].iter(),
&State::Compound(ref c) => c.substates.iter(),
&State::Parallel(ref p) => p.substates.iter(),
&State::Final(_) => [].iter(),
}
}
fn substates_mut(&mut self) -> IterMut<State> {
match self {
&mut State::Atomic(_) => [].iter_mut(),
&mut State::Compound(ref mut c) => c.substates.iter_mut(),
&mut State::Parallel(ref mut p) => p.substates.iter_mut(),
&mut State::Final(_) => [].iter_mut(),
}
}
fn set_parent(&mut self, parent: StateID) {
match self {
&mut State::Atomic(ref mut a) => a.parent = Some(parent),
&mut State::Compound(ref mut c) => c.parent = Some(parent),
&mut State::Parallel(ref mut p) => p.parent = Some(parent),
&mut State::Final(ref mut f) => f.parent = Some(parent),
}
}
fn init(st: &mut State, id: StateID) {
{
match st {
&mut State::Atomic(ref mut a) => {
a.id = id;
return;
}
&mut State::Final(ref mut f) => {
f.id = id;
return;
}
&mut State::Compound(ref mut c) => c.id = id.clone(),
&mut State::Parallel(ref mut p) => p.id = id.clone(),
}
}
let mut i = 0;
for ss in st.substates_mut() {
let mut child_id = id.clone();
child_id.push(i);
ss.set_parent(id.clone());
State::init(ss, child_id);
i += 1;
}
}
}
#[derive(Debug, PartialEq, Clone, Builder)]
pub struct Transition {
#[builder(default="HashSet::new()")]
pub topics: HashSet<String>,
#[builder(default="Condition::True(True)")]
pub cond: Condition,
#[builder(default="vec![]")]
pub actions: Vec<Action>,
#[builder(default="None")]
pub target_label: Option<StateLabel>,
}
pub struct Context {
root: State,
state_by_label: HashMap<StateLabel, StateID>,
}
impl Context {
pub fn new(root: State) -> Context {
let mut root = root;
State::init(&mut root, vec![]);
let root = root;
let mut ctx = Context {
root: root,
state_by_label: HashMap::new(),
};
for st in State::allstates(&ctx.root) {
let n = st.node();
ctx.state_by_label.insert(n.label().to_owned(), n.id().clone());
}
ctx
}
pub fn root(&self) -> &State {
&self.root
}
pub fn state(&self, label: &str) -> Option<&State> {
match self.state_by_label.get(label) {
Some(ref id) => self.state_by_id(id),
None => None,
}
}
pub fn state_by_id(&self, id: &StateID) -> Option<&State> {
self.root.find(id)
}
}
#[macro_export]
macro_rules! state {
($label:ident {$($tail:tt)*}) => {{
let mut stb = $crate::ast::AtomicBuilder::default();
stb.label(stringify!($label));
state_props!(stb {$($tail)*});
$crate::ast::State::Atomic(stb.build().unwrap())
}}
}
#[macro_export]
macro_rules! states {
($label:ident {$($tail:tt)*}) => {{
let mut stb = $crate::ast::CompoundBuilder::default();
stb.label(stringify!($label));
state_props!(stb {$($tail)*});
$crate::ast::State::Compound(stb.build().unwrap())
}}
}
#[macro_export]
macro_rules! parallel {
($label:ident {$($tail:tt)*}) => {{
let mut stb = $crate::ast::ParallelBuilder::default();
stb.label(stringify!($label));
state_props!(stb {$($tail)*});
$crate::ast::State::Parallel(stb.build().unwrap())
}}
}
#[macro_export]
macro_rules! final_state {
($label:ident {$($tail:tt)*}) => {{
let mut stb = $crate::ast::FinalBuilder::default();
stb.label(stringify!($label));
state_props!(stb {$($tail)*});
$crate::ast::State::Final(stb.build().unwrap())
}}
}
#[macro_export]
macro_rules! state_props {
($stb:ident {$key:ident: $value:expr}) => {
state_prop!($stb, $key, $value);
};
($stb:ident {$key:ident: $value:expr, $($tail:tt)*}) => {
state_prop!($stb, $key, $value);
state_props!($stb {$($tail)*});
};
($stb:ident {}) => {}
}
#[macro_export]
macro_rules! state_prop {
($stb:ident, substates, $value:expr) => {
$stb.substates($value.iter().cloned().collect());
};
($stb:ident, on_entry, $value:expr) => {
$stb.on_entry($value.iter().cloned().collect());
};
($stb:ident, on_exit, $value:expr) => {
$stb.on_exit($value.iter().cloned().collect());
};
($stb:ident, transitions, $value:expr) => {
$stb.transitions($value.iter().cloned().collect());
};
($stb:ident, $key:ident, $value:expr) => {
$stb.$key($value);
}
}
#[macro_export]
macro_rules! goto {
(@props $t:ident, $key:ident: $value:expr) => {
goto!{@prop $t, $key, $value};
};
(@props $t:ident, $key:ident: $value:expr, $($tail:tt)*) => {
goto!{@prop $t, $key, $value};
goto!{@props $t, $($tail)*};
};
(@prop $t:ident, target, $value:ident) => {
$t.target_label(Some(stringify!($value).to_owned()));
};
(@prop $t:ident, topics, $value:expr) => {
$t.topics($value.iter().map(|x|{x.to_string()}).collect());
};
(@prop $t:ident, actions, $value:expr) => {
$t.actions($value.iter().cloned().collect());
};
(@prop $t:ident, $key:ident, $value:expr) => {
$t.$key($value);
};
($key:ident: $value:tt) => {{
let mut t = $crate::ast::TransitionBuilder::default();
goto!{@prop t, $key, $value};
t.build().unwrap()
}};
($key:ident: $value:tt, $($tail:tt)*) => {{
let mut t = $crate::ast::TransitionBuilder::default();
goto!{@prop t, $key, $value};
goto!{@props t, $($tail)*};
t.build().unwrap()
}};
}
|
use regex::Regex;
pub fn regex_em() {
let re = Regex::new(r"[a-z]+(?:([0-9]+)|([A-Z]+))").unwrap();
let caps = re.captures("abc123").unwrap();
let text1 = caps.get(1).map_or("", |m| m.as_str());
let text2 = caps.get(2).map_or("", |m| m.as_str());
assert_eq!(text1, "123");
assert_eq!(text2, "");
} |
extern crate actix_web;
use actix_web::{server, App, HttpRequest, HttpResponse, http, Json};
#[macro_use] extern crate serde_derive;
#[derive(Debug, Deserialize, Serialize)]
struct UserLogin {
username: String,
password: String
}
#[derive(Debug, Deserialize, Serialize)]
struct User {
username: String,
password: String,
desc: String
}
fn index(req: &HttpRequest) -> HttpResponse {
HttpResponse::Ok()
.body("Index route wut")
}
fn handle_login(data: Json<UserLogin>) -> Json<User>{
let user = User{
username: data.username.to_string(),
password: data.password.to_string(),
desc: "This is the description tho".to_string()
};
Json(user)
}
fn main() {
server::new(|| App::new()
.resource("/", |r| r.f(index))
.resource("/login", |r| r.method(http::Method::POST).with(handle_login)))
.bind("127.0.0.1:3001")
.unwrap()
.run();
} |
#[derive(Debug)]
pub enum WardenError {
KAUTH_REGISTRATION,
}
|
use std::collections::HashMap;
#[derive(Debug)]
pub struct RedisAccessorError {
pub err_type: RedisAccessorErrorType
}
#[derive(Debug)]
pub enum RedisAccessorErrorType {
ConnNotOpen,
OpenConnError,
AuthError,
GetContentError,
GetKeyNotExist,
SetContentError
}
pub trait RedisAccessor {
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.